repo_name
stringlengths 5
92
| path
stringlengths 4
221
| copies
stringclasses 19
values | size
stringlengths 4
6
| content
stringlengths 766
896k
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 32
997
| alpha_frac
float64 0.25
0.96
| autogenerated
bool 1
class | ratio
float64 1.5
13.6
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
DedMemez/ODS-August-2017
|
suit/SuitDNA.py
|
1
|
7589
|
# Fuck you Disyer. Stealing my fucking paypal. GET FUCKED: toontown.suit.SuitDNA
from panda3d.core import Datagram, DatagramIterator, VBase4
import random
from direct.directnotify.DirectNotifyGlobal import *
from toontown.toonbase import TTLocalizer, ToontownGlobals
import random
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
notify = directNotify.newCategory('SuitDNA')
suitHeadTypes = ['f',
'p',
'ym',
'mm',
'ds',
'hh',
'cr',
'tbc',
'bf',
'b',
'dt',
'ac',
'bs',
'sd',
'le',
'bw',
'sc',
'pp',
'tw',
'bc',
'nc',
'mb',
'ls',
'rb',
'cc',
'tm',
'nd',
'gh',
'ms',
'tf',
'm',
'mh',
'sk',
'cm',
'vp',
'db',
'kc',
'ss',
'iw',
'ru']
suitATypes = ['ym',
'hh',
'tbc',
'dt',
'bs',
'le',
'bw',
'pp',
'nc',
'rb',
'nd',
'tf',
'm',
'mh',
'vp',
'ss',
'ru']
suitBTypes = ['p',
'ds',
'b',
'ac',
'sd',
'bc',
'ls',
'tm',
'ms',
'kc',
'iw']
suitCTypes = ['f',
'mm',
'cr',
'bf',
'sc',
'tw',
'mb',
'cc',
'gh',
'sk',
'cm',
'db']
suitDepts = ['c',
'l',
'm',
's',
't']
suitDeptZones = [ToontownGlobals.BossbotHQ,
ToontownGlobals.LawbotHQ,
ToontownGlobals.CashbotHQ,
ToontownGlobals.SellbotHQ,
ToontownGlobals.TechbotHQ]
suitDeptFullnames = {'c': TTLocalizer.Bossbot,
'l': TTLocalizer.Lawbot,
'm': TTLocalizer.Cashbot,
's': TTLocalizer.Sellbot,
't': TTLocalizer.Techbot}
suitDeptFullnamesP = {'c': TTLocalizer.BossbotP,
'l': TTLocalizer.LawbotP,
'm': TTLocalizer.CashbotP,
's': TTLocalizer.SellbotP,
't': TTLocalizer.TechbotP}
suitDeptFilenames = {'c': 'boss',
'l': 'law',
'm': 'cash',
's': 'sell',
't': 'tech'}
suitDeptModelPaths = {'c': '**/CorpIcon',
0: '**/CorpIcon',
'l': '**/LegalIcon',
1: '**/LegalIcon',
'm': '**/MoneyIcon',
2: '**/MoneyIcon',
's': '**/SalesIcon',
3: '**/SalesIcon',
't': '**/TechIcon',
4: '**/TechIcon'}
corpPolyColor = VBase4(0.95, 0.75, 0.75, 1.0)
legalPolyColor = VBase4(0.75, 0.75, 0.95, 1.0)
moneyPolyColor = VBase4(0.65, 0.95, 0.85, 1.0)
salesPolyColor = VBase4(0.95, 0.75, 0.95, 1.0)
techPolyColor = VBase4(0.6, 0.48, 0.7, 1.0)
suitDeptColors = {'c': corpPolyColor,
'l': legalPolyColor,
'm': moneyPolyColor,
's': salesPolyColor,
't': techPolyColor}
suitsPerLevel = [1,
1,
1,
1,
1,
1,
1,
1]
suitsPerDept = 8
goonTypes = ['pg', 'sg', 'fg1']
def getSuitBodyType(name):
if name in suitATypes:
return 'a'
if name in suitBTypes:
return 'b'
if name in suitCTypes:
return 'c'
print 'Unknown body type for suit name: ', name
def getSuitDept(name):
index = suitHeadTypes.index(name)
for dept in xrange(len(suitDepts)):
if index < suitsPerDept * (dept + 1):
return suitDepts[dept]
print 'Unknown dept for suit name: ', name
def getDeptFullname(dept):
return suitDeptFullnames[dept]
def getDeptFullnameP(dept):
return suitDeptFullnamesP[dept]
def getSuitDeptFullname(name):
return suitDeptFullnames[getSuitDept(name)]
def getSuitType(name):
index = suitHeadTypes.index(name)
return index % suitsPerDept + 1
def getSuitName(deptIndex, typeIndex):
return suitHeadTypes[suitsPerDept * deptIndex + typeIndex]
def getRandomSuitType(level, rng = random):
return random.randint(max(level - 4, 1), min(level, 8))
def getRandomIndexByDept(dept):
return suitsPerDept * suitDepts.index(dept) + random.randint(0, suitsPerDept - 1)
def getRandomSuitByDept(dept):
return suitHeadTypes[getRandomIndexByDept(dept)]
def getSuitsInDept(dept):
start = dept * suitsPerDept
end = start + suitsPerDept
return suitHeadTypes[start:end]
def getLevelByIndex(index):
return index % suitsPerDept + 1
class SuitDNA:
def __init__(self, str = None, type = None, dna = None, r = None, b = None, g = None):
if str != None:
self.makeFromNetString(str)
elif type != None:
if type == 's':
self.newSuit()
else:
self.type = 'u'
return
def __str__(self):
if self.type == 's':
return 'type = %s\nbody = %s, dept = %s, name = %s' % ('suit',
self.body,
self.dept,
self.name)
elif self.type == 'b':
return 'type = boss cog\ndept = %s' % self.dept
else:
return 'type undefined'
def makeNetString(self):
dg = PyDatagram()
dg.addFixedString(self.type, 1)
if self.type == 's':
dg.addFixedString(self.name, 3)
dg.addFixedString(self.dept, 1)
elif self.type == 'b':
dg.addFixedString(self.dept, 1)
elif self.type == 'u':
notify.error('undefined avatar')
else:
notify.error('unknown avatar type: ', self.type)
return dg.getMessage()
def makeFromNetString(self, string):
dg = PyDatagram(string)
dgi = PyDatagramIterator(dg)
self.type = dgi.getFixedString(1)
if self.type == 's':
self.name = dgi.getFixedString(3)
self.dept = dgi.getFixedString(1)
self.body = getSuitBodyType(self.name)
elif self.type == 'b':
self.dept = dgi.getFixedString(1)
else:
notify.error('unknown avatar type: ', self.type)
return None
def __defaultGoon(self):
self.type = 'g'
self.name = goonTypes[0]
def __defaultSuit(self):
self.type = 's'
self.name = 'ds'
self.dept = getSuitDept(self.name)
self.body = getSuitBodyType(self.name)
def newSuit(self, name = None):
if name == None:
self.__defaultSuit()
else:
self.type = 's'
self.name = name
self.dept = getSuitDept(self.name)
self.body = getSuitBodyType(self.name)
return
def newBossCog(self, dept):
self.type = 'b'
self.dept = dept
def newSuitRandom(self, level = None, dept = None):
self.type = 's'
if level == None:
level = random.choice(range(1, len(suitsPerLevel)))
elif level < 0 or level > len(suitsPerLevel):
notify.error('Invalid suit level: %d' % level)
if dept == None:
dept = random.choice(suitDepts)
self.dept = dept
index = suitDepts.index(dept)
base = index * suitsPerDept
offset = 0
if level > 1:
for i in xrange(1, level):
offset = offset + suitsPerLevel[i - 1]
bottom = base + offset
top = bottom + suitsPerLevel[level - 1]
self.name = suitHeadTypes[random.choice(range(bottom, top))]
self.body = getSuitBodyType(self.name)
return
def newGoon(self, name = None):
if type == None:
self.__defaultGoon()
else:
self.type = 'g'
if name in goonTypes:
self.name = name
else:
notify.error('unknown goon type: ', name)
return
def getType(self):
if self.type == 's':
type = 'suit'
elif self.type == 'b':
type = 'boss'
else:
notify.error('Invalid DNA type: ', self.type)
return type
|
apache-2.0
| 5,145,229,808,531,475,000
| 21.501548
| 90
| 0.548557
| false
| 2.940333
| false
| false
| false
|
tswast/google-cloud-python
|
videointelligence/google/cloud/videointelligence_v1/gapic/video_intelligence_service_client.py
|
1
|
14088
|
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.
"""Accesses the google.cloud.videointelligence.v1 VideoIntelligenceService API."""
import pkg_resources
import warnings
from google.oauth2 import service_account
import google.api_core.client_options
import google.api_core.gapic_v1.client_info
import google.api_core.gapic_v1.config
import google.api_core.gapic_v1.method
import google.api_core.grpc_helpers
import google.api_core.operation
import google.api_core.operations_v1
import grpc
from google.cloud.videointelligence_v1.gapic import enums
from google.cloud.videointelligence_v1.gapic import (
video_intelligence_service_client_config,
)
from google.cloud.videointelligence_v1.gapic.transports import (
video_intelligence_service_grpc_transport,
)
from google.cloud.videointelligence_v1.proto import video_intelligence_pb2
from google.cloud.videointelligence_v1.proto import video_intelligence_pb2_grpc
from google.longrunning import operations_pb2
_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(
"google-cloud-videointelligence"
).version
class VideoIntelligenceServiceClient(object):
"""Service that implements Google Cloud Video Intelligence API."""
SERVICE_ADDRESS = "videointelligence.googleapis.com:443"
"""The default address of the service."""
# The name of the interface for this client. This is the key used to
# find the method configuration in the client_config dictionary.
_INTERFACE_NAME = "google.cloud.videointelligence.v1.VideoIntelligenceService"
@classmethod
def from_service_account_file(cls, filename, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
VideoIntelligenceServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
def __init__(
self,
transport=None,
channel=None,
credentials=None,
client_config=None,
client_info=None,
client_options=None,
):
"""Constructor.
Args:
transport (Union[~.VideoIntelligenceServiceGrpcTransport,
Callable[[~.Credentials, type], ~.VideoIntelligenceServiceGrpcTransport]): A transport
instance, responsible for actually making the API calls.
The default transport uses the gRPC protocol.
This argument may also be a callable which returns a
transport instance. Callables will be sent the credentials
as the first argument and the default transport class as
the second argument.
channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
through which to make calls. This argument is mutually exclusive
with ``credentials``; providing both will raise an exception.
credentials (google.auth.credentials.Credentials): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is mutually exclusive with providing a
transport instance to ``transport``; doing so will raise
an exception.
client_config (dict): DEPRECATED. A dictionary of call options for
each method. If not specified, the default configuration is used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
client_options (Union[dict, google.api_core.client_options.ClientOptions]):
Client options used to set user options on the client. API Endpoint
should be set through client_options.
"""
# Raise deprecation warnings for things we want to go away.
if client_config is not None:
warnings.warn(
"The `client_config` argument is deprecated.",
PendingDeprecationWarning,
stacklevel=2,
)
else:
client_config = video_intelligence_service_client_config.config
if channel:
warnings.warn(
"The `channel` argument is deprecated; use " "`transport` instead.",
PendingDeprecationWarning,
stacklevel=2,
)
api_endpoint = self.SERVICE_ADDRESS
if client_options:
if type(client_options) == dict:
client_options = google.api_core.client_options.from_dict(
client_options
)
if client_options.api_endpoint:
api_endpoint = client_options.api_endpoint
# Instantiate the transport.
# The transport is responsible for handling serialization and
# deserialization and actually sending data to the service.
if transport:
if callable(transport):
self.transport = transport(
credentials=credentials,
default_class=video_intelligence_service_grpc_transport.VideoIntelligenceServiceGrpcTransport,
address=api_endpoint,
)
else:
if credentials:
raise ValueError(
"Received both a transport instance and "
"credentials; these are mutually exclusive."
)
self.transport = transport
else:
self.transport = video_intelligence_service_grpc_transport.VideoIntelligenceServiceGrpcTransport(
address=api_endpoint, channel=channel, credentials=credentials
)
if client_info is None:
client_info = google.api_core.gapic_v1.client_info.ClientInfo(
gapic_version=_GAPIC_LIBRARY_VERSION
)
else:
client_info.gapic_version = _GAPIC_LIBRARY_VERSION
self._client_info = client_info
# Parse out the default settings for retry and timeout for each RPC
# from the client configuration.
# (Ordinarily, these are the defaults specified in the `*_config.py`
# file next to this one.)
self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
client_config["interfaces"][self._INTERFACE_NAME]
)
# Save a dictionary of cached API call functions.
# These are the actual callables which invoke the proper
# transport methods, wrapped with `wrap_method` to add retry,
# timeout, and the like.
self._inner_api_calls = {}
# Service calls
def annotate_video(
self,
input_uri=None,
input_content=None,
features=None,
video_context=None,
output_uri=None,
location_id=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Performs asynchronous video annotation. Progress and results can be
retrieved through the ``google.longrunning.Operations`` interface.
``Operation.metadata`` contains ``AnnotateVideoProgress`` (progress).
``Operation.response`` contains ``AnnotateVideoResponse`` (results).
Example:
>>> from google.cloud import videointelligence_v1
>>> from google.cloud.videointelligence_v1 import enums
>>>
>>> client = videointelligence_v1.VideoIntelligenceServiceClient()
>>>
>>> input_uri = 'gs://cloud-samples-data/video/cat.mp4'
>>> features_element = enums.Feature.LABEL_DETECTION
>>> features = [features_element]
>>>
>>> response = client.annotate_video(input_uri=input_uri, features=features)
>>>
>>> def callback(operation_future):
... # Handle result.
... result = operation_future.result()
>>>
>>> response.add_done_callback(callback)
>>>
>>> # Handle metadata.
>>> metadata = response.metadata()
Args:
input_uri (str): Input video location. Currently, only `Google Cloud
Storage <https://cloud.google.com/storage/>`__ URIs are supported, which
must be specified in the following format: ``gs://bucket-id/object-id``
(other URI formats return ``google.rpc.Code.INVALID_ARGUMENT``). For
more information, see `Request
URIs <https://cloud.google.com/storage/docs/reference-uris>`__. A video
URI may include wildcards in ``object-id``, and thus identify multiple
videos. Supported wildcards: '\*' to match 0 or more characters; '?' to
match 1 character. If unset, the input video should be embedded in the
request as ``input_content``. If set, ``input_content`` should be unset.
input_content (bytes): The video data bytes. If unset, the input video(s) should be specified
via ``input_uri``. If set, ``input_uri`` should be unset.
features (list[~google.cloud.videointelligence_v1.types.Feature]): Required. Requested video annotation features.
video_context (Union[dict, ~google.cloud.videointelligence_v1.types.VideoContext]): Additional video context and/or feature-specific parameters.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.videointelligence_v1.types.VideoContext`
output_uri (str): Optional. Location where the output (in JSON format) should be stored.
Currently, only `Google Cloud
Storage <https://cloud.google.com/storage/>`__ URIs are supported, which
must be specified in the following format: ``gs://bucket-id/object-id``
(other URI formats return ``google.rpc.Code.INVALID_ARGUMENT``). For
more information, see `Request
URIs <https://cloud.google.com/storage/docs/reference-uris>`__.
location_id (str): Optional. Cloud region where annotation should take place. Supported
cloud regions: ``us-east1``, ``us-west1``, ``europe-west1``,
``asia-east1``. If no region is specified, a region will be determined
based on video file location.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will
be retried using a default configuration.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.videointelligence_v1.types._OperationFuture` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if "annotate_video" not in self._inner_api_calls:
self._inner_api_calls[
"annotate_video"
] = google.api_core.gapic_v1.method.wrap_method(
self.transport.annotate_video,
default_retry=self._method_configs["AnnotateVideo"].retry,
default_timeout=self._method_configs["AnnotateVideo"].timeout,
client_info=self._client_info,
)
request = video_intelligence_pb2.AnnotateVideoRequest(
input_uri=input_uri,
input_content=input_content,
features=features,
video_context=video_context,
output_uri=output_uri,
location_id=location_id,
)
operation = self._inner_api_calls["annotate_video"](
request, retry=retry, timeout=timeout, metadata=metadata
)
return google.api_core.operation.from_gapic(
operation,
self.transport._operations_client,
video_intelligence_pb2.AnnotateVideoResponse,
metadata_type=video_intelligence_pb2.AnnotateVideoProgress,
)
|
apache-2.0
| -8,513,084,120,351,419,000
| 45.039216
| 156
| 0.626704
| false
| 4.681954
| true
| false
| false
|
BeeeOn/server
|
t/restui/t1007-types-list-detail.py
|
1
|
10281
|
#! /usr/bin/env python3
import config
config.import_libs()
import unittest
import socket
import json
from rest import GET, POST, PUT, DELETE
class TestTypesListDetail(unittest.TestCase):
"""
Create a session for testing.
"""
def setUp(self):
req = POST(config.ui_host, config.ui_port, "/auth")
req.body(config.PERMIT_LOGIN)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
self.session = result["data"]["id"]
def tearDown(self):
req = DELETE(config.ui_host, config.ui_port, "/auth")
req.authorize(self.session)
response, content = req()
self.assertEqual(204, response.status)
"""
List all available types.
"""
def test1_list_all(self):
req = GET(config.ui_host, config.ui_port, "/types")
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
self.assertEqual(30, len(result["data"]))
def test2_detail_of_non_existing(self):
req = GET(config.ui_host, config.ui_port, "/types/12904232")
req.authorize(self.session)
response, content = req()
self.assertEqual(404, response.status)
result = json.loads(content)
self.assertEqual("error", result["status"])
self.assertEqual("requested resource does not exist", result["message"])
def test3_detail_of_battery(self):
req = GET(config.ui_host, config.ui_port, "/types/battery")
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
self.assertEqual("battery", result["data"]["name"])
self.assertEqual("%", result["data"]["unit"])
def assure_range(self, id, name, min, max, step):
req = GET(config.ui_host, config.ui_port, "/types/" + id)
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
type = result["data"]
self.assertEqual(name, type["name"])
self.assertTrue("range" in type)
if min is not None:
self.assertTrue("min" in type["range"])
self.assertEqual(min, type["range"]["min"])
else:
self.assertFalse("min" in type["range"])
if max is not None:
self.assertTrue("max" in type["range"])
self.assertEqual(max, type["range"]["max"])
else:
self.assertFalse("max" in type["range"])
if step is not None:
self.assertTrue("step" in type["range"])
self.assertEqual(step, type["range"]["step"])
else:
self.assertFalse("step" in type["range"])
def test4_check_types_with_ranges(self):
self.assure_range("battery", "battery", 0, 100, 1)
self.assure_range("brightness", "brightness", 0, 100, 1)
self.assure_range("co2", "CO2", 0, 1000000, 1)
self.assure_range("humidity", "humidity", 0, 100, 1)
self.assure_range("luminance", "luminance", 0, 1000000, 1)
self.assure_range("noise", "noise", 0, 200, 1)
self.assure_range("performance", "performance", 0, 100, 1)
self.assure_range("pressure", "pressure", 800, 1100, 1)
self.assure_range("rssi", "signal", 0, 100, 1)
self.assure_range("temperature", "temperature", -273.15, 200, 0.01)
self.assure_range("ultraviolet", "UV", 0, 11, 0.1)
self.assure_range("color_temperature", "color temperature", 1700, 27000, 1)
self.assure_range("color", "color", 0, 16777215, 1)
def assure_values(self, id, name, values):
req = GET(config.ui_host, config.ui_port, "/types/" + id)
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
type = result["data"]
self.assertEqual(name, type["name"])
self.assertTrue("values" in type)
self.assertEqual(len(values), len(type["values"]))
for key in values:
self.assertTrue(key in type["values"])
self.assertEqual(values[key], type["values"][key])
def test5_check_types_with_values(self):
self.assure_values("availability", "availability", {"0": "unavailable", "1": "available"})
self.assure_values("fire", "fire", {"0": "no fire", "1": "fire"})
self.assure_values("motion", "motion", {"0": "no motion", "1": "motion"})
self.assure_values("open_close", "open/close", {"0": "closed", "1": "open"})
self.assure_values("on_off", "on/off", {"0": "off", "1": "on"})
self.assure_values("security_alert", "security alert", {"0": "ease", "1": "alert"})
self.assure_values("shake", "shake", {"0": "ease", "1": "shake"})
def assure_levels(self, id, name, levels):
req = GET(config.ui_host, config.ui_port, "/types/" + id)
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
type = result["data"]
self.assertEqual(name, type["name"])
self.assertTrue("levels" in type)
self.assertEqual(len(levels), len(type["levels"]))
for i in range(len(levels)):
if levels[i][0] is None:
self.assertFalse("min" in type["levels"][i])
else:
self.assertTrue("min" in type["levels"][i])
self.assertEqual(levels[i][0], type["levels"][i]["min"])
if levels[i][1] is None:
self.assertFalse("max" in type["levels"][i])
else:
self.assertTrue("max" in type["levels"][i])
self.assertEqual(levels[i][1], type["levels"][i]["max"])
if levels[i][2] is None:
self.assertFalse("attention" in type["levels"][i])
else:
self.assertTrue("attention" in type["levels"][i])
self.assertEqual(levels[i][2], type["levels"][i]["attention"])
if levels[i][3] is None:
self.assertFalse("name" in type["levels"][i])
else:
self.assertTrue("name" in type["levels"][i])
self.assertEqual(levels[i][3], type["levels"][i]["name"])
def test6_check_types_with_levels(self):
self.assure_levels("battery", "battery", [
(0, 10, "single", "critical"),
(11, 25, "single", "low"),
(26, 80, None, "medium"),
(81, 100, None, "high")
])
self.assure_levels("co2", "CO2", [
(None, 450, None, "normal outdoor"),
(451, 1000, None, "normal indoor"),
(1001, 2500, None, "poor air"),
(2501, 5000, "single", "adverse health effects"),
(5001, 10000, "repeat", "dangerous after few hours"),
(10001, 30000, "repeat" , "dangerous after several minutes"),
(30001, None, "alert", "extreme and dangerous")
])
self.assure_levels("fire", "fire", [
(1, 1, "alert", None)
])
self.assure_levels("motion", "motion", [
(1, 1, "single", None)
])
self.assure_levels("noise", "noise", [
(None, 80, None, "normal"),
(81, 90, None, "acceptable"),
(91, 99, "single", "loud"),
(100, 111, "repeat", "dangerous for several minutes stay"),
(112, 139, "repeat", "dangerous for few minutes stay"),
(140, None, "alert", "immediate nerve damage possible"),
])
self.assure_levels("performance", "performance", [
(0, 0, None, "idle"),
(95, None, None, "high load")
])
self.assure_levels("rssi", "signal", [
(None, 25, None, "poor"),
(26, 80, None, "good"),
(81, 100, None, "high")
])
self.assure_levels("security_alert", "security alert", [
(1, 1, "alert", None)
])
self.assure_levels("ultraviolet", "UV", [
(None, 2.9, None, "low"),
(3, 5.9, None, "moderate"),
(6, 7.9, "single", "high"),
(8, 10.9, "single", "very high"),
(11, None, "single", "extreme")
])
def test7_check_enums(self):
req = GET(config.ui_host, config.ui_port, "/types/enum/MOD_BOILER_STATUS")
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
enum = result["data"]
self.assertEqual("boiler status", enum["name"])
self.assertTrue("values" in enum)
self.assertEqual(5, len(enum["values"]))
self.assertEqual("undefined", enum["values"]["0"])
self.assertEqual("heating", enum["values"]["1"])
self.assertEqual("heating water", enum["values"]["2"])
self.assertEqual("failure", enum["values"]["3"])
self.assertEqual("shutdown", enum["values"]["4"])
def test8_check_bitmap_with_flags(self):
req = GET(config.ui_host, config.ui_port, "/types/bitmap/MOD_CURRENT_BOILER_OT_FAULT_FLAGS")
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
bitmap = result["data"]
self.assertEqual("OT Fault Flags", bitmap["name"])
self.assertTrue("flags" in bitmap)
self.assertEqual(6, len(bitmap["flags"]))
self.assertEqual("service request", bitmap["flags"]["0"]["name"])
self.assertEqual("lockout reset enabled", bitmap["flags"]["1"]["name"])
self.assertEqual("low water pressure", bitmap["flags"]["2"]["name"])
self.assertEqual("gas/flame fault", bitmap["flags"]["3"]["name"])
self.assertEqual("air pressure fault", bitmap["flags"]["4"]["name"])
self.assertEqual("water overheated", bitmap["flags"]["5"]["name"])
def test9_check_bitmap_with_group(self):
req = GET(config.ui_host, config.ui_port, "/types/bitmap/MOD_CURRENT_BOILER_OT_OEM_FAULTS")
req.authorize(self.session)
response, content = req()
self.assertEqual(200, response.status)
result = json.loads(content)
self.assertEqual("success", result["status"])
bitmap = result["data"]
self.assertEqual("OT OEM Faults", bitmap["name"])
self.assertTrue("groups" in bitmap)
self.assertEqual(1, len(bitmap["groups"]))
self.assertEqual("OEM specific", bitmap["groups"][0]["name"])
self.assertEqual(8, len(bitmap["groups"][0]["mapping"]))
self.assertEqual(0, bitmap["groups"][0]["mapping"][0])
self.assertEqual(1, bitmap["groups"][0]["mapping"][1])
self.assertEqual(2, bitmap["groups"][0]["mapping"][2])
self.assertEqual(3, bitmap["groups"][0]["mapping"][3])
self.assertEqual(4, bitmap["groups"][0]["mapping"][4])
self.assertEqual(5, bitmap["groups"][0]["mapping"][5])
self.assertEqual(6, bitmap["groups"][0]["mapping"][6])
self.assertEqual(7, bitmap["groups"][0]["mapping"][7])
if __name__ == '__main__':
import sys
import taprunner
unittest.main(testRunner=taprunner.TAPTestRunner(stream = sys.stdout))
|
bsd-3-clause
| 227,601,853,684,804,400
| 32.271845
| 94
| 0.654897
| false
| 3.010542
| true
| false
| false
|
fusionbox/django-darkknight
|
darkknight/forms.py
|
1
|
4549
|
import re
import os
from django import forms
from django.db import transaction
from django.utils.translation import ugettext as _
from django.forms.formsets import BaseFormSet
from localflavor.us.us_states import US_STATES
from django_countries import countries
from OpenSSL import crypto
from darkknight.models import CertificateSigningRequest, SSLKey
from darkknight.signals import key_created
KEY_SIZE = 2048
WWW = 'www.'
def creat(filename, mode):
fd = os.open(filename, os.O_CREAT | os.O_WRONLY | os.O_EXCL, mode)
return os.fdopen(fd, 'w')
class GenerateForm(forms.Form):
countryName = forms.ChoiceField(
choices=countries,
label=_("Country Name"),
initial='US',
)
stateOrProvinceName = forms.CharField(
label=_("State or province name"),
help_text=_("Enter its full name"),
)
localityName = forms.CharField(
label=_("Locality name"),
help_text=_("eg, city name"),
)
organizationName = forms.CharField(
label=_("Organisation Name"),
help_text=_("eg, company name"),
)
organizationalUnitName = forms.CharField(
label=_("Organisation Unit"),
help_text=_("Section, Department, ... eg, IT Departement"),
required=False,
)
commonName = forms.CharField(
label=_("Common Name"),
help_text=_("Domain name, including 'www.' if applicable. "
"eg, www.example.com")
)
emailAddress = forms.EmailField(
label=_("Email address"),
required=False,
)
subjectAlternativeNames = forms.CharField(
label=_('Subject Alternative Names (SAN)'),
required=False,
help_text=_('Please put one domain name per line'),
widget=forms.Textarea,
)
def clean_countryName(self):
country = self.cleaned_data['countryName']
if not re.match('^[a-z]{2}$', country, flags=re.IGNORECASE):
raise forms.ValidationError(_("Please enter a two-letters code"))
return country.upper()
def clean_subjectAlternativeNames(self):
sans = list(filter(bool, (
domain.strip() for domain in self.cleaned_data['subjectAlternativeNames'].splitlines()
)))
return sans
def clean(self):
cd = super(GenerateForm, self).clean()
if cd.get('countryName') == 'US':
try:
if cd['stateOrProvinceName'] not in set(i[1] for i in US_STATES):
self.add_error('stateOrProvinceName', 'State should be the full state name, eg "Colorado"')
except KeyError:
pass
return cd
class GenerateBaseFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(GenerateBaseFormSet, self).__init__(*args, **kwargs)
for form in self.forms:
form.empty_permitted = False
def generate(self):
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, KEY_SIZE)
key_obj = SSLKey()
csr_list = [self._generate_csr(pkey, key_obj, data) for data in self.cleaned_data]
with transaction.atomic():
key = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
assert not os.path.exists(key_obj.key_path)
with creat(key_obj.key_path, 0000) as f:
f.write(key)
key_obj.save()
CertificateSigningRequest.objects.bulk_create(csr_list)
key_created.send(sender=self, instance=key_obj, private_key=key)
return key_obj
def _generate_csr(self, pkey, key_obj, cleaned_data):
req = crypto.X509Req()
req.set_pubkey(pkey)
subject = req.get_subject()
for attr, value in cleaned_data.items():
if value:
if attr == 'subjectAlternativeNames':
req.add_extensions([
crypto.X509Extension('subjectAltName', False, ", ".join(
"DNS.{i}:{domain}".format(i=i, domain=domain)
for i, domain in enumerate(value)
))
])
else:
setattr(subject, attr, value)
cn = cleaned_data['commonName']
# Strip www. from the common name
if cn.startswith(WWW):
cn = cn[len(WWW):]
req.sign(pkey, "sha256")
csr = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)
csr_obj = CertificateSigningRequest(domain=cn, key=key_obj, content=csr)
return csr_obj
|
bsd-2-clause
| -862,029,955,554,943,000
| 31.963768
| 111
| 0.591778
| false
| 4.043556
| false
| false
| false
|
debian789/suescunet
|
apps/codigos/admin.py
|
1
|
1478
|
from django.contrib import admin
from models import mdl_codigos
from apps.elementos_comunes.models import mdl_lenguaje,mdl_sistema_operativo
from actions import export_as_csv
## crea el listado de opciones en el administrado !!!
class codigosAdmin(admin.ModelAdmin):
list_display = ('titulo','lenguaje','archivo','imagen_azul','esta_publicado','url')
list_filter = ('publicado','so','lenguaje')
search_fields = ('titulo','codigo')
list_editable = ('archivo',)
actions = [export_as_csv]
raw_id_fields = ('lenguaje',)
filter_horizontal = ('so',)
def imagen_azul(self,obj):
url = obj.imagen_azul_publicado()
tag = '<img src="%s">'% url
return tag
imagen_azul.allow_tags = True #permite que tenga tag html
imagen_azul.admin_order_field = 'publicado' #permite ordenarlos por publicado
class CodigosInline(admin.StackedInline):
model = mdl_codigos
extra = 1
class LenguajesAdmin(admin.ModelAdmin):
actions = [export_as_csv]
inlines = [CodigosInline]
#class SitemaOperativoAdmin(admin.ModelAdmin):
# fiter_vertical = ('so',)
#class AgregadorAdmin(admin.ModelAdmin):
# filter_vertical = ('enlaces',)
admin.site.register(mdl_sistema_operativo)
#admin.site.register(Agregador,AgregadorAdmin)
#admin.site.register(mdl_sistema_operativo)
#admin.site.register(mdl_lenguaje,LenguajesAdmin)
admin.site.register(mdl_lenguaje)
admin.site.register(mdl_codigos,codigosAdmin)
#admin.site.register(soAdmin)
#admin.site.register(mdl_lenguaje,LenguajesAdmin)
|
gpl-2.0
| 5,772,595,188,927,756,000
| 31.152174
| 85
| 0.747632
| false
| 2.672694
| false
| false
| false
|
jeremiah-c-leary/vhdl-style-guide
|
vsg/tests/sequential/test_rule_006.py
|
1
|
1193
|
import os
import unittest
from vsg.rules import sequential
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_006_test_input.vhd'))
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_006_test_input.fixed.vhd'), lExpected)
class test_sequential_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
def test_rule_006(self):
oRule = sequential.rule_006()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'sequential')
self.assertEqual(oRule.identifier, '006')
lExpected = [19, 21]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_006(self):
oRule = sequential.rule_006()
oRule.fixable = True
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
|
gpl-3.0
| 3,324,378,810,418,496,500
| 24.934783
| 106
| 0.678122
| false
| 3.304709
| true
| false
| false
|
acjones617/k-means
|
lib/exec.py
|
1
|
1524
|
import normalize as n
import cluster as c
import jsonpickle as j
import argparse
import ast
parser = argparse.ArgumentParser()
parser.add_argument('matrix')
parser.add_argument('options')
args = parser.parse_args()
matrix = ast.literal_eval(args.matrix)
options = ast.literal_eval(args.options)
# steps:
# 1. normalize data
# 2. randomly pick center points
# 3. assign points to a cluster
# 4. re-pick cluster center points
# 5. repeat
# 6. assign clusters to original data
# 7. send back to node
# steps:
# 1. normalize data
normal_matrix = n.normalize(matrix)
# 2. randomly pick cluster center points
cluster_centers = c.init(normal_matrix, options['clusters'])
# 3. assign points to a cluster
# 4. re-pick cluster center points
# 5. repeat steps 3 and 4
clusters = []
has_converged = False
for i in range(options['iterations']):
old_clusters = clusters
cluster_points, clusters = c.assign_points(normal_matrix, cluster_centers)
if c.converged(old_clusters, clusters):
has_converged = True
break
cluster_centers = c.reselect_centers(cluster_points, options['clusters'])
# final assignment of points if never converged
if (not has_converged):
cluster_points, clusters = c.assign_points(normal_matrix, cluster_centers)
# 6. assign clusters to original data
final_matrix = n.reassign(matrix, cluster_points)
# 7. send back to node - need to convert cluster centers to list first
print j.encode({
'finalMatrix' : final_matrix,
'clusterCenters': cluster_centers
})
|
mit
| 4,464,520,530,550,727,700
| 24.4
| 78
| 0.727034
| false
| 3.544186
| false
| false
| false
|
mlperf/training_results_v0.7
|
Google/benchmarks/ssd/implementations/ssd-research-TF-tpu-v4-512/ssd_main.py
|
1
|
11062
|
# Copyright 2018 Google. 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 implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Training script for SSD.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import math
import multiprocessing
import sys
import threading
from absl import app
import tensorflow.compat.v1 as tf
from REDACTED.mlp_log import mlp_log
from REDACTED.ssd import coco_metric
from REDACTED.ssd import dataloader
from REDACTED.ssd import ssd_constants
from REDACTED.ssd import ssd_model
from REDACTED.util import train_and_eval_runner
# copybara:strip_begin
from REDACTED.REDACTED.multiprocessing import REDACTEDprocess
# copybara:strip_end
tf.flags.DEFINE_string(
'resnet_checkpoint',
'/REDACTED/mb-d/home/tpu-perf-team/ssd_checkpoint/resnet34_bs2048_2',
'Location of the ResNet checkpoint to use for model '
'initialization.')
tf.flags.DEFINE_string('hparams', '',
'Comma separated k=v pairs of hyperparameters.')
tf.flags.DEFINE_integer(
'num_shards', default=8, help='Number of shards (TPU cores) for '
'training.')
tf.flags.DEFINE_integer('train_batch_size', 64, 'training batch size')
tf.flags.DEFINE_integer('eval_batch_size', 1, 'evaluation batch size')
tf.flags.DEFINE_integer('eval_samples', 5000, 'The number of samples for '
'evaluation.')
tf.flags.DEFINE_integer(
'iterations_per_loop', 1000, 'Number of iterations per TPU training loop')
tf.flags.DEFINE_string(
'training_file_pattern',
'REDACTEDtrain*',
'Glob for training data files (e.g., COCO train - minival set)')
tf.flags.DEFINE_string(
'validation_file_pattern',
'REDACTEDval*',
'Glob for evaluation tfrecords (e.g., COCO val2017 set)')
tf.flags.DEFINE_bool(
'use_fake_data', False,
'Use fake data to reduce the input preprocessing overhead (for unit tests)')
tf.flags.DEFINE_string(
'val_json_file',
'REDACTEDinstances_val2017.json',
'COCO validation JSON containing golden bounding boxes.')
tf.flags.DEFINE_integer('num_examples_per_epoch', 118287,
'Number of examples in one epoch')
tf.flags.DEFINE_integer('num_epochs', 64, 'Number of epochs for training')
tf.flags.DEFINE_multi_integer(
'input_partition_dims',
default=None,
help=('Number of partitions on each dimension of the input. Each TPU core'
' processes a partition of the input image in parallel using spatial'
' partitioning.'))
tf.flags.DEFINE_bool('run_cocoeval', True, 'Whether to run cocoeval')
FLAGS = tf.flags.FLAGS
_STOP = -1
def construct_run_config(iterations_per_loop):
"""Construct the run config."""
# Parse hparams
hparams = ssd_model.default_hparams()
hparams.parse(FLAGS.hparams)
return dict(
hparams.values(),
num_shards=FLAGS.num_shards,
num_examples_per_epoch=FLAGS.num_examples_per_epoch,
resnet_checkpoint=FLAGS.resnet_checkpoint,
val_json_file=FLAGS.val_json_file,
model_dir=FLAGS.model_dir,
iterations_per_loop=iterations_per_loop,
steps_per_epoch=FLAGS.num_examples_per_epoch // FLAGS.train_batch_size,
eval_samples=FLAGS.eval_samples,
transpose_input=False if FLAGS.input_partition_dims is not None else True,
use_spatial_partitioning=True
if FLAGS.input_partition_dims is not None else False,
)
# copybara:strip_begin
def REDACTED_predict_post_processing():
"""REDACTED batch-processes the predictions."""
q_in, q_out = REDACTEDprocess.get_user_data()
predict_post_processing(q_in, q_out)
# copybara:strip_end
def predict_post_processing(q_in, q_out):
"""Run post-processing on CPU for predictions."""
coco_gt = coco_metric.create_coco(FLAGS.val_json_file, use_cpp_extension=True)
current_step, predictions = q_in.get()
while current_step != _STOP and q_out is not None:
q_out.put((current_step,
coco_metric.compute_map(
predictions,
coco_gt,
use_cpp_extension=True,
nms_on_tpu=True)))
current_step, predictions = q_in.get()
def main(argv):
del argv # Unused.
params = construct_run_config(FLAGS.iterations_per_loop)
mlp_log.mlperf_print(key='cache_clear', value=True)
mlp_log.mlperf_print(key='init_start', value=None)
mlp_log.mlperf_print('global_batch_size', FLAGS.train_batch_size)
mlp_log.mlperf_print('opt_base_learning_rate', params['base_learning_rate'])
mlp_log.mlperf_print(
'opt_learning_rate_decay_boundary_epochs',
[params['first_lr_drop_epoch'], params['second_lr_drop_epoch']])
mlp_log.mlperf_print('opt_weight_decay', params['weight_decay'])
mlp_log.mlperf_print(
'model_bn_span', FLAGS.train_batch_size // FLAGS.num_shards *
params['distributed_group_size'])
mlp_log.mlperf_print('max_samples', ssd_constants.NUM_CROP_PASSES)
mlp_log.mlperf_print('train_samples', FLAGS.num_examples_per_epoch)
mlp_log.mlperf_print('eval_samples', FLAGS.eval_samples)
params['batch_size'] = FLAGS.train_batch_size // FLAGS.num_shards
input_partition_dims = FLAGS.input_partition_dims
train_steps = FLAGS.num_epochs * FLAGS.num_examples_per_epoch // FLAGS.train_batch_size
eval_steps = int(math.ceil(FLAGS.eval_samples / FLAGS.eval_batch_size))
runner = train_and_eval_runner.TrainAndEvalRunner(FLAGS.iterations_per_loop,
train_steps, eval_steps,
FLAGS.num_shards)
train_input_fn = dataloader.SSDInputReader(
FLAGS.training_file_pattern,
params['transpose_input'],
is_training=True,
use_fake_data=FLAGS.use_fake_data,
params=params)
eval_input_fn = dataloader.SSDInputReader(
FLAGS.validation_file_pattern,
is_training=False,
use_fake_data=FLAGS.use_fake_data,
distributed_eval=True,
count=eval_steps * FLAGS.eval_batch_size,
params=params)
def init_fn():
tf.train.init_from_checkpoint(params['resnet_checkpoint'], {
'resnet/': 'resnet%s/' % ssd_constants.RESNET_DEPTH,
})
if FLAGS.run_cocoeval:
# copybara:strip_begin
q_in, q_out = REDACTEDprocess.get_user_data()
processes = [
REDACTEDprocess.Process(target=REDACTED_predict_post_processing) for _ in range(4)
]
# copybara:strip_end_and_replace_begin
# q_in = multiprocessing.Queue(maxsize=ssd_constants.QUEUE_SIZE)
# q_out = multiprocessing.Queue(maxsize=ssd_constants.QUEUE_SIZE)
# processes = [
# multiprocessing.Process(
# target=predict_post_processing, args=(q_in, q_out))
# for _ in range(self.num_multiprocessing_workers)
# ]
# copybara:replace_end
for p in processes:
p.start()
def log_eval_results_fn():
"""Print out MLPerf log."""
result = q_out.get()
success = False
while result[0] != _STOP:
if not success:
steps_per_epoch = (
FLAGS.num_examples_per_epoch // FLAGS.train_batch_size)
epoch = (result[0] + FLAGS.iterations_per_loop) // steps_per_epoch
mlp_log.mlperf_print(
'eval_accuracy',
result[1]['COCO/AP'],
metadata={'epoch_num': epoch})
mlp_log.mlperf_print('eval_stop', None, metadata={'epoch_num': epoch})
if result[1]['COCO/AP'] > ssd_constants.EVAL_TARGET:
success = True
mlp_log.mlperf_print(
'run_stop', None, metadata={'status': 'success'})
result = q_out.get()
if not success:
mlp_log.mlperf_print('run_stop', None, metadata={'status': 'abort'})
log_eval_result_thread = threading.Thread(target=log_eval_results_fn)
log_eval_result_thread.start()
runner.initialize(train_input_fn, eval_input_fn,
functools.partial(ssd_model.ssd_model_fn,
params), FLAGS.train_batch_size,
FLAGS.eval_batch_size, input_partition_dims, init_fn)
mlp_log.mlperf_print('init_stop', None)
mlp_log.mlperf_print('run_start', None)
def eval_init_fn(cur_step):
"""Executed before every eval."""
steps_per_epoch = FLAGS.num_examples_per_epoch // FLAGS.train_batch_size
epoch = cur_step // steps_per_epoch
mlp_log.mlperf_print(
'block_start',
None,
metadata={
'first_epoch_num': epoch,
'epoch_count': FLAGS.iterations_per_loop // steps_per_epoch
})
mlp_log.mlperf_print(
'eval_start',
None,
metadata={
'epoch_num': epoch + FLAGS.iterations_per_loop // steps_per_epoch
})
def eval_finish_fn(cur_step, eval_output, _):
steps_per_epoch = FLAGS.num_examples_per_epoch // FLAGS.train_batch_size
epoch = cur_step // steps_per_epoch
mlp_log.mlperf_print(
'block_stop',
None,
metadata={
'first_epoch_num': epoch,
'epoch_count': FLAGS.iterations_per_loop // steps_per_epoch
})
if FLAGS.run_cocoeval:
q_in.put((cur_step, eval_output['detections']))
runner.train_and_eval(eval_init_fn, eval_finish_fn)
if FLAGS.run_cocoeval:
for _ in processes:
q_in.put((_STOP, None))
for p in processes:
try:
p.join(timeout=10)
except Exception: # pylint: disable=broad-except
pass
q_out.put((_STOP, None))
log_eval_result_thread.join()
# Clear out all the queues to avoid deadlock.
while not q_out.empty():
q_out.get()
while not q_in.empty():
q_in.get()
if __name__ == '__main__':
# copybara:strip_begin
user_data = (multiprocessing.Queue(maxsize=ssd_constants.QUEUE_SIZE),
multiprocessing.Queue(maxsize=ssd_constants.QUEUE_SIZE))
in_compile_test = False
for arg in sys.argv:
if arg == '--xla_jf_exit_process_on_compilation_success=true':
in_compile_test = True
break
if in_compile_test:
# Exiting from XLA's C extension skips REDACTEDprocess's multiprocessing clean
# up. Don't use REDACTED process when xla is in compilation only mode.
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
else:
with REDACTEDprocess.main_handler(user_data=user_data):
tf.logging.set_verbosity(tf.logging.INFO)
app.run(main)
# copybara:strip_end
# copybara:insert tf.logging.set_verbosity(tf.logging.INFO)
# copybara:insert app.run(main)
|
apache-2.0
| 66,469,063,065,002,300
| 35.388158
| 90
| 0.653679
| false
| 3.437539
| false
| false
| false
|
openwebcc/ba
|
maintenance/rawdata/als/hef/071011_hef14_fix_ala.py
|
1
|
2755
|
#!/usr/bin/python
#
# fix incorrect syntax for echoes in .ala files of 071011_hef14
#
import re
import os
import sys
sys.path.append('/home/institut/rawdata/www/lib')
from Laser.Util import las
if __name__ == '__main__':
""" fix incorrect return number and number of returns for given pulse syntax """
import argparse
parser = argparse.ArgumentParser(description='fix incorrect syntax for echoes in .ala files')
parser.add_argument('--ala', dest='ala', required=True, help='path to input .ala file')
parser.add_argument('--out', dest='out', required=True, help='path to cleaned output file')
args = parser.parse_args()
# init utility library
util = las.rawdata()
# open output file
o = open(args.out,'w')
# loop through input file, read pairs of line and clean up
with open(args.ala) as f:
prev_line = None
curr_line = None
for line in f:
if not prev_line:
prev_line = util.parse_line(line)
continue
else:
curr_line = util.parse_line(line)
# alter previous and current line in one turn if gpstimes are the same
if prev_line[0] == curr_line[0]:
# set return numbers of previous echo
prev_line[-2] = '1'
prev_line[-1] = '2'
# set return numbers of current echo
curr_line[-2] = '2'
curr_line[-1] = '2'
# write out both lines
o.write('%s\n' % ' '.join(prev_line))
o.write('%s\n' % ' '.join(curr_line))
# set previous line to None
prev_line = None
continue
else:
# write previous line with 1 1 as no second echo is present
prev_line[-2] = '1'
prev_line[-1] = '1'
o.write('%s\n' % ' '.join(prev_line))
# assign current line as next previous line
prev_line = curr_line[:]
# write last record from loop if any
if prev_line:
o.write('%s\n' % ' '.join(prev_line))
# create log file
with open("%s.txt" % args.out, "w") as log:
log.write("the corresponding file was created with %s\n" % __file__)
log.write("it contains fixed return numbers for first and second returns\n")
log.write("\n")
log.write("input file with incorrect return numbers: %s\n" % re.sub("raw/str/ala","raw/bad/ala",args.ala[:-4]) )
log.write("output file with correct return numbers: %s\n" % args.out)
log.write("\n")
# close cleaned output file
o.close()
|
gpl-3.0
| -4,989,434,933,116,422,000
| 33.873418
| 120
| 0.536116
| false
| 3.969741
| false
| false
| false
|
google/retiming
|
models/networks.py
|
1
|
16657
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from third_party.models.networks import init_net
###############################################################################
# Helper Functions
###############################################################################
def define_LNR(nf=64, texture_channels=16, texture_res=16, n_textures=25, gpu_ids=[]):
"""Create a layered neural renderer.
Parameters:
nf (int) -- the number of channels in the first/last conv layers
texture_channels (int) -- the number of channels in the neural texture
texture_res (int) -- the size of each individual texture map
n_textures (int) -- the number of individual texture maps
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
Returns a layered neural rendering model.
"""
net = LayeredNeuralRenderer(nf, texture_channels, texture_res, n_textures)
return init_net(net, gpu_ids)
def define_kp2uv(nf=64, gpu_ids=[]):
"""Create a keypoint-to-UV model.
Parameters:
nf (int) -- the number of channels in the first/last conv layers
Returns a keypoint-to-UV model.
"""
net = kp2uv(nf)
return init_net(net, gpu_ids)
def cal_alpha_reg(prediction, lambda_alpha_l1, lambda_alpha_l0):
"""Calculate the alpha regularization term.
Parameters:
prediction (tensor) - - composite of predicted alpha layers
lambda_alpha_l1 (float) - - weight for the L1 regularization term
lambda_alpha_l0 (float) - - weight for the L0 regularization term
Returns the alpha regularization loss term
"""
assert prediction.max() <= 1.
assert prediction.min() >= 0.
loss = 0.
if lambda_alpha_l1 > 0:
loss += lambda_alpha_l1 * torch.mean(prediction)
if lambda_alpha_l0 > 0:
# Pseudo L0 loss using a squished sigmoid curve.
l0_prediction = (torch.sigmoid(prediction * 5.0) - 0.5) * 2.0
loss += lambda_alpha_l0 * torch.mean(l0_prediction)
return loss
##############################################################################
# Classes
##############################################################################
class MaskLoss(nn.Module):
"""Define the loss which encourages the predicted alpha matte to match the mask (trimap)."""
def __init__(self):
super(MaskLoss, self).__init__()
self.loss = nn.L1Loss(reduction='none')
def __call__(self, prediction, target):
"""Calculate loss given predicted alpha matte and trimap.
Balance positive and negative regions. Exclude 'unknown' region from loss.
Parameters:
prediction (tensor) - - predicted alpha
target (tensor) - - trimap
Returns: the computed loss
"""
mask_err = self.loss(prediction, target)
pos_mask = F.relu(target)
neg_mask = F.relu(-target)
pos_mask_loss = (pos_mask * mask_err).sum() / (1 + pos_mask.sum())
neg_mask_loss = (neg_mask * mask_err).sum() / (1 + neg_mask.sum())
loss = .5 * (pos_mask_loss + neg_mask_loss)
return loss
class ConvBlock(nn.Module):
"""Helper module consisting of a convolution, optional normalization and activation, with padding='same'."""
def __init__(self, conv, in_channels, out_channels, ksize=4, stride=1, dil=1, norm=None, activation='relu'):
"""Create a conv block.
Parameters:
conv (convolutional layer) - - the type of conv layer, e.g. Conv2d, ConvTranspose2d
in_channels (int) - - the number of input channels
in_channels (int) - - the number of output channels
ksize (int) - - the kernel size
stride (int) - - stride
dil (int) - - dilation
norm (norm layer) - - the type of normalization layer, e.g. BatchNorm2d, InstanceNorm2d
activation (str) -- the type of activation: relu | leaky | tanh | none
"""
super(ConvBlock, self).__init__()
self.k = ksize
self.s = stride
self.d = dil
self.conv = conv(in_channels, out_channels, ksize, stride=stride, dilation=dil)
if norm is not None:
self.norm = norm(out_channels)
else:
self.norm = None
if activation == 'leaky':
self.activation = nn.LeakyReLU(0.2)
elif activation == 'relu':
self.activation = nn.ReLU()
elif activation == 'tanh':
self.activation = nn.Tanh()
else:
self.activation = None
def forward(self, x):
"""Forward pass. Compute necessary padding and cropping because pytorch doesn't have pad=same."""
height, width = x.shape[-2:]
if isinstance(self.conv, nn.modules.ConvTranspose2d):
desired_height = height * self.s
desired_width = width * self.s
pady = 0
padx = 0
else:
# o = [i + 2*p - k - (k-1)*(d-1)]/s + 1
# padding = .5 * (stride * (output-1) + (k-1)(d-1) + k - input)
desired_height = height // self.s
desired_width = width // self.s
pady = .5 * (self.s * (desired_height - 1) + (self.k - 1) * (self.d - 1) + self.k - height)
padx = .5 * (self.s * (desired_width - 1) + (self.k - 1) * (self.d - 1) + self.k - width)
x = F.pad(x, [int(np.floor(padx)), int(np.ceil(padx)), int(np.floor(pady)), int(np.ceil(pady))])
x = self.conv(x)
if x.shape[-2] != desired_height or x.shape[-1] != desired_width:
cropy = x.shape[-2] - desired_height
cropx = x.shape[-1] - desired_width
x = x[:, :, int(np.floor(cropy / 2.)):-int(np.ceil(cropy / 2.)),
int(np.floor(cropx / 2.)):-int(np.ceil(cropx / 2.))]
if self.norm:
x = self.norm(x)
if self.activation:
x = self.activation(x)
return x
class ResBlock(nn.Module):
"""Define a residual block."""
def __init__(self, channels, ksize=4, stride=1, dil=1, norm=None, activation='relu'):
"""Initialize the residual block, which consists of 2 conv blocks with a skip connection."""
super(ResBlock, self).__init__()
self.convblock1 = ConvBlock(nn.Conv2d, channels, channels, ksize=ksize, stride=stride, dil=dil, norm=norm,
activation=activation)
self.convblock2 = ConvBlock(nn.Conv2d, channels, channels, ksize=ksize, stride=stride, dil=dil, norm=norm,
activation=None)
def forward(self, x):
identity = x
x = self.convblock1(x)
x = self.convblock2(x)
x += identity
return x
class kp2uv(nn.Module):
"""UNet architecture for converting keypoint image to UV map.
Same person UV map format as described in https://arxiv.org/pdf/1802.00434.pdf.
"""
def __init__(self, nf=64):
super(kp2uv, self).__init__(),
self.encoder = nn.ModuleList([
ConvBlock(nn.Conv2d, 3, nf, ksize=4, stride=2),
ConvBlock(nn.Conv2d, nf, nf * 2, ksize=4, stride=2, norm=nn.InstanceNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 2, nf * 4, ksize=4, stride=2, norm=nn.InstanceNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=4, stride=2, norm=nn.InstanceNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=4, stride=2, norm=nn.InstanceNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=3, stride=1, norm=nn.InstanceNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=3, stride=1, norm=nn.InstanceNorm2d, activation='leaky')])
self.decoder = nn.ModuleList([
ConvBlock(nn.ConvTranspose2d, nf * 4 * 2, nf * 4, ksize=4, stride=2, norm=nn.InstanceNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 4 * 2, nf * 4, ksize=4, stride=2, norm=nn.InstanceNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 4 * 2, nf * 2, ksize=4, stride=2, norm=nn.InstanceNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 2 * 2, nf, ksize=4, stride=2, norm=nn.InstanceNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 2, nf, ksize=4, stride=2, norm=nn.InstanceNorm2d)])
# head to predict body part class (25 classes - 24 body parts, 1 background.)
self.id_pred = ConvBlock(nn.Conv2d, nf + 3, 25, ksize=3, stride=1, activation='none')
# head to predict UV coordinates for every body part class
self.uv_pred = ConvBlock(nn.Conv2d, nf + 3, 2 * 24, ksize=3, stride=1, activation='tanh')
def forward(self, x):
"""Forward pass through UNet, handling skip connections.
Parameters:
x (tensor) - - rendered keypoint image, shape [B, 3, H, W]
Returns:
x_id (tensor): part id class probabilities
x_uv (tensor): uv coordinates for each part id
"""
skips = [x]
for i, layer in enumerate(self.encoder):
x = layer(x)
if i < 5:
skips.append(x)
for layer in self.decoder:
x = torch.cat((x, skips.pop()), 1)
x = layer(x)
x = torch.cat((x, skips.pop()), 1)
x_id = self.id_pred(x)
x_uv = self.uv_pred(x)
return x_id, x_uv
class LayeredNeuralRenderer(nn.Module):
"""Layered Neural Rendering model for video decomposition.
Consists of neural texture, UNet, upsampling module.
"""
def __init__(self, nf=64, texture_channels=16, texture_res=16, n_textures=25):
super(LayeredNeuralRenderer, self).__init__(),
"""Initialize layered neural renderer.
Parameters:
nf (int) -- the number of channels in the first/last conv layers
texture_channels (int) -- the number of channels in the neural texture
texture_res (int) -- the size of each individual texture map
n_textures (int) -- the number of individual texture maps
"""
# Neural texture is implemented as 'n_textures' concatenated horizontally
self.texture = nn.Parameter(torch.randn(1, texture_channels, texture_res, n_textures * texture_res))
# Define UNet
self.encoder = nn.ModuleList([
ConvBlock(nn.Conv2d, texture_channels + 1, nf, ksize=4, stride=2),
ConvBlock(nn.Conv2d, nf, nf * 2, ksize=4, stride=2, norm=nn.BatchNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 2, nf * 4, ksize=4, stride=2, norm=nn.BatchNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=4, stride=2, norm=nn.BatchNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=4, stride=2, norm=nn.BatchNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=4, stride=1, dil=2, norm=nn.BatchNorm2d, activation='leaky'),
ConvBlock(nn.Conv2d, nf * 4, nf * 4, ksize=4, stride=1, dil=2, norm=nn.BatchNorm2d, activation='leaky')])
self.decoder = nn.ModuleList([
ConvBlock(nn.ConvTranspose2d, nf * 4 * 2, nf * 4, ksize=4, stride=2, norm=nn.BatchNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 4 * 2, nf * 4, ksize=4, stride=2, norm=nn.BatchNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 4 * 2, nf * 2, ksize=4, stride=2, norm=nn.BatchNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 2 * 2, nf, ksize=4, stride=2, norm=nn.BatchNorm2d),
ConvBlock(nn.ConvTranspose2d, nf * 2, nf, ksize=4, stride=2, norm=nn.BatchNorm2d)])
self.final_rgba = ConvBlock(nn.Conv2d, nf, 4, ksize=4, stride=1, activation='tanh')
# Define upsampling block, which outputs a residual
upsampling_ic = texture_channels + 5 + nf
self.upsample_block = nn.Sequential(
ConvBlock(nn.Conv2d, upsampling_ic, nf, ksize=3, stride=1, norm=nn.InstanceNorm2d),
ResBlock(nf, ksize=3, stride=1, norm=nn.InstanceNorm2d),
ResBlock(nf, ksize=3, stride=1, norm=nn.InstanceNorm2d),
ResBlock(nf, ksize=3, stride=1, norm=nn.InstanceNorm2d),
ConvBlock(nn.Conv2d, nf, 4, ksize=3, stride=1, activation='none'))
def render(self, x):
"""Pass inputs for a single layer through UNet.
Parameters:
x (tensor) - - sampled texture concatenated with person IDs
Returns RGBA for the input layer and the final feature maps.
"""
skips = [x]
for i, layer in enumerate(self.encoder):
x = layer(x)
if i < 5:
skips.append(x)
for layer in self.decoder:
x = torch.cat((x, skips.pop()), 1)
x = layer(x)
rgba = self.final_rgba(x)
return rgba, x
def forward(self, uv_map, id_layers, uv_map_upsampled=None, crop_params=None):
"""Forward pass through layered neural renderer.
Steps:
1. Sample from the neural texture using uv_map
2. Input uv_map and id_layers into UNet
2a. If doing upsampling, then pass upsampled inputs and results through upsampling module
3. Composite RGBA outputs.
Parameters:
uv_map (tensor) - - UV maps for all layers, with shape [B, (2*L), H, W]
id_layers (tensor) - - person ID for all layers, with shape [B, L, H, W]
uv_map_upsampled (tensor) - - upsampled UV maps to input to upsampling module (if None, skip upsampling)
crop_params
"""
b_sz = uv_map.shape[0]
n_layers = uv_map.shape[1] // 2
texture = self.texture.repeat(b_sz, 1, 1, 1)
composite = None
layers = []
sampled_textures = []
for i in range(n_layers):
# Get RGBA for this layer.
uv_map_i = uv_map[:, i * 2:(i + 1) * 2, ...]
uv_map_i = uv_map_i.permute(0, 2, 3, 1)
sampled_texture = F.grid_sample(texture, uv_map_i, mode='bilinear', padding_mode='zeros')
inputs = torch.cat([sampled_texture, id_layers[:, i:i + 1]], 1)
rgba, last_feat = self.render(inputs)
if uv_map_upsampled is not None:
uv_map_up_i = uv_map_upsampled[:, i * 2:(i + 1) * 2, ...]
uv_map_up_i = uv_map_up_i.permute(0, 2, 3, 1)
sampled_texture_up = F.grid_sample(texture, uv_map_up_i, mode='bilinear', padding_mode='zeros')
id_layers_up = F.interpolate(id_layers[:, i:i + 1], size=sampled_texture_up.shape[-2:],
mode='bilinear')
inputs_up = torch.cat([sampled_texture_up, id_layers_up], 1)
upsampled_size = inputs_up.shape[-2:]
rgba = F.interpolate(rgba, size=upsampled_size, mode='bilinear')
last_feat = F.interpolate(last_feat, size=upsampled_size, mode='bilinear')
if crop_params is not None:
starty, endy, startx, endx = crop_params
rgba = rgba[:, :, starty:endy, startx:endx]
last_feat = last_feat[:, :, starty:endy, startx:endx]
inputs_up = inputs_up[:, :, starty:endy, startx:endx]
rgba_residual = self.upsample_block(torch.cat((rgba, inputs_up, last_feat), 1))
rgba += .01 * rgba_residual
rgba = torch.clamp(rgba, -1, 1)
sampled_texture = sampled_texture_up
# Update the composite with this layer's RGBA output
if composite is None:
composite = rgba
else:
alpha = rgba[:, 3:4] * .5 + .5
composite = rgba * alpha + composite * (1.0 - alpha)
layers.append(rgba)
sampled_textures.append(sampled_texture)
outputs = {
'reconstruction': composite,
'layers': torch.stack(layers, 1),
'sampled texture': sampled_textures, # for debugging
}
return outputs
|
apache-2.0
| 2,665,017,518,263,958,500
| 44.386921
| 117
| 0.576514
| false
| 3.506737
| false
| false
| false
|
samirelanduk/pygtop
|
pygtop/targets.py
|
1
|
14667
|
"""Contains target-specific objects and functions."""
from . import gtop
from . import pdb
from .interactions import Interaction, get_interaction_by_id
from .exceptions import NoSuchTargetError, NoSuchTargetFamilyError
from .shared import DatabaseLink, Gene, strip_html
def get_target_by_id(target_id):
"""Returns a Target object of the target with the given ID.
:param int target_id: The GtoP ID of the Target desired.
:rtype: :py:class:`Target`
:raises: :class:`.NoSuchTargetError`: if no such target exists in the database"""
if not isinstance(target_id, int):
raise TypeError("target_id must be int, not '%s'" % str(target_id))
json_data = gtop.get_json_from_gtop("targets/%i" % target_id)
if json_data:
return Target(json_data)
else:
raise NoSuchTargetError("There is no target with ID %i" % target_id)
def get_all_targets():
"""Returns a list of all targets in the Guide to PHARMACOLOGY database. This
can take a few seconds.
:returns: list of :py:class:`Target` objects"""
json_data = gtop.get_json_from_gtop("targets")
return [Target(t) for t in json_data]
def get_targets_by(criteria):
"""Get all targets which specify the criteria dictionary.
:param dict criteria: A dictionary of `field=value` pairs. See the\
`GtoP target web services page <http://www.guidetopharmacology.org/\
webServices.jsp#targets>`_ for key/value pairs which can be supplied.
:returns: list of :py:class:`Target` objects."""
if not isinstance(criteria, dict):
raise TypeError("criteria must be dict, not '%s'" % str(criteria))
search_string = "&".join(["%s=%s" % (key, criteria[key]) for key in criteria])
json_data = gtop.get_json_from_gtop("targets?%s" % search_string)
if json_data:
return [Target(t) for t in json_data]
else:
return []
def get_target_by_name(name):
"""Returns the target which matches the name given.
:param str name: The name of the target to search for. Note that synonyms \
will not be searched.
:rtype: :py:class:`Target`
:raises: :class:`.NoSuchTargetError`: if no such target exists in the database."""
if not isinstance(name, str):
raise TypeError("name must be str, not '%s'" % str(name))
targets = get_targets_by({"name": name})
if targets:
return targets[0]
else:
raise NoSuchTargetError("There is no target with name %s" % name)
def get_target_family_by_id(family_id):
"""Returns a TargetFamily object of the family with the given ID.
:param int family_id: The GtoP ID of the TargetFamily desired.
:rtype: :py:class:`TargetFamily`
:raises: :class:`.NoSuchTargetFamilyError`: if no such family exists in the database"""
if not isinstance(family_id, int):
raise TypeError("family_id must be int, not '%s'" % str(family_id))
json_data = gtop.get_json_from_gtop("targets/families/%i" % family_id)
if json_data:
return TargetFamily(json_data)
else:
raise NoSuchTargetFamilyError("There is no Target Family with ID %i" % family_id)
def get_all_target_families():
"""Returns a list of all target families in the Guide to PHARMACOLOGY database.
:returns: list of :py:class:`TargetFamily` objects"""
json_data = gtop.get_json_from_gtop("targets/families")
return [TargetFamily(f) for f in json_data]
class Target:
"""A Guide to PHARMACOLOGY target object.
:param json_data: A dictionary obtained from the web services."""
def __init__(self, json_data):
self.json_data = json_data
self._target_id = json_data["targetId"]
self._name = json_data["name"]
self._abbreviation = json_data["abbreviation"]
self._systematic_name = json_data["systematicName"]
self._target_type = json_data["type"]
self._family_ids = json_data["familyIds"]
self._subunit_ids = json_data["subunitIds"]
self._complex_ids = json_data["complexIds"]
def __repr__(self):
return "<Target %i (%s)>" % (self._target_id, self._name)
def target_id(self):
"""Returns the target's GtoP ID.
:rtype: int"""
return self._target_id
@strip_html
def name(self):
"""Returns the target's name.
:param bool strip_html: If ``True``, the name will have HTML entities stripped.
:rtype: str"""
return self._name
@strip_html
def abbreviation(self):
"""Returns the target's abbreviated name.
:param bool strip_html: If ``True``, the abbreviation will have HTML entities stripped.
:rtype: str"""
return self._abbreviation
@strip_html
def systematic_name(self):
"""Returns the target's systematic name.
:param bool strip_html: If ``True``, the name will have HTML entities stripped.
:rtype: str"""
return self._systematic_name
def target_type(self):
"""Returns the target's type.
:rtype: str"""
return self._target_type
def family_ids(self):
"""Returns the the family IDs of any families this target is a member of.
:returns: list of ``int``"""
return self._family_ids
def families(self):
"""Returns a list of all target families of which this target is a member.
:returns: list of :py:class:`TargetFamily` objects"""
return [get_target_family_by_id(i) for i in self._family_ids]
def subunit_ids(self):
"""Returns the the target IDs of all targets which are subunits of this
target.
:returns: list of ``int``"""
return self._subunit_ids
def subunits(self):
"""Returns a list of all targets which are subunits of this target.
:returns: list of :py:class:`Target` objects"""
return [get_target_by_id(id_) for id_ in self._subunit_ids]
def complex_ids(self):
"""Returns the the target IDs of all targets of which this target is a
subunit.
:returns: list of ``int``"""
return self._complex_ids
def complexes(self):
"""Returns a list of all targets of which this target is a subunit.
:returns: list of :py:class:`Target` objects"""
return [get_target_by_id(id_) for id_ in self._complex_ids]
@strip_html
def synonyms(self):
"""Returns any synonyms for this target.
:param bool strip_html: If ``True``, the synonyms will have HTML entities stripped.
:returns: list of str"""
return [synonym["name"] for synonym in self._get_synonym_json()]
def database_links(self, species=None):
"""Returns any database links for this target.
:param str species: If given, only links belonging to this species will be returned.
:returns: list of :class:`.DatabaseLink` objects."""
if species:
return [DatabaseLink(link_json) for link_json in self._get_database_json()
if link_json["species"] and link_json["species"].lower() == species.lower()]
else:
return [DatabaseLink(link_json) for link_json in self._get_database_json()]
def genes(self, species=None):
"""Returns any genes for this target.
:param str species: If given, only genes belonging to this species will be returned.
:returns: list of :class:`.Gene` objects."""
if species:
return [Gene(gene_json) for gene_json in self._get_gene_json()
if gene_json["species"] and gene_json["species"].lower() == species.lower()]
else:
return [Gene(gene_json) for gene_json in self._get_gene_json()]
def interactions(self, species=None):
"""Returns any interactions for this target.
:param str species: If given, only interactions belonging to this species will be returned.
:returns: list of :class:`.Interaction` objects."""
if species:
return [Interaction(interaction_json) for interaction_json in self._get_interactions_json()
if interaction_json["targetSpecies"] and interaction_json["targetSpecies"].lower() == species.lower()]
else:
return [Interaction(interaction_json) for interaction_json in self._get_interactions_json()]
get_interaction_by_id = get_interaction_by_id
"""Returns an Interaction object of a given ID belonging to the target.
:param int interaction_id: The interactions's ID.
:rtype: :py:class:`.Interaction`
:raises: :class:`.NoSuchInteractionError`: if no such interaction exists in the database."""
def ligands(self, species=None):
"""Returns any ligands that this target interacts with.
:param str species: If given, only ligands belonging to this species will be returned.
:returns: list of :class:`.DatabaseLink` objects."""
ligands = []
for interaction in self.interactions(species=species):
ligand = interaction.ligand()
if ligand not in ligands:
ligands.append(ligand)
return ligands
@pdb.ask_about_molecupy
def gtop_pdbs(self, species=None):
"""Returns a list of PDBs which the Guide to PHARMACOLOGY says contain
this target.
:param bool as_molecupy: Returns the PDBs as \
`molecuPy <http://molecupy.readthedocs.io>`_ PDB objects.
:returns: list of ``str`` PDB codes"""
if species is None:
return [pdb["pdbCode"] for pdb in self._get_pdb_json() if pdb["pdbCode"]]
else:
return [pdb["pdbCode"] for pdb in self._get_pdb_json()
if pdb["pdbCode"] and pdb["species"].lower() == species.lower()]
@pdb.ask_about_molecupy
def uniprot_pdbs(self, species=None):
"""Queries the RSCB PDB database with the targets's uniprot accessions.
:param bool as_molecupy: Returns the PDBs as \
`molecuPy <http://molecupy.readthedocs.io>`_ PDB objects.
:param str species: If given, only PDBs belonging to this species will be returned.
:returns: list of ``str`` PDB codes"""
uniprot_accessions = [
link.accession() for link in self.database_links(species=species)
if link.database() == "UniProtKB"
]
if uniprot_accessions:
results = pdb.query_rcsb_advanced("UpAccessionIdQuery", {
"accessionIdList": ",".join(uniprot_accessions)
})
return [result.split(":")[0] for result in results] if results else []
else:
return []
@pdb.ask_about_molecupy
def all_pdbs(self, species=None):
"""Get a list of PDB codes using all means available - annotated and
external.
:param bool as_molecupy: Returns the PDBs as \
`molecuPy <http://molecupy.readthedocs.io>`_ PDB objects.
:param str species: If given, only PDBs belonging to this species will be returned.
:returns: list of ``str`` PDB codes"""
return list(set(
self.gtop_pdbs(species=species) +
self.uniprot_pdbs(species=species)
))
def _get_synonym_json(self):
json_object = gtop.get_json_from_gtop(
"targets/%i/synonyms" % self._target_id
)
return json_object if json_object else []
def _get_database_json(self):
json_object = gtop.get_json_from_gtop(
"targets/%i/databaseLinks" % self._target_id
)
return json_object if json_object else []
def _get_gene_json(self):
json_object = gtop.get_json_from_gtop(
"targets/%i/geneProteinInformation" % self._target_id
)
return json_object if json_object else []
def _get_interactions_json(self):
json_object = gtop.get_json_from_gtop(
"targets/%i/interactions" % self._target_id
)
return json_object if json_object else []
def _get_pdb_json(self):
json_object = gtop.get_json_from_gtop(
"targets/%i/pdbStructure" % self._target_id
)
return json_object if json_object else []
class TargetFamily:
"""A Guide to PHARMACOLOGY target family object.
:param json_data: A dictionary obtained from the web services."""
def __init__(self, json_data):
self.json_data = json_data
self._family_id = json_data["familyId"]
self._name = json_data["name"]
self._target_ids = json_data["targetIds"]
self._parent_family_ids = json_data["parentFamilyIds"]
self._sub_family_ids = json_data["subFamilyIds"]
def __repr__(self):
return "<'%s' TargetFamily>" % self._name
def family_id(self):
"""Returns the family's GtoP ID.
:rtype: int"""
return self._family_id
@strip_html
def name(self):
"""Returns the family's name.
:param bool strip_html: If ``True``, the name will have HTML entities stripped.
:rtype: str"""
return self._name
def target_ids(self):
"""Returns the the target IDs of all targets in this family. Note that only
immediate children are shown - if a family has subfamilies then it will
not return any targets here - you must look in the sub-families.
:returns: list of ``int``"""
return self._target_ids
def targets(self):
"""Returns a list of all targets in this family. Note that only
immediate children are shown - if a family has subfamilies then it will
not return any targets here - you must look in the sub-families.
:returns: list of :py:class:`Target` objects"""
return [get_target_by_id(i) for i in self._target_ids]
def parent_family_ids(self):
"""Returns the the target IDs of all target families of which this
family is a member.
:returns: list of ``int``"""
return self._parent_family_ids
def parent_families(self):
"""Returns a list of all target families of which this family is a member.
:returns: list of :py:class:`TargetFamily` objects"""
return [get_target_family_by_id(i) for i in self._parent_family_ids]
def sub_family_ids(self):
"""Returns the the target IDs of all arget families which are a member
of this family.
:returns: list of ``int``"""
return self._sub_family_ids
def sub_families(self):
"""Returns a list of all target families which are a member of this family.
:returns: list of :py:class:`TargetFamily` objects"""
return [get_target_family_by_id(i) for i in self._sub_family_ids]
|
mit
| 6,307,949,579,907,811,000
| 30.678186
| 115
| 0.628281
| false
| 3.83752
| false
| false
| false
|
easyw/kicad-3d-models-in-freecad
|
cadquery/FCAD_script_generator/Fuse/main_generator_SMD.py
|
1
|
13644
|
# -*- coding: utf8 -*-
#!/usr/bin/python
#
# This is derived from a cadquery script for generating PDIP models in X3D format
#
# from https://bitbucket.org/hyOzd/freecad-macros
# author hyOzd
# This is a
# Dimensions are from Microchips Packaging Specification document:
# DS00000049BY. Body drawing is the same as QFP generator#
## requirements
## cadquery FreeCAD plugin
## https://github.com/jmwright/cadquery-freecad-module
## to run the script just do: freecad make_gwexport_fc.py modelName
## e.g. c:\freecad\bin\freecad make_gw_export_fc.py SOIC_8
## the script will generate STEP and VRML parametric models
## to be used with kicad StepUp script
#* These are a FreeCAD & cadquery tools *
#* to export generated models in STEP & VRML format. *
#* *
#* cadquery script for generating QFP/SOIC/SSOP/TSSOP models in STEP AP214 *
#* Copyright (c) 2015 *
#* Maurice https://launchpad.net/~easyw *
#* All trademarks within this guide belong to their legitimate owners. *
#* *
#* 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 Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., *
#* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *
#* *
#****************************************************************************
__title__ = "make chip Resistors 3D models"
__author__ = "maurice"
__Comment__ = 'make chip Resistors 3D models exported to STEP and VRML for Kicad StepUP script'
___ver___ = "1.3.2 10/02/2017"
# thanks to Frank Severinsen Shack for including vrml materials
# maui import cadquery as cq
# maui from Helpers import show
from math import tan, radians, sqrt
from collections import namedtuple
global save_memory
save_memory = False #reducing memory consuming for all generation params
import sys, os
import datetime
from datetime import datetime
sys.path.append("../_tools")
import exportPartToVRML as expVRML
import shaderColors
body_color_key = "white body"
body_color = shaderColors.named_colors[body_color_key].getDiffuseFloat()
pins_color_key = "metal grey pins"
pins_color = shaderColors.named_colors[pins_color_key].getDiffuseFloat()
top_color_key = "resistor black body"
top_color = shaderColors.named_colors[top_color_key].getDiffuseFloat()
# maui start
import FreeCAD, Draft, FreeCADGui
import ImportGui
import FreeCADGui as Gui
import yaml
#from Gui.Command import *
outdir=os.path.dirname(os.path.realpath(__file__)+"/../_3Dmodels")
scriptdir=os.path.dirname(os.path.realpath(__file__))
sys.path.append(outdir)
sys.path.append(scriptdir)
if FreeCAD.GuiUp:
from PySide import QtCore, QtGui
# Licence information of the generated models.
#################################################################################################
STR_licAuthor = "kicad StepUp"
STR_licEmail = "ksu"
STR_licOrgSys = "kicad StepUp"
STR_licPreProc = "OCC"
STR_licOrg = "FreeCAD"
LIST_license = ["",]
#################################################################################################
try:
# Gui.SendMsgToActiveView("Run")
#from Gui.Command import *
Gui.activateWorkbench("CadQueryWorkbench")
import cadquery as cq
from Helpers import show
# CadQuery Gui
except Exception as e: # catch *all* exceptions
print(e)
msg="missing CadQuery 0.3.0 or later Module!\r\n\r\n"
msg+="https://github.com/jmwright/cadquery-freecad-module/wiki\n"
reply = QtGui.QMessageBox.information(None,"Info ...",msg)
# maui end
# Import cad_tools
from cqToolsExceptions import *
# Import cad_tools
import cq_cad_tools
# Explicitly load all needed functions
from cq_cad_tools import FuseObjs_wColors, GetListOfObjects, restore_Main_Tools, \
exportSTEP, close_CQ_Example, exportVRML, saveFCdoc, z_RotateObject, Color_Objects, \
CutObjs_wColors, checkRequirements
#checking requirements
checkRequirements(cq)
# Sphinx workaround #1
try:
QtGui
except NameError:
QtGui = None
#
try:
close_CQ_Example(App, Gui)
except: # catch *all* exceptions
print("CQ 030 doesn't open example file")
def make_chip(model, all_params):
# dimensions for chip capacitors
length = all_params[model]['length'] # package length
width = all_params[model]['width'] # package width
height = all_params[model]['height'] # package height
pin_band = all_params[model]['pin_band'] # pin band
pin_thickness = all_params[model]['pin_thickness'] # pin thickness
if pin_thickness == 'auto':
pin_thickness = height/10.
edge_fillet = all_params[model]['edge_fillet'] # fillet of edges
if edge_fillet == 'auto':
edge_fillet = pin_thickness
# Create a 3D box based on the dimension variables above and fillet it
case = cq.Workplane("XY").workplane(offset=pin_thickness). \
box(length-2*pin_thickness, width, height-2*pin_thickness,centered=(True, True, False))
top = cq.Workplane("XY").workplane(offset=height-pin_thickness).box(length-2*pin_band, width, pin_thickness,centered=(True, True, False))
# Create a 3D box based on the dimension variables above and fillet it
pin1 = cq.Workplane("XY").box(pin_band, width, height)
pin1.edges("|Y").fillet(edge_fillet)
pin1=pin1.translate((-length/2+pin_band/2,0,height/2)).rotate((0,0,0), (0,0,1), 0)
pin2 = cq.Workplane("XY").box(pin_band, width, height)
pin2.edges("|Y").fillet(edge_fillet)
pin2=pin2.translate((length/2-pin_band/2,0,height/2)).rotate((0,0,0), (0,0,1), 0)
pins = pin1.union(pin2)
#body_copy.ShapeColor=result.ShapeColor
# extract case from pins
# case = case.cut(pins)
pins = pins.cut(case)
return (case, top, pins)
#import step_license as L
import add_license as Lic
if __name__ == "__main__" or __name__ == "main_generator_SMD":
destination_dir = '/Fuse.3dshapes'
expVRML.say(expVRML.__file__)
FreeCAD.Console.PrintMessage('\r\nRunning...\r\n')
full_path=os.path.realpath(__file__)
expVRML.say(full_path)
scriptdir=os.path.dirname(os.path.realpath(__file__))
expVRML.say(scriptdir)
sub_path = full_path.split(scriptdir)
expVRML.say(sub_path)
sub_dir_name =full_path.split(os.sep)[-2]
expVRML.say(sub_dir_name)
sub_path = full_path.split(sub_dir_name)[0]
expVRML.say(sub_path)
models_dir=sub_path+"_3Dmodels"
#expVRML.say(models_dir)
#stop
try:
with open('cq_parameters_SMD.yaml', 'r') as f:
all_params = yaml.load(f)
except yaml.YAMLError as exc:
print(exc)
from sys import argv
models = []
if len(sys.argv) < 3:
FreeCAD.Console.PrintMessage('No variant name is given! building:\n')
model_to_build = list(all_params.keys())[0]
print(model_to_build)
else:
model_to_build = sys.argv[2]
if model_to_build == "all":
models = all_params
save_memory=True
else:
models = [model_to_build]
for model in models:
if not model in all_params.keys():
print("Parameters for %s doesn't exist in 'all_params', skipping." % model)
continue
ModelName = model
CheckedModelName = ModelName.replace('.', '').replace('-', '_').replace('(', '').replace(')', '')
Newdoc = App.newDocument(CheckedModelName)
App.setActiveDocument(CheckedModelName)
Gui.ActiveDocument=Gui.getDocument(CheckedModelName)
body, pins, top = make_chip(model, all_params)
show(body)
show(pins)
show(top)
doc = FreeCAD.ActiveDocument
objs = GetListOfObjects(FreeCAD, doc)
Color_Objects(Gui,objs[0],body_color)
Color_Objects(Gui,objs[1],top_color)
Color_Objects(Gui,objs[2],pins_color)
col_body=Gui.ActiveDocument.getObject(objs[0].Name).DiffuseColor[0]
col_top=Gui.ActiveDocument.getObject(objs[1].Name).DiffuseColor[0]
col_pin=Gui.ActiveDocument.getObject(objs[2].Name).DiffuseColor[0]
material_substitutions={
col_body[:-1]:body_color_key,
col_pin[:-1]:pins_color_key,
col_top[:-1]:top_color_key
}
expVRML.say(material_substitutions)
del objs
objs=GetListOfObjects(FreeCAD, doc)
FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
objs=GetListOfObjects(FreeCAD, doc)
FuseObjs_wColors(FreeCAD, FreeCADGui, doc.Name, objs[0].Name, objs[1].Name)
doc.Label = CheckedModelName
objs=GetListOfObjects(FreeCAD, doc)
objs[0].Label = CheckedModelName
restore_Main_Tools()
#rotate if required
rotation = all_params[model]['rotation']
if (rotation!=0):
z_RotateObject(doc, rotation)
#out_dir=destination_dir+all_params[variant].dest_dir_prefix+'/'
script_dir=os.path.dirname(os.path.realpath(__file__))
#models_dir=script_dir+"/../_3Dmodels"
expVRML.say(models_dir)
out_dir=models_dir+destination_dir
if not os.path.exists(out_dir):
os.makedirs(out_dir)
#out_dir="./generated_qfp/"
# export STEP model
exportSTEP(doc, ModelName, out_dir)
if LIST_license[0]=="":
LIST_license=Lic.LIST_int_license
LIST_license.append("")
Lic.addLicenseToStep(out_dir+'/', ModelName+".step", LIST_license,\
STR_licAuthor, STR_licEmail, STR_licOrgSys, STR_licOrg, STR_licPreProc)
# scale and export Vrml model
scale=1/2.54
#exportVRML(doc,ModelName,scale,out_dir)
objs=GetListOfObjects(FreeCAD, doc)
expVRML.say("######################################################################")
expVRML.say(objs)
expVRML.say("######################################################################")
export_objects, used_color_keys = expVRML.determineColors(Gui, objs, material_substitutions)
export_file_name=out_dir+os.sep+ModelName+'.wrl'
colored_meshes = expVRML.getColoredMesh(Gui, export_objects , scale)
expVRML.writeVRMLFile(colored_meshes, export_file_name, used_color_keys, LIST_license)
# Save the doc in Native FC format
if save_memory == False:
Gui.SendMsgToActiveView("ViewFit")
Gui.activeDocument().activeView().viewAxometric()
# Save the doc in Native FC format
saveFCdoc(App, Gui, doc, ModelName,out_dir, False)
check_Model=True
if save_memory == True or check_Model==True:
doc=FreeCAD.ActiveDocument
FreeCAD.closeDocument(doc.Name)
step_path=os.path.join(out_dir,ModelName+u'.step')
if check_Model==True:
#ImportGui.insert(step_path,ModelName)
ImportGui.open(step_path)
docu = FreeCAD.ActiveDocument
if cq_cad_tools.checkUnion(docu) == True:
FreeCAD.Console.PrintMessage('step file is correctly Unioned\n')
else:
FreeCAD.Console.PrintError('step file is NOT Unioned\n')
stop
FC_majorV=int(FreeCAD.Version()[0])
FC_minorV=int(FreeCAD.Version()[1][0:FreeCAD.Version()[1].find('.')])
print("Minor version: "+str(FC_minorV))
if FC_majorV == 0 and FC_minorV >= 17:
for o in docu.Objects:
if hasattr(o,'Shape'):
chks=cq_cad_tools.checkBOP(o.Shape)
print ('chks ',chks)
print (cq_cad_tools.mk_string(o.Label))
if chks != True:
msg='shape \''+o.Name+'\' \''+cq_cad_tools.mk_string(o.Label)+'\' is INVALID!\n'
FreeCAD.Console.PrintError(msg)
FreeCAD.Console.PrintWarning(chks[0])
stop
else:
msg='shape \''+o.Name+'\' \''+cq_cad_tools.mk_string(o.Label)+'\' is valid\n'
FreeCAD.Console.PrintMessage(msg)
else:
FreeCAD.Console.PrintError('BOP check requires FC 0.17+\n')
# Save the doc in Native FC format
saveFCdoc(App, Gui, docu, ModelName,out_dir, False)
doc=FreeCAD.ActiveDocument
FreeCAD.closeDocument(doc.Name)
|
gpl-2.0
| -5,632,057,004,259,708,000
| 38.547826
| 141
| 0.591469
| false
| 3.632588
| false
| false
| false
|
kalyptorisk/daversy
|
src/daversy/db/oracle/index.py
|
1
|
3580
|
from daversy.utils import *
from daversy.db.object import Index, IndexColumn
class IndexColumnBuilder(object):
""" Represents a builder for a column in an index. """
DbClass = IndexColumn
XmlTag = 'index-column'
Query = """
SELECT c.column_name, lower(c.descend) AS sort, i.index_name,
i.table_name, c.column_position AS position,
e.column_expression AS expression
FROM sys.user_indexes i, sys.user_ind_columns c,
sys.user_ind_expressions e
WHERE i.index_name = c.index_name
AND i.table_name = c.table_name
AND c.index_name = e.index_name (+)
AND c.column_position = e.column_position (+)
ORDER BY i.index_name, c.column_position
"""
PropertyList = odict(
('COLUMN_NAME', Property('name')),
('SORT', Property('sort')),
('EXPRESSION', Property('expression', exclude=True)),
('INDEX_NAME', Property('index-name', exclude=True)),
('TABLE_NAME', Property('table-name', exclude=True)),
('POSITION', Property('position', exclude=True)),
)
@staticmethod
def addToState(state, column):
table = state.tables.get(column['table-name'])
real = table and table.columns.get(column.name)
if column.expression and not real: # function-based columns have no name
column.name = column.expression
index = state.indexes.get(column['index-name'])
if index:
index.columns[column.name] = column
class IndexBuilder(object):
""" Represents a builder for a index on a table. """
DbClass = Index
XmlTag = 'index'
Query = """
SELECT i.index_name, i.table_name,
decode(i.uniqueness, 'UNIQUE', 'true', 'false') AS is_unique,
decode(i.index_type, 'BITMAP', 'true') AS is_bitmap,
DECODE(i.compression, 'ENABLED', i.prefix_length) AS "COMPRESS"
FROM sys.user_indexes i
WHERE i.index_type IN ('NORMAL', 'FUNCTION-BASED NORMAL', 'BITMAP')
ORDER BY i.index_name
"""
PropertyList = odict(
('INDEX_NAME', Property('name')),
('IS_UNIQUE', Property('unique')),
('IS_BITMAP', Property('bitmap')),
('TABLE_NAME', Property('table-name')),
('COMPRESS', Property('compress'))
)
@staticmethod
def addToState(state, index):
# ensure that the table exists and the index is not for a PK/UK
table = state.tables.get(index['table-name'])
if table:
if table.primary_keys.has_key(index.name) or table.unique_keys.has_key(index.name):
return
state.indexes[index.name] = index
@staticmethod
def isAllowed(state, index):
return state.tables.get(index['table-name'])
@staticmethod
def createSQL(index):
sql = "CREATE %(unique)s %(bitmap)s INDEX %(name)s ON %(table-name)s (\n" \
" %(column_sql)s\n)%(suffix)s\n/\n"
column_def = ["%(name)-30s %(sort)s" % column for column
in index.columns.values()]
column_sql = ",\n ".join(column_def)
unique = index.unique == 'true' and 'UNIQUE' or ''
bitmap = index.bitmap == 'true' and 'BITMAP' or ''
suffix = ''
if index.compress:
suffix = ' COMPRESS '+index.compress
return render(sql, index, unique=unique, bitmap=bitmap,
suffix=suffix, column_sql=column_sql)
|
gpl-2.0
| 1,298,916,235,426,265,300
| 35.907216
| 95
| 0.569832
| false
| 3.824786
| false
| false
| false
|
patrick91/pycon
|
backend/notifications/aws.py
|
1
|
2184
|
import typing
from urllib.parse import urljoin
import boto3
from django.conf import settings
from newsletters.exporter import Endpoint
from users.models import User
def _get_client():
return boto3.client("pinpoint", region_name="eu-central-1")
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i : i + n] # noqa
def send_endpoints_to_pinpoint(endpoints: typing.Iterable[Endpoint]):
# batch only supports 100 at the time
endpoint_chunks = chunks(list(endpoints), 100)
for endpoints_chunk in endpoint_chunks:
data = {"Item": [endpoint.to_item() for endpoint in endpoints_chunk]}
client = _get_client()
client.update_endpoints_batch(
ApplicationId=settings.PINPOINT_APPLICATION_ID, EndpointBatchRequest=data
)
def send_notification(
template_name: str,
users: typing.List[User],
substitutions: typing.Dict[str, typing.List[str]],
):
client = _get_client()
client.send_users_messages(
ApplicationId=settings.PINPOINT_APPLICATION_ID,
SendUsersMessageRequest={
"MessageConfiguration": {
"EmailMessage": {
"FromAddress": "noreply@pycon.it",
"Substitutions": substitutions,
}
},
"TemplateConfiguration": {"EmailTemplate": {"Name": template_name}},
"Users": {str(user.id): {} for user in users},
},
)
# TODO: validate that it has been sent correctly
def send_comment_notification(comment):
submission = comment.submission
users: typing.Set[User] = set([submission.speaker])
# also send notification to all other commenters
users = users.union(set([comment.author for comment in submission.comments.all()]))
# don't notify current user
users.discard(comment.author)
if not users:
return
submission_url = urljoin(
settings.FRONTEND_URL, f"/en/submission/{submission.hashid}"
)
substitutions = {
"submission_url": [submission_url],
"submission": [submission.title],
}
send_notification("pycon-11-new-comment-on-submission", users, substitutions)
|
mit
| 7,613,541,312,755,594,000
| 27.736842
| 87
| 0.642399
| false
| 4.044444
| false
| false
| false
|
jcushman/pywb
|
pywb/rewrite/cookie_rewriter.py
|
1
|
4929
|
from Cookie import SimpleCookie, CookieError
#=================================================================
class WbUrlBaseCookieRewriter(object):
""" Base Cookie rewriter for wburl-based requests.
"""
def __init__(self, url_rewriter):
self.url_rewriter = url_rewriter
def rewrite(self, cookie_str, header='Set-Cookie'):
results = []
cookie = SimpleCookie()
try:
cookie.load(cookie_str)
except CookieError:
return results
for name, morsel in cookie.iteritems():
morsel = self.rewrite_cookie(name, morsel)
if morsel:
path = morsel.get('path')
if path:
inx = path.find(self.url_rewriter.rel_prefix)
if inx > 0:
morsel['path'] = path[inx:]
results.append((header, morsel.OutputString()))
return results
def _remove_age_opts(self, morsel):
# remove expires as it refers to archived time
if morsel.get('expires'):
del morsel['expires']
# don't use max-age, just expire at end of session
if morsel.get('max-age'):
del morsel['max-age']
# for now, also remove secure to avoid issues when
# proxying over plain http (TODO: detect https?)
if morsel.get('secure'):
del morsel['secure']
#=================================================================
class RemoveAllCookiesRewriter(WbUrlBaseCookieRewriter):
def rewrite(self, cookie_str, header='Set-Cookie'):
return []
#=================================================================
class MinimalScopeCookieRewriter(WbUrlBaseCookieRewriter):
"""
Attempt to rewrite cookies to minimal scope possible
If path present, rewrite path to current rewritten url only
If domain present, remove domain and set to path prefix
"""
def rewrite_cookie(self, name, morsel):
# if domain set, no choice but to expand cookie path to root
if morsel.get('domain'):
del morsel['domain']
morsel['path'] = self.url_rewriter.rel_prefix
# else set cookie to rewritten path
elif morsel.get('path'):
morsel['path'] = self.url_rewriter.rewrite(morsel['path'])
self._remove_age_opts(morsel)
return morsel
#=================================================================
class HostScopeCookieRewriter(WbUrlBaseCookieRewriter):
"""
Attempt to rewrite cookies to current host url..
If path present, rewrite path to current host. Only makes sense in live
proxy or no redirect mode, as otherwise timestamp may change.
If domain present, remove domain and set to path prefix
"""
def rewrite_cookie(self, name, morsel):
# if domain set, expand cookie to host prefix
if morsel.get('domain'):
del morsel['domain']
morsel['path'] = self.url_rewriter.rewrite('/')
# set cookie to rewritten path
elif morsel.get('path'):
morsel['path'] = self.url_rewriter.rewrite(morsel['path'])
self._remove_age_opts(morsel)
return morsel
#=================================================================
class ExactPathCookieRewriter(WbUrlBaseCookieRewriter):
"""
Rewrite cookies only using exact path, useful for live rewrite
without a timestamp and to minimize cookie pollution
If path or domain present, simply remove
"""
def rewrite_cookie(self, name, morsel):
if morsel.get('domain'):
del morsel['domain']
# else set cookie to rewritten path
if morsel.get('path'):
del morsel['path']
self._remove_age_opts(morsel)
return morsel
#=================================================================
class RootScopeCookieRewriter(WbUrlBaseCookieRewriter):
"""
Sometimes it is necessary to rewrite cookies to root scope
in order to work across time boundaries and modifiers
This rewriter simply sets all cookies to be in the root
"""
def rewrite_cookie(self, name, morsel):
# get root path
morsel['path'] = self.url_rewriter.root_path
# remove domain
if morsel.get('domain'):
del morsel['domain']
self._remove_age_opts(morsel)
return morsel
#=================================================================
def get_cookie_rewriter(cookie_scope):
if cookie_scope == 'root':
return RootScopeCookieRewriter
elif cookie_scope == 'exact':
return ExactPathCookieRewriter
elif cookie_scope == 'host':
return HostScopeCookieRewriter
elif cookie_scope == 'removeall':
return RemoveAllCookiesRewriter
elif cookie_scope == 'coll':
return MinimalScopeCookieRewriter
else:
return HostScopeCookieRewriter
|
gpl-3.0
| -1,616,446,436,483,166,000
| 31.006494
| 75
| 0.564212
| false
| 4.526171
| false
| false
| false
|
colloquium/spacewalk
|
client/solaris/smartpm/smart/interfaces/gtk/interactive.py
|
1
|
31919
|
#
# Copyright (c) 2004 Conectiva, Inc.
#
# Written by Gustavo Niemeyer <niemeyer@conectiva.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# Smart Package Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Smart Package Manager; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
from smart.transaction import INSTALL, REMOVE, UPGRADE, REINSTALL, KEEP, FIX
from smart.transaction import Transaction, ChangeSet, checkPackages
from smart.transaction import PolicyInstall, PolicyRemove, PolicyUpgrade
from smart.interfaces.gtk.channels import GtkChannels, GtkChannelSelector
from smart.interfaces.gtk.mirrors import GtkMirrors
from smart.interfaces.gtk.flags import GtkFlags
from smart.interfaces.gtk.priorities import GtkPriorities, GtkSinglePriority
from smart.interfaces.gtk.packageview import GtkPackageView
from smart.interfaces.gtk.packageinfo import GtkPackageInfo
from smart.interfaces.gtk.interface import GtkInterface
from smart.interfaces.gtk import getPixbuf
from smart.const import NEVER, VERSION
from smart.searcher import Searcher
from smart.cache import Package
from smart import *
import shlex, re
import fnmatch
import gtk
UI = """
<ui>
<menubar>
<menu action="file">
<menuitem action="update-selected-channels"/>
<menuitem action="update-channels"/>
<separator/>
<menuitem action="rebuild-cache"/>
<separator/>
<menuitem action="exec-changes"/>
<separator/>
<menuitem action="quit"/>
</menu>
<menu action="edit">
<menuitem action="undo"/>
<menuitem action="redo"/>
<menuitem action="clear-changes"/>
<separator/>
<menuitem action="upgrade-all"/>
<menuitem action="fix-all-problems"/>
<separator/>
<menuitem action="check-installed-packages"/>
<menuitem action="check-uninstalled-packages"/>
<menuitem action="check-all-packages"/>
<separator/>
<menuitem action="find"/>
<separator/>
<menuitem action="edit-channels"/>
<menuitem action="edit-mirrors"/>
<menuitem action="edit-flags"/>
<menuitem action="edit-priorities"/>
</menu>
<menu action="view">
<menuitem action="hide-non-upgrades"/>
<menuitem action="hide-installed"/>
<menuitem action="hide-uninstalled"/>
<menuitem action="hide-unmarked"/>
<menuitem action="hide-old"/>
<separator/>
<menuitem action="expand-all"/>
<menuitem action="collapse-all"/>
<separator/>
<menu action="tree-style">
<menuitem action="tree-style-groups"/>
<menuitem action="tree-style-channels"/>
<menuitem action="tree-style-channels-groups"/>
<menuitem action="tree-style-none"/>
</menu>
<separator/>
<menuitem action="summary-window"/>
<menuitem action="log-window"/>
</menu>
</menubar>
<toolbar>
<toolitem action="update-channels"/>
<separator/>
<toolitem action="exec-changes"/>
<separator/>
<toolitem action="undo"/>
<toolitem action="redo"/>
<toolitem action="clear-changes"/>
<separator/>
<toolitem action="upgrade-all"/>
<separator/>
<toolitem action="find"/>
</toolbar>
</ui>
"""
ACTIONS = [
("file", None, _("_File")),
("update-selected-channels", "gtk-refresh", _("Update _Selected Channels..."), None,
_("Update given channels"), "self.updateChannels(True)"),
("update-channels", "gtk-refresh", _("_Update Channels"), None,
_("Update channels"), "self.updateChannels()"),
("rebuild-cache", None, _("_Rebuild Cache"), None,
_("Reload package information"), "self.rebuildCache()"),
("exec-changes", "gtk-execute", _("_Execute Changes..."), "<control>c",
_("Apply marked changes"), "self.applyChanges()"),
("quit", "gtk-quit", _("_Quit"), "<control>q",
_("Quit application"), "gtk.main_quit()"),
("edit", None, _("_Edit")),
("undo", "gtk-undo", _("_Undo"), "<control>z",
_("Undo last change"), "self.undo()"),
("redo", "gtk-redo", _("_Redo"), "<control><shift>z",
_("Redo last undone change"), "self.redo()"),
("clear-changes", "gtk-clear", _("Clear Marked Changes"), None,
_("Clear all changes"), "self.clearChanges()"),
("check-installed-packages", None, _("Check Installed Packages..."), None,
_("Check installed packages"), "self.checkPackages()"),
("check-uninstalled-packages", None, _("Check Uninstalled Packages..."), None,
_("Check uninstalled packages"), "self.checkPackages(uninstalled=True)"),
("check-all-packages", None, _("Check All Packages..."), None,
_("Check all packages"), "self.checkPackages(all=True)"),
("upgrade-all", "gtk-go-up", _("Upgrade _All..."), None,
_("Upgrade all packages"), "self.upgradeAll()"),
("fix-all-problems", None, _("Fix All _Problems..."), None,
_("Fix all problems"), "self.fixAllProblems()"),
("find", "gtk-find", _("_Find..."), "<control>f",
_("Find packages"), "self.toggleSearch()"),
("edit-channels", None, _("_Channels"), None,
_("Edit channels"), "self.editChannels()"),
("edit-mirrors", None, _("_Mirrors"), None,
_("Edit mirrors"), "self.editMirrors()"),
("edit-flags", None, _("_Flags"), None,
_("Edit package flags"), "self.editFlags()"),
("edit-priorities", None, _("_Priorities"), None,
_("Edit package priorities"), "self.editPriorities()"),
("view", None, _("_View")),
("tree-style", None, _("_Tree Style")),
("expand-all", "gtk-open", _("_Expand All"), None,
_("Expand all items in the tree"), "self._pv.getTreeView().expand_all()"),
("collapse-all", "gtk-close", _("_Collapse All"), None,
_("Collapse all items in the tree"), "self._pv.getTreeView().collapse_all()"),
("summary-window", None, _("_Summary Window"), "<control>s",
_("Show summary window"), "self.showChanges()"),
("log-window", None, _("_Log Window"), None,
_("Show log window"), "self._log.show()"),
]
def compileActions(actions, globals):
newactions = []
for action in actions:
if len(action) > 5:
action = list(action)
code = compile(action[5], "<callback>", "exec")
def callback(action, code=code, globals=globals):
globals["action"] = action
exec code in globals
action[5] = callback
newactions.append(tuple(action))
return newactions
class GtkInteractiveInterface(GtkInterface):
def __init__(self, ctrl):
GtkInterface.__init__(self, ctrl)
self._changeset = None
self._window = gtk.Window()
self._window.set_title("Smart Package Manager %s" % VERSION)
self._window.set_position(gtk.WIN_POS_CENTER)
self._window.set_geometry_hints(min_width=640, min_height=480)
self._window.connect("destroy", lambda x: gtk.main_quit())
self._log.set_transient_for(self._window)
self._progress.set_transient_for(self._window)
self._hassubprogress.set_transient_for(self._window)
self._watch = gtk.gdk.Cursor(gtk.gdk.WATCH)
self._undo = []
self._redo = []
self._topvbox = gtk.VBox()
self._topvbox.show()
self._window.add(self._topvbox)
globals = {"self": self, "gtk": gtk}
self._actions = gtk.ActionGroup("Actions")
self._actions.add_actions(compileActions(ACTIONS, globals))
self._filters = {}
for name, label in [("hide-non-upgrades", _("Hide Non-upgrades")),
("hide-installed", _("Hide Installed")),
("hide-uninstalled", _("Hide Uninstalled")),
("hide-unmarked", _("Hide Unmarked")),
("hide-old", _("Hide Old"))]:
action = gtk.ToggleAction(name, label, "", "")
action.connect("toggled", lambda x, y: self.toggleFilter(y), name)
self._actions.add_action(action)
treestyle = sysconf.get("package-tree")
lastaction = None
for name, label in [("groups", _("Groups")),
("channels", _("Channels")),
("channels-groups", _("Channels & Groups")),
("none", _("None"))]:
action = gtk.RadioAction("tree-style-"+name, label, "", "", 0)
if name == treestyle:
action.set_active(True)
if lastaction:
action.set_group(lastaction)
lastaction = action
action.connect("toggled", lambda x, y: self.setTreeStyle(y), name)
self._actions.add_action(action)
self._ui = gtk.UIManager()
self._ui.insert_action_group(self._actions, 0)
self._ui.add_ui_from_string(UI)
self._menubar = self._ui.get_widget("/menubar")
self._topvbox.pack_start(self._menubar, False)
self._toolbar = self._ui.get_widget("/toolbar")
self._toolbar.set_style(gtk.TOOLBAR_ICONS)
self._topvbox.pack_start(self._toolbar, False)
self._window.add_accel_group(self._ui.get_accel_group())
self._execmenuitem = self._ui.get_action("/menubar/file/exec-changes")
self._execmenuitem.set_property("sensitive", False)
self._clearmenuitem = self._ui.get_action("/menubar/edit/clear-changes")
self._clearmenuitem.set_property("sensitive", False)
self._undomenuitem = self._ui.get_action("/menubar/edit/undo")
self._undomenuitem.set_property("sensitive", False)
self._redomenuitem = self._ui.get_action("/menubar/edit/redo")
self._redomenuitem.set_property("sensitive", False)
# Search bar
self._searchbar = gtk.Alignment()
self._searchbar.set(0, 0, 1, 1)
self._searchbar.set_padding(3, 3, 0, 0)
self._topvbox.pack_start(self._searchbar, False)
searchvp = gtk.Viewport()
searchvp.set_shadow_type(gtk.SHADOW_OUT)
searchvp.show()
self._searchbar.add(searchvp)
searchtable = gtk.Table(1, 1)
searchtable.set_row_spacings(5)
searchtable.set_col_spacings(5)
searchtable.set_border_width(5)
searchtable.show()
searchvp.add(searchtable)
label = gtk.Label(_("Search:"))
label.show()
searchtable.attach(label, 0, 1, 0, 1, 0, 0)
self._searchentry = gtk.Entry()
self._searchentry.connect("activate", lambda x: self.refreshPackages())
self._searchentry.show()
searchtable.attach(self._searchentry, 1, 2, 0, 1)
button = gtk.Button()
button.set_relief(gtk.RELIEF_NONE)
button.connect("clicked", lambda x: self.refreshPackages())
button.show()
searchtable.attach(button, 2, 3, 0, 1, 0, 0)
image = gtk.Image()
image.set_from_stock("gtk-find", gtk.ICON_SIZE_BUTTON)
image.show()
button.add(image)
align = gtk.Alignment()
align.set(1, 0, 0, 0)
align.set_padding(0, 0, 10, 0)
align.show()
searchtable.attach(align, 3, 4, 0, 1, gtk.FILL, gtk.FILL)
button = gtk.Button()
button.set_size_request(20, 20)
button.set_relief(gtk.RELIEF_NONE)
button.connect("clicked", lambda x: self.toggleSearch())
button.show()
align.add(button)
image = gtk.Image()
image.set_from_stock("gtk-close", gtk.ICON_SIZE_MENU)
image.show()
button.add(image)
hbox = gtk.HBox()
hbox.set_spacing(10)
hbox.show()
searchtable.attach(hbox, 1, 2, 1, 2)
self._searchname = gtk.RadioButton(None, _("Automatic"))
self._searchname.set_active(True)
self._searchname.connect("clicked", lambda x: self.refreshPackages())
self._searchname.show()
hbox.pack_start(self._searchname, False)
self._searchdesc = gtk.RadioButton(self._searchname, _("Description"))
self._searchdesc.connect("clicked", lambda x: self.refreshPackages())
self._searchdesc.show()
hbox.pack_start(self._searchdesc, False)
# Packages and information
self._vpaned = gtk.VPaned()
self._vpaned.show()
self._topvbox.pack_start(self._vpaned)
self._pv = GtkPackageView()
self._pv.show()
self._vpaned.pack1(self._pv, True)
self._pi = GtkPackageInfo()
self._pi.show()
self._pv.connect("package_selected",
lambda x, y: self._pi.setPackage(y))
self._pv.connect("package_activated",
lambda x, y: self.actOnPackages(y))
self._pv.connect("package_popup", self.packagePopup)
self._vpaned.pack2(self._pi, False)
self._status = gtk.Statusbar()
self._status.show()
self._topvbox.pack_start(self._status, False)
def showStatus(self, msg):
self._status.pop(0)
self._status.push(0, msg)
while gtk.events_pending():
gtk.main_iteration()
def hideStatus(self):
self._status.pop(0)
while gtk.events_pending():
gtk.main_iteration()
def run(self, command=None, argv=None):
self.setCatchExceptions(True)
self._window.set_icon(getPixbuf("smart"))
self._window.show()
self._ctrl.reloadChannels()
self._changeset = ChangeSet(self._ctrl.getCache())
self._pi.setChangeSet(self._changeset)
self._progress.hide()
self.refreshPackages()
gtk.main()
self.setCatchExceptions(False)
# Non-standard interface methods:
def getChangeSet(self):
return self._changeset
def updateChannels(self, selected=False, channels=None):
if selected:
aliases = GtkChannelSelector().show()
channels = [channel for channel in self._ctrl.getChannels()
if channel.getAlias() in aliases]
if not channels:
return
state = self._changeset.getPersistentState()
self._ctrl.reloadChannels(channels, caching=NEVER)
self._changeset.setPersistentState(state)
self.refreshPackages()
def rebuildCache(self):
state = self._changeset.getPersistentState()
self._ctrl.reloadChannels()
self._changeset.setPersistentState(state)
self.refreshPackages()
def applyChanges(self):
transaction = Transaction(self._ctrl.getCache(),
changeset=self._changeset)
if self._ctrl.commitTransaction(transaction):
del self._undo[:]
del self._redo[:]
self._redomenuitem.set_property("sensitive", False)
self._undomenuitem.set_property("sensitive", False)
self._changeset.clear()
self._ctrl.reloadChannels()
self.refreshPackages()
self.changedMarks()
self._progress.hide()
def clearChanges(self):
self.saveUndo()
self._changeset.clear()
self.changedMarks()
def showChanges(self):
return self._changes.showChangeSet(self._changeset)
def toggleFilter(self, filter):
if filter in self._filters:
del self._filters[filter]
else:
self._filters[filter] = True
self.refreshPackages()
def upgradeAll(self):
transaction = Transaction(self._ctrl.getCache())
transaction.setState(self._changeset)
for pkg in self._ctrl.getCache().getPackages():
if pkg.installed:
transaction.enqueue(pkg, UPGRADE)
transaction.setPolicy(PolicyUpgrade)
transaction.run()
changeset = transaction.getChangeSet()
if changeset != self._changeset:
if self.confirmChange(self._changeset, changeset):
self.saveUndo()
self._changeset.setState(changeset)
self.changedMarks()
if self.askYesNo(_("Apply marked changes now?"), True):
self.applyChanges()
else:
self.showStatus(_("No interesting upgrades available!"))
def actOnPackages(self, pkgs, op=None):
cache = self._ctrl.getCache()
transaction = Transaction(cache, policy=PolicyInstall)
transaction.setState(self._changeset)
changeset = transaction.getChangeSet()
if op is None:
if not [pkg for pkg in pkgs if pkg not in changeset]:
op = KEEP
else:
for pkg in pkgs:
if not pkg.installed:
op = INSTALL
break
else:
op = REMOVE
if op is REMOVE:
transaction.setPolicy(PolicyRemove)
policy = transaction.getPolicy()
for pkg in pkgs:
if op is KEEP:
transaction.enqueue(pkg, op)
elif op in (REMOVE, REINSTALL, FIX):
if pkg.installed:
transaction.enqueue(pkg, op)
if op is REMOVE:
for _pkg in cache.getPackages(pkg.name):
if not _pkg.installed:
policy.setLocked(_pkg, True)
elif op is INSTALL:
if not pkg.installed:
transaction.enqueue(pkg, op)
transaction.run()
if op is FIX:
expected = 0
else:
expected = 1
if self.confirmChange(self._changeset, changeset, expected):
self.saveUndo()
self._changeset.setState(changeset)
self.changedMarks()
def packagePopup(self, packageview, pkgs, event):
menu = gtk.Menu()
hasinstalled = bool([pkg for pkg in pkgs if pkg.installed
and self._changeset.get(pkg) is not REMOVE])
hasnoninstalled = bool([pkg for pkg in pkgs if not pkg.installed
and self._changeset.get(pkg) is not INSTALL])
image = gtk.Image()
image.set_from_pixbuf(getPixbuf("package-install"))
item = gtk.ImageMenuItem(_("Install"))
item.set_image(image)
item.connect("activate", lambda x: self.actOnPackages(pkgs, INSTALL))
if not hasnoninstalled:
item.set_sensitive(False)
menu.append(item)
image = gtk.Image()
image.set_from_pixbuf(getPixbuf("package-reinstall"))
item = gtk.ImageMenuItem(_("Reinstall"))
item.set_image(image)
item.connect("activate", lambda x: self.actOnPackages(pkgs, REINSTALL))
if not hasinstalled:
item.set_sensitive(False)
menu.append(item)
image = gtk.Image()
image.set_from_pixbuf(getPixbuf("package-remove"))
item = gtk.ImageMenuItem(_("Remove"))
item.set_image(image)
item.connect("activate", lambda x: self.actOnPackages(pkgs, REMOVE))
if not hasinstalled:
item.set_sensitive(False)
menu.append(item)
image = gtk.Image()
if not hasinstalled:
image.set_from_pixbuf(getPixbuf("package-available"))
else:
image.set_from_pixbuf(getPixbuf("package-installed"))
item = gtk.ImageMenuItem(_("Keep"))
item.set_image(image)
item.connect("activate", lambda x: self.actOnPackages(pkgs, KEEP))
if not [pkg for pkg in pkgs if pkg in self._changeset]:
item.set_sensitive(False)
menu.append(item)
image = gtk.Image()
image.set_from_pixbuf(getPixbuf("package-broken"))
item = gtk.ImageMenuItem(_("Fix problems"))
item.set_image(image)
item.connect("activate", lambda x: self.actOnPackages(pkgs, FIX))
if not hasinstalled:
item.set_sensitive(False)
menu.append(item)
inconsistent = False
thislocked = None
alllocked = None
names = pkgconf.getFlagTargets("lock")
if [pkg for pkg in pkgs if pkg in self._changeset]:
inconsistent = True
else:
for pkg in pkgs:
if (names and pkg.name in names and
("=", pkg.version) in names[pkg.name]):
newthislocked = True
newalllocked = len(names[pkg.name]) > 1
else:
newthislocked = False
newalllocked = pkgconf.testFlag("lock", pkg)
if (thislocked is not None and thislocked != newthislocked or
alllocked is not None and alllocked != newalllocked):
inconsistent = True
break
thislocked = newthislocked
alllocked = newalllocked
image = gtk.Image()
if thislocked:
item = gtk.ImageMenuItem(_("Unlock this version"))
if not hasnoninstalled:
image.set_from_pixbuf(getPixbuf("package-installed"))
else:
image.set_from_pixbuf(getPixbuf("package-available"))
def unlock_this(x):
for pkg in pkgs:
pkgconf.clearFlag("lock", pkg.name, "=", pkg.version)
self._pv.queue_draw()
self._pi.setPackage(pkgs[0])
item.connect("activate", unlock_this)
else:
item = gtk.ImageMenuItem(_("Lock this version"))
if not hasnoninstalled:
image.set_from_pixbuf(getPixbuf("package-installed-locked"))
else:
image.set_from_pixbuf(getPixbuf("package-available-locked"))
def lock_this(x):
for pkg in pkgs:
pkgconf.setFlag("lock", pkg.name, "=", pkg.version)
self._pv.queue_draw()
self._pi.setPackage(pkgs[0])
item.connect("activate", lock_this)
item.set_image(image)
if inconsistent:
item.set_sensitive(False)
menu.append(item)
image = gtk.Image()
if alllocked:
item = gtk.ImageMenuItem(_("Unlock all versions"))
if not hasnoninstalled:
image.set_from_pixbuf(getPixbuf("package-installed"))
else:
image.set_from_pixbuf(getPixbuf("package-available"))
def unlock_all(x):
for pkg in pkgs:
pkgconf.clearFlag("lock", pkg.name)
self._pv.queue_draw()
self._pi.setPackage(pkgs[0])
item.connect("activate", unlock_all)
else:
item = gtk.ImageMenuItem(_("Lock all versions"))
if not hasnoninstalled:
image.set_from_pixbuf(getPixbuf("package-installed-locked"))
else:
image.set_from_pixbuf(getPixbuf("package-available-locked"))
def lock_all(x):
for pkg in pkgs:
pkgconf.setFlag("lock", pkg.name)
self._pv.queue_draw()
self._pi.setPackage(pkgs[0])
item.connect("activate", lock_all)
item.set_image(image)
if inconsistent:
item.set_sensitive(False)
menu.append(item)
item = gtk.MenuItem(_("Priority"))
def priority(x):
GtkSinglePriority(self._window).show(pkgs[0])
self._pi.setPackage(pkgs[0])
item.connect("activate", priority)
if len(pkgs) != 1:
item.set_sensitive(False)
menu.append(item)
menu.show_all()
menu.popup(None, None, None, event.button, event.time)
def checkPackages(self, all=False, uninstalled=False):
cache = self._ctrl.getCache()
if checkPackages(cache, cache.getPackages(), report=True,
all=all, uninstalled=uninstalled):
self.info(_("All checked packages have correct relations."))
def fixAllProblems(self):
self.actOnPackages([pkg for pkg in self._ctrl.getCache().getPackages()
if pkg.installed], FIX)
def undo(self):
if self._undo:
state = self._undo.pop(0)
if not self._undo:
self._undomenuitem.set_property("sensitive", False)
self._redo.insert(0, self._changeset.getPersistentState())
self._redomenuitem.set_property("sensitive", True)
self._changeset.setPersistentState(state)
self.changedMarks()
def redo(self):
if self._redo:
state = self._redo.pop(0)
if not self._redo:
self._redomenuitem.set_property("sensitive", False)
self._undo.insert(0, self._changeset.getPersistentState())
self._undomenuitem.set_property("sensitive", True)
self._changeset.setPersistentState(state)
self.changedMarks()
def saveUndo(self):
self._undo.insert(0, self._changeset.getPersistentState())
del self._redo[:]
del self._undo[20:]
self._undomenuitem.set_property("sensitive", True)
self._redomenuitem.set_property("sensitive", False)
def setTreeStyle(self, mode):
if mode != sysconf.get("package-tree"):
sysconf.set("package-tree", mode)
self.refreshPackages()
def editChannels(self):
if GtkChannels(self._window).show():
self.rebuildCache()
def editMirrors(self):
GtkMirrors(self._window).show()
def editFlags(self):
GtkFlags(self._window).show()
def editPriorities(self):
GtkPriorities(self._window).show()
def setBusy(self, flag):
if flag:
self._window.window.set_cursor(self._watch)
while gtk.events_pending():
gtk.main_iteration()
else:
self._window.window.set_cursor(None)
def changedMarks(self):
if "hide-unmarked" in self._filters:
self.refreshPackages()
else:
self._pv.queue_draw()
self._execmenuitem.set_property("sensitive", bool(self._changeset))
self._clearmenuitem.set_property("sensitive", bool(self._changeset))
def toggleSearch(self):
visible = not self._searchbar.get_property('visible')
self._searchbar.set_property('visible', visible)
self.refreshPackages()
if visible:
self._searchentry.grab_focus()
def refreshPackages(self):
if not self._ctrl:
return
self.setBusy(True)
tree = sysconf.get("package-tree", "groups")
ctrl = self._ctrl
changeset = self._changeset
if self._searchbar.get_property("visible"):
searcher = Searcher()
dosearch = False
if self._searchdesc.get_active():
text = self._searchentry.get_text().strip()
if text:
dosearch = True
searcher.addDescription(text)
searcher.addSummary(text)
else:
try:
tokens = shlex.split(self._searchentry.get_text())
except ValueError:
pass
else:
if tokens:
dosearch = True
for tok in tokens:
searcher.addAuto(tok)
packages = []
if dosearch:
self._ctrl.getCache().search(searcher)
for ratio, obj in searcher.getResults():
if isinstance(obj, Package):
packages.append(obj)
else:
packages.extend(obj.packages)
else:
packages = ctrl.getCache().getPackages()
filters = self._filters
if filters:
if "hide-non-upgrades" in filters:
newpackages = {}
for pkg in packages:
if pkg.installed:
upgpkgs = {}
try:
for prv in pkg.provides:
for upg in prv.upgradedby:
for upgpkg in upg.packages:
if upgpkg.installed:
raise StopIteration
upgpkgs[upgpkg] = True
except StopIteration:
pass
else:
newpackages.update(upgpkgs)
packages = newpackages.keys()
if "hide-uninstalled" in filters:
packages = [x for x in packages if x.installed]
if "hide-unmarked" in filters:
packages = [x for x in packages if x in changeset]
if "hide-installed" in filters:
packages = [x for x in packages if not x.installed]
if "hide-old" in filters:
packages = pkgconf.filterByFlag("new", packages)
if tree == "groups":
groups = {}
done = {}
for pkg in packages:
lastgroup = None
for loader in pkg.loaders:
info = loader.getInfo(pkg)
group = info.getGroup()
donetuple = (group, pkg)
if donetuple not in done:
done[donetuple] = True
if group in groups:
groups[group].append(pkg)
else:
groups[group] = [pkg]
elif tree == "channels":
groups = {}
done = {}
for pkg in packages:
for loader in pkg.loaders:
channel = loader.getChannel()
group = channel.getName() or channel.getAlias()
donetuple = (group, pkg)
if donetuple not in done:
done[donetuple] = True
if group in groups:
groups[group].append(pkg)
else:
groups[group] = [pkg]
elif tree == "channels-groups":
groups = {}
done = {}
for pkg in packages:
for loader in pkg.loaders:
channel = loader.getChannel()
group = channel.getName() or channel.getAlias()
subgroup = loader.getInfo(pkg).getGroup()
donetuple = (group, subgroup, pkg)
if donetuple not in done:
done[donetuple] = True
if group in groups:
if subgroup in groups[group]:
groups[group][subgroup].append(pkg)
else:
groups[group][subgroup] = [pkg]
else:
groups[group] = {subgroup: [pkg]}
else:
groups = packages
self._pv.setPackages(groups, changeset, keepstate=True)
self.setBusy(False)
# vim:ts=4:sw=4:et
|
gpl-2.0
| -5,670,332,782,027,367,000
| 37.135006
| 88
| 0.556534
| false
| 4.217627
| false
| false
| false
|
qbuat/tauperf
|
old/eff_tools/DecisionTool.py
|
1
|
2103
|
from ROOT import TMVA
from array import array
from rootpy.extern import ordereddict
import logging
log = logging.getLogger('DecisionTool')
class DecisionTool:
def __init__(self,tree,name,weight_file,var_file,cutval):
""" A class to handle the decision of the BDT"""
TMVA.Tools.Instance()
self._reader = TMVA.Reader()
self._tree = tree
self._variables = {}
self._cutvalue = -1
self._bdtscore = -9999
self._name = name
self._weight_file = weight_file
self._var_file = var_file
self.SetReader(self._name,self._weight_file,self._var_file)
self.SetCutValue(cutval)
# --------------------------
def SetCutValue(self,val):
self._cutvalue = val
# --------------------------------------------
def SetReader(self,name,weight_file,var_file):
self._variables = self.InitVariables(var_file)
for varName, var in self._variables.iteritems():
self._reader.AddVariable(varName,var[1])
self._reader.BookMVA(name,weight_file)
# ----------------------
def InitVariables(self,var_file):
variables = ordereddict.OrderedDict()
file = open(var_file,'r')
for line in file:
if "#" in line: continue
words = line.strip().split(',')
variables[ words[0] ] = [ words[1],array( 'f',[0.]) ]
return variables
# -------------------------------------------------
def BDTScore(self):
for varName, var in self._variables.iteritems():
var[1][0] = getattr(self._tree,var[0])
log.info('{0}: {1}'.format(varName, var[1][0]))
return self._reader.EvaluateMVA(self._name)
# --------------------------------------------
def Decision(self):
self._bdtscore = self.BDTScore()
if self._bdtscore>=self._cutvalue:
return True
else:
return False
# ----------------------
def GetBDTScore(self):
self._bdtscore = self.BDTScore()
return self._bdtscore
|
gpl-3.0
| -3,456,458,913,760,876,500
| 30.863636
| 67
| 0.514503
| false
| 4.021033
| false
| false
| false
|
bioconda/bioconda-utils
|
bioconda_utils/bot/chat.py
|
1
|
5842
|
"""
Chat with the bot via Gitter
"""
import asyncio
import logging
from typing import Any, Dict, List
import aiohttp
from .. import gitter
from ..gitter import AioGitterAPI
from .commands import command_routes
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
"""
https://webhooks.gitter.im/e/b9e5fad23b9cf034879083a
POST
{ message: 'message', level='error|normal' }
"""
class GitterListener:
"""Listens to messages in a Gitter chat room
Args:
app: Web Server Application
api: Gitter API object
rooms: Map containing rooms and their respective github user/repo
"""
def __init__(self, app: aiohttp.web.Application, token: str, rooms: Dict[str, str],
session: aiohttp.ClientSession, ghappapi) -> None:
self.rooms = rooms
self._ghappapi = ghappapi
self._api = AioGitterAPI(app['client_session'], token)
self._user: gitter.User = None
self._tasks: List[Any] = []
self._session = session
app.on_startup.append(self.start)
app.on_shutdown.append(self.shutdown)
def __str__(self) -> str:
return f"{self.__class__.__name__}"
async def start(self, app: aiohttp.web.Application) -> None:
"""Start listeners"""
self._user = await self._api.get_user()
logger.debug("%s: User Info: %s", self, self._user)
for room in await self._api.list_rooms():
logger.debug("%s: Room Info: %s", self, room)
logger.debug("%s: Groups Info: %s", self, await self._api.list_groups())
self._tasks = [app.loop.create_task(self.listen(room))
for room in self.rooms]
async def shutdown(self, _app: aiohttp.web.Application) -> None:
"""Send cancel signal to listener"""
logger.info("%s: Shutting down listeners", self)
for task in self._tasks:
task.cancel()
for task in self._tasks:
await task
logger.info("%s: Shut down all listeners", self)
async def listen(self, room_name: str) -> None:
"""Main run loop"""
try:
user, repo = self.rooms[room_name].split('/')
logger.error("Listening in %s for repo %s/%s", room_name, user, repo)
message = None
while True:
try:
room = await self._api.get_room(room_name)
logger.info("%s: joining %s", self, room_name)
await self._api.join_room(self._user, room)
logger.info("%s: listening in %s", self, room_name)
async for message in self._api.iter_chat(room):
# getting a new ghapi object for every message because our
# creds time out. Ideally, the api class would take care of that.
ghapi = await self._ghappapi.get_github_api(False, user, repo)
await self.handle_msg(room, message, ghapi)
# on timeouts, we just run log into the room again
except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
pass
# http errors just get logged
except aiohttp.ClientResponseError as exc:
logger.exception("HTTP Error Code %s while listening to room %s",
exc.code, room_name)
# asyncio cancellation needs to be passed up
except asyncio.CancelledError: # pylint: disable=try-except-raise
raise
# the rest, we just log so that we remain online after an error
except Exception: # pylint: disable=broad-except
logger.exception("Unexpected exception caught. Last message: '%s'", message)
await asyncio.sleep(1)
except asyncio.CancelledError:
logger.error("%s: stopped listening in %s", self, room_name)
# we need a new session here as the one we got passed might have been
# closed already when we get cancelled
async with aiohttp.ClientSession() as session:
self._api._session = session
await self._api.leave_room(self._user, room)
logger.error("%s: left room %s", self, room_name)
async def handle_msg(self, room: gitter.Room, message: gitter.Message, ghapi) -> None:
"""Parse Gitter message and dispatch via command_routes"""
await self._api.mark_as_read(self._user, room, [message.id])
if self._user.id not in (m.userId for m in message.mentions):
if self._user.username.lower() in (m.screenName.lower() for m in message.mentions):
await self._api.send_message(room, "@%s - are you talking to me?",
message.fromUser.username)
return
command = message.text.strip().lstrip('@'+self._user.username).strip()
if command == message.text.strip():
await self._api.send_message(room, "Hmm? Someone talking about me?",
message.fromUser.username)
return
cmd, *args = command.split()
issue_number = None
try:
if args[-1][0] == '#':
issue_number = int(args[-1][1:])
args.pop()
except (ValueError, IndexError):
pass
response = await command_routes.dispatch(cmd.lower(), ghapi, issue_number,
message.fromUser.username, *args)
if response:
await self._api.send_message(room, "@%s: %s", message.fromUser.username, response)
else:
await self._api.send_message(room, "@%s: command failed", message.fromUser.username)
|
mit
| 7,395,101,836,971,723,000
| 40.432624
| 96
| 0.566587
| false
| 4.181818
| false
| false
| false
|
reshanie/roblox.py
|
roblox/asset.py
|
1
|
12222
|
"""
Copyright (c) 2017 James Patrick Dill, reshanie
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 without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import datetime
import logging
from collections import namedtuple
from json import JSONDecodeError
import faste
from . import utils, enums, errors
log = logging.getLogger("roblox")
class Asset(object):
"""Roblox Asset object.
Use :meth:`RobloxSession.get_asset` to get a specific asset.
Attributes
----------
name : str
Asset name
description : str
Asset description
id : int
Asset ID
product_id : Optional[int]
Product ID
asset_type : :class:`roblox.AssetType`
Asset type
created : :class:`datetime.datetime`
When the asset was first created
updated : :class:`datetime.datetime`
When the asset was last updated
price : Optional[int]
Price of the asset in ROBUX
sales : Optional[int]
Total sales of the asset
is_new : bool
Whether Roblox considers the asset 'new'
for_sale : bool
Whether asset can be taken/bought
public_domain : bool
If the asset is public domain / publicly viewable
limited : bool
If the asset is limited
limited_unique : bool
If the asset is limited and unique
remaining : Optional[int]
How many are remaining, if the asset is limited
membership_level: :class:`roblox.Membership`
Minimum Builders Club needed to take the asset
"""
def __init__(self, client, asset_id=0):
"""param client: client
:type client: roblox.RobloxSession
"""
self.client = client
self.id = asset_id
self._update_info()
def _update_info(self):
try:
product_info = self.client.http.product_info(self.id)
except JSONDecodeError:
raise errors.BadRequest("Invalid asset, possibly deleted")
self.product_id = product_info.get("ProductId")
self.name = product_info.get("Name")
self.description = product_info.get("Description")
self.asset_type = enums.AssetType(product_info.get("AssetTypeId"))
self.icon_image_asset_id = product_info.get("IconImageAssetId")
self.created = utils.get_datetime(product_info.get("Created"))
self.updated = utils.get_datetime(product_info.get("Updated"))
self.price = product_info.get("PriceInRobux")
self.sales = product_info.get("Sales")
self.is_new = product_info.get("IsNew")
self.for_sale = product_info.get("IsForSale")
self.public_domain = product_info.get("IsPublicDomain")
self.unique = product_info.get("IsLimitedUnique")
self.limited = product_info.get("IsLimited") or self.unique
self.remaining = product_info.get("Remaining")
self.membership_level = enums.Membership(product_info.get("MinimumMembershipLevel"))
self.creator_id = product_info["Creator"]["CreatorTargetId"]
self.creator_type = product_info["Creator"]["CreatorType"]
def __hash__(self):
return self.id
def __repr__(self):
return "<roblox.Asset {0.asset_type.name} name={0.name!r} id={0.id!r}>".format(self)
def __str__(self):
return self.name
def __eq__(self, other):
"""
Returns True if two asset objects are the same asset.
"""
if type(other) != Asset:
return False
return self.id == other.id
@property
@faste.decor.rr_cache()
def creator(self):
"""Asset creator
:returns: :class:`User` or :class:`Group`"""
if self.creator_type == "User":
return self.client.get_user(user_id=self.creator_id)
else:
return self.client.get_group(self.creator_id)
def buy(self):
"""
Takes/buys asset.
:returns: `True` if successful
"""
return self.client.http.buy_product(self.product_id,
self.price,
self.creator_id)
def remove_from_inventory(self):
"""
Deletes asset from inventory of client user.
:returns: `True` if successful
"""
return self.client.http.delete_from_inventory(self.id)
def post_comment(self, content):
"""
Posts comment on asset
:param str content: Comment text
:return: :class:`Comment`
"""
if not content:
raise errors.BadRequest("Comment must have text.")
comment = self.client.http.post_comment(self.id, content)
return Comment(self, content=comment["Text"], created=comment["PostedDate"], author=self.client.me)
def owned_by(self, user):
"""
Checks if asset is owned by user.
:param user: User
:type user: :class:`User`
:returns: `True` if user owns asset
"""
return self.client.http.user_owns_asset(user.id, self.id)
@property
@faste.decor.rr_cache()
def icon(self):
"""Asset for icon
:returns: Optional[:class:`Asset`]"""
if self.icon_image_asset_id == 0:
return None
return self.client.get_asset(self.icon_image_asset_id)
@property
def favorites(self):
"""Favorite count of asset
:returns: int"""
return self.client.http.asset_favorites(self.id)
def is_favorited(self):
"""Whether asset is favorited by client
:returns: bool"""
return self.client.http.is_favorited(self.id)
def favorite(self):
"""Favorites asset if it isn't favorited already.
:returns: return value of :meth:`is_favorited` (bool)"""
if self.is_favorited():
return True
return self.client.http.toggle_favorite(self.id)
def unfavorite(self):
"""Unfavorites asset if it's favorited.
:returns: return value of :meth:`is_favorited` (bool)"""
if not self.is_favorited():
return False
return not self.client.http.toggle_favorite(self.id)
def recent_average_price(self):
"""Gets RAP of asset, if it is a collectible.
:returns: Optional[`int`]"""
return self.client.http.get_sales_data(self.id).get("AveragePrice")
def RAP(self):
"""Alias for :meth:recent_average_pice"""
return self.recent_average_price()
def sales_chart(self):
"""Gets :class:`SalesChart` for asset, if it's a collectible."""
return SalesChart(self.client, self)
class Game(Asset):
pass
sales_point = namedtuple("sales_day", "date price volume")
class SalesChart(object):
"""Asset sales chart, representing user sales of a collectible.
You can also iterate over this object, and index it. ``SalesChart[0]`` will return the first sales point.
You can also use ::
>>> list(chart)
>>> reversed(chart)
>>> dict(chart)
>>> len(chart)
>>> datetime.date in chart
The dict version and list versions' values are namedtuples representing sales points, with ``sales_point.date``
, ``sales_point.price`` , and ``sales_point.volume``
The dict's keys are :class:`datetime.date`
Attributes
----------
asset : :class:`Asset`
Asset the sales chart belongs to
chart_dict : dict
dict version of the sales chart
"""
def __init__(self, client, asset):
self.client = client
self.asset = asset
self.chart_dict = self._chart_dict()
def _chart_dict(self):
sales_data = self.client.http.get_sales_data(self.asset.id)
if not sales_data:
raise ValueError("{!r} isn't a collectible and has no sales data".format(self.asset))
sales_chart = sales_data.get("HundredEightyDaySalesChart").split("|")
volume_chart = sales_data.get("HundredEightyDayVolumeChart").split("|")
sales_chart_dict = {}
for sale in sales_chart:
ts = sale.split(",")
if not ts[0]:
break
k = int(ts[0][:-3])
sales_chart_dict[k] = int(ts[1])
volume_chart_dict = {}
for vol in volume_chart:
tv = vol.split(",")
if not tv[0]:
break
k = int(tv[0][:-3])
volume_chart_dict[k] = int(tv[1])
rtd = {}
for timestamp in sales_chart_dict:
nts = datetime.date.fromtimestamp(timestamp)
rtd[nts] = sales_point(
date=nts,
price=sales_chart_dict.get(timestamp),
volume=volume_chart_dict.get(timestamp) or 0,
)
return rtd
def __dict__(self):
return self.chart_dict
def __iter__(self):
return list(self.chart_dict.values())
def __getitem__(self, index):
return list(self.chart_dict.values())[index]
def __len__(self):
return len(self.chart_dict)
def __reversed__(self):
return reversed(list(self.chart_dict.values()))
def __contains__(self, item):
if isinstance(item, datetime.date):
return item in self.chart_dict.keys()
elif isinstance(item, sales_point):
return item in self.chart_dict.values()
return False
def __repr__(self):
return "<roblox.SalesChart asset={0.asset.name!r}>".format(self)
class Comment(object):
"""Asset comment.
Attributes
----------
asset : :class:`Asset`
Asset the comment belongs to
content : str
Comment content
created : :class:`datetime.datetime`
When the comment was posted"""
__slots__ = ["asset", "content", "created", "_user", "_user_cache"]
def __init__(self, asset, content=None, created=None, author=None):
"""
:type asset: :class:`Asset`
"""
self.asset = asset
self.content = content
self.created = utils.get_datetime(created) if created else None
self._user = author
self._user_cache = None
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return self.asset == other.asset and self.created == other.created and self.author == other.author
def __repr__(self):
return "<roblox.Comment asset={0.asset.name!r} author={0.author!r} created={0.created!r}>".format(self)
def __str__(self):
return self.content
@property
@faste.decor.rr_cache()
def author(self):
"""User who made the post.
:returns: :class:`User`"""
if type(self._user) == int:
return self.asset.client.get_user(user_id=self._user)
elif type(self._user) == str:
return self.asset.client.get_user(username=self._user)
return self._user
|
mit
| -1,756,698,657,007,532,500
| 28.708543
| 115
| 0.58722
| false
| 4.090361
| false
| false
| false
|
jcsp/manila
|
manila/tests/scheduler/fakes.py
|
1
|
12546
|
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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.
"""
Fakes For Scheduler tests.
"""
from oslo_utils import timeutils
import six
from manila.scheduler import filter_scheduler
from manila.scheduler import host_manager
SHARE_SERVICES_NO_POOLS = [
dict(id=1, host='host1', topic='share', disabled=False,
availability_zone='zone1', updated_at=timeutils.utcnow()),
dict(id=2, host='host2@back1', topic='share', disabled=False,
availability_zone='zone1', updated_at=timeutils.utcnow()),
dict(id=3, host='host2@back2', topic='share', disabled=False,
availability_zone='zone2', updated_at=timeutils.utcnow()),
]
SERVICE_STATES_NO_POOLS = {
'host1': dict(share_backend_name='AAA',
total_capacity_gb=512, free_capacity_gb=200,
timestamp=None, reserved_percentage=0,
provisioned_capacity_gb=312,
max_over_subscription_ratio=1.0,
thin_provisioning=False,
driver_handles_share_servers=False),
'host2@back1': dict(share_backend_name='BBB',
total_capacity_gb=256, free_capacity_gb=100,
timestamp=None, reserved_percentage=0,
provisioned_capacity_gb=400,
max_over_subscription_ratio=2.0,
thin_provisioning=True,
driver_handles_share_servers=False),
'host2@back2': dict(share_backend_name='CCC',
total_capacity_gb=10000, free_capacity_gb=700,
timestamp=None, reserved_percentage=0,
provisioned_capacity_gb=50000,
max_over_subscription_ratio=20.0,
thin_provisioning=True,
driver_handles_share_servers=False),
}
SHARE_SERVICES_WITH_POOLS = [
dict(id=1, host='host1@AAA', topic='share', disabled=False,
availability_zone='zone1', updated_at=timeutils.utcnow()),
dict(id=2, host='host2@BBB', topic='share', disabled=False,
availability_zone='zone1', updated_at=timeutils.utcnow()),
dict(id=3, host='host3@CCC', topic='share', disabled=False,
availability_zone='zone2', updated_at=timeutils.utcnow()),
dict(id=4, host='host4@DDD', topic='share', disabled=False,
availability_zone='zone3', updated_at=timeutils.utcnow()),
# service on host5 is disabled
dict(id=5, host='host5@EEE', topic='share', disabled=True,
availability_zone='zone4', updated_at=timeutils.utcnow()),
dict(id=5, host='host6@FFF', topic='share', disabled=True,
availability_zone='zone5', updated_at=timeutils.utcnow()),
]
SHARE_SERVICE_STATES_WITH_POOLS = {
'host1@AAA': dict(share_backend_name='AAA',
timestamp=None, reserved_percentage=0,
driver_handles_share_servers=False,
snapshot_support=True,
pools=[dict(pool_name='pool1',
total_capacity_gb=51,
free_capacity_gb=41,
reserved_percentage=0,
provisioned_capacity_gb=10,
max_over_subscription_ratio=1.0,
thin_provisioning=False)]),
'host2@BBB': dict(share_backend_name='BBB',
timestamp=None, reserved_percentage=0,
driver_handles_share_servers=False,
snapshot_support=True,
pools=[dict(pool_name='pool2',
total_capacity_gb=52,
free_capacity_gb=42,
reserved_percentage=0,
provisioned_capacity_gb=60,
max_over_subscription_ratio=2.0,
thin_provisioning=True)]),
'host3@CCC': dict(share_backend_name='CCC',
timestamp=None, reserved_percentage=0,
driver_handles_share_servers=False,
snapshot_support=True,
pools=[dict(pool_name='pool3',
total_capacity_gb=53,
free_capacity_gb=43,
reserved_percentage=0,
provisioned_capacity_gb=100,
max_over_subscription_ratio=20.0,
thin_provisioning=True,
consistency_group_support='pool')]),
'host4@DDD': dict(share_backend_name='DDD',
timestamp=None, reserved_percentage=0,
driver_handles_share_servers=False,
snapshot_support=True,
pools=[dict(pool_name='pool4a',
total_capacity_gb=541,
free_capacity_gb=441,
reserved_percentage=0,
provisioned_capacity_gb=800,
max_over_subscription_ratio=2.0,
thin_provisioning=True,
consistency_group_support='host'),
dict(pool_name='pool4b',
total_capacity_gb=542,
free_capacity_gb=442,
reserved_percentage=0,
provisioned_capacity_gb=2000,
max_over_subscription_ratio=10.0,
thin_provisioning=True,
consistency_group_support='host')]),
'host5@EEE': dict(share_backend_name='EEE',
timestamp=None, reserved_percentage=0,
driver_handles_share_servers=False,
snapshot_support=True,
pools=[dict(pool_name='pool5a',
total_capacity_gb=551,
free_capacity_gb=451,
reserved_percentage=0,
provisioned_capacity_gb=100,
max_over_subscription_ratio=1.0,
thin_provisioning=False),
dict(pool_name='pool5b',
total_capacity_gb=552,
free_capacity_gb=452,
reserved_percentage=0,
provisioned_capacity_gb=100,
max_over_subscription_ratio=1.0,
thin_provisioning=False)]),
'host6@FFF': dict(share_backend_name='FFF',
timestamp=None, reserved_percentage=0,
driver_handles_share_servers=False,
pools=[dict(pool_name='pool6a',
total_capacity_gb='unknown',
free_capacity_gb='unknown',
reserved_percentage=0,
provisioned_capacity_gb=100,
max_over_subscription_ratio=1.0,
thin_provisioning=False),
dict(pool_name='pool6b',
total_capacity_gb='unknown',
free_capacity_gb='unknown',
reserved_percentage=0,
provisioned_capacity_gb=100,
max_over_subscription_ratio=1.0,
thin_provisioning=False)]),
}
class FakeFilterScheduler(filter_scheduler.FilterScheduler):
def __init__(self, *args, **kwargs):
super(FakeFilterScheduler, self).__init__(*args, **kwargs)
self.host_manager = host_manager.HostManager()
class FakeHostManager(host_manager.HostManager):
def __init__(self):
super(FakeHostManager, self).__init__()
self.service_states = {
'host1': {'total_capacity_gb': 1024,
'free_capacity_gb': 1024,
'allocated_capacity_gb': 0,
'thin_provisioning': False,
'reserved_percentage': 10,
'timestamp': None},
'host2': {'total_capacity_gb': 2048,
'free_capacity_gb': 300,
'allocated_capacity_gb': 1748,
'provisioned_capacity_gb': 1748,
'max_over_subscription_ratio': 2.0,
'thin_provisioning': True,
'reserved_percentage': 10,
'timestamp': None},
'host3': {'total_capacity_gb': 512,
'free_capacity_gb': 256,
'allocated_capacity_gb': 256,
'provisioned_capacity_gb': 256,
'max_over_subscription_ratio': 2.0,
'thin_provisioning': False,
'consistency_group_support': 'host',
'reserved_percentage': 0,
'timestamp': None},
'host4': {'total_capacity_gb': 2048,
'free_capacity_gb': 200,
'allocated_capacity_gb': 1848,
'provisioned_capacity_gb': 1848,
'max_over_subscription_ratio': 1.0,
'thin_provisioning': True,
'reserved_percentage': 5,
'timestamp': None},
'host5': {'total_capacity_gb': 2048,
'free_capacity_gb': 500,
'allocated_capacity_gb': 1548,
'provisioned_capacity_gb': 1548,
'max_over_subscription_ratio': 1.5,
'thin_provisioning': True,
'reserved_percentage': 5,
'timestamp': None,
'consistency_group_support': 'pool'},
'host6': {'total_capacity_gb': 'unknown',
'free_capacity_gb': 'unknown',
'allocated_capacity_gb': 1548,
'thin_provisioning': False,
'reserved_percentage': 5,
'timestamp': None},
}
class FakeHostState(host_manager.HostState):
def __init__(self, host, attribute_dict):
super(FakeHostState, self).__init__(host)
for (key, val) in six.iteritems(attribute_dict):
setattr(self, key, val)
def mock_host_manager_db_calls(mock_obj, disabled=None):
services = [
dict(id=1, host='host1', topic='share', disabled=False,
availability_zone='zone1', updated_at=timeutils.utcnow()),
dict(id=2, host='host2', topic='share', disabled=False,
availability_zone='zone1', updated_at=timeutils.utcnow()),
dict(id=3, host='host3', topic='share', disabled=False,
availability_zone='zone2', updated_at=timeutils.utcnow()),
dict(id=4, host='host4', topic='share', disabled=False,
availability_zone='zone3', updated_at=timeutils.utcnow()),
dict(id=5, host='host5', topic='share', disabled=False,
availability_zone='zone3', updated_at=timeutils.utcnow()),
dict(id=6, host='host6', topic='share', disabled=False,
availability_zone='zone4', updated_at=timeutils.utcnow()),
]
if disabled is None:
mock_obj.return_value = services
else:
mock_obj.return_value = [service for service in services
if service['disabled'] == disabled]
|
apache-2.0
| 4,470,534,704,318,130,700
| 48.588933
| 78
| 0.492428
| false
| 4.650111
| false
| false
| false
|
corredD/upy
|
transformation.py
|
1
|
68489
|
# -*- coding: utf-8 -*-
# transformations.py
# Copyright (c) 2006-2013, Christoph Gohlke
# Copyright (c) 2006-2013, The Regents of the University of California
# Produced at the Laboratory for Fluorescence Dynamics
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions 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 the copyright holders nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Homogeneous Transformation Matrices and Quaternions.
A library for calculating 4x4 matrices for translating, rotating, reflecting,
scaling, shearing, projecting, orthogonalizing, and superimposing arrays of
3D homogeneous coordinates as well as for converting between rotation matrices,
Euler angles, and quaternions. Also includes an Arcball control object and
functions to decompose transformation matrices.
:Author:
`Christoph Gohlke <http://www.lfd.uci.edu/~gohlke/>`_
:Organization:
Laboratory for Fluorescence Dynamics, University of California, Irvine
:Version: 2013.06.29
Requirements
------------
* `CPython 2.7 or 3.3 <http://www.python.org>`_
* `Numpy 1.7 <http://www.numpy.org>`_
* `Transformations.c 2013.01.18 <http://www.lfd.uci.edu/~gohlke/>`_
(recommended for speedup of some functions)
Notes
-----
The API is not stable yet and is expected to change between revisions.
This Python code is not optimized for speed. Refer to the transformations.c
module for a faster implementation of some functions.
Documentation in HTML format can be generated with epydoc.
Matrices (M) can be inverted using numpy.linalg.inv(M), be concatenated using
numpy.dot(M0, M1), or transform homogeneous coordinate arrays (v) using
numpy.dot(M, v) for shape (4, \*) column vectors, respectively
numpy.dot(v, M.T) for shape (\*, 4) row vectors ("array of points").
This module follows the "column vectors on the right" and "row major storage"
(C contiguous) conventions. The translation components are in the right column
of the transformation matrix, i.e. M[:3, 3].
The transpose of the transformation matrices may have to be used to interface
with other graphics systems, e.g. with OpenGL's glMultMatrixd(). See also [16].
Calculations are carried out with numpy.float64 precision.
Vector, point, quaternion, and matrix function arguments are expected to be
"array like", i.e. tuple, list, or numpy arrays.
Return types are numpy arrays unless specified otherwise.
Angles are in radians unless specified otherwise.
Quaternions w+ix+jy+kz are represented as [w, x, y, z].
A triple of Euler angles can be applied/interpreted in 24 ways, which can
be specified using a 4 character string or encoded 4-tuple:
*Axes 4-string*: e.g. 'sxyz' or 'ryxy'
- first character : rotations are applied to 's'tatic or 'r'otating frame
- remaining characters : successive rotation axis 'x', 'y', or 'z'
*Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1)
- inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix.
- parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed
by 'z', or 'z' is followed by 'x'. Otherwise odd (1).
- repetition : first and last axis are same (1) or different (0).
- frame : rotations are applied to static (0) or rotating (1) frame.
References
----------
(1) Matrices and transformations. Ronald Goldman.
In "Graphics Gems I", pp 472-475. Morgan Kaufmann, 1990.
(2) More matrices and transformations: shear and pseudo-perspective.
Ronald Goldman. In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(3) Decomposing a matrix into simple transformations. Spencer Thomas.
In "Graphics Gems II", pp 320-323. Morgan Kaufmann, 1991.
(4) Recovering the data from the transformation matrix. Ronald Goldman.
In "Graphics Gems II", pp 324-331. Morgan Kaufmann, 1991.
(5) Euler angle conversion. Ken Shoemake.
In "Graphics Gems IV", pp 222-229. Morgan Kaufmann, 1994.
(6) Arcball rotation control. Ken Shoemake.
In "Graphics Gems IV", pp 175-192. Morgan Kaufmann, 1994.
(7) Representing attitude: Euler angles, unit quaternions, and rotation
vectors. James Diebel. 2006.
(8) A discussion of the solution for the best rotation to relate two sets
of vectors. W Kabsch. Acta Cryst. 1978. A34, 827-828.
(9) Closed-form solution of absolute orientation using unit quaternions.
BKP Horn. J Opt Soc Am A. 1987. 4(4):629-642.
(10) Quaternions. Ken Shoemake.
http://www.sfu.ca/~jwa3/cmpt461/files/quatut.pdf
(11) From quaternion to matrix and back. JMP van Waveren. 2005.
http://www.intel.com/cd/ids/developer/asmo-na/eng/293748.htm
(12) Uniform random rotations. Ken Shoemake.
In "Graphics Gems III", pp 124-132. Morgan Kaufmann, 1992.
(13) Quaternion in molecular modeling. CFF Karney.
J Mol Graph Mod, 25(5):595-604
(14) New method for extracting the quaternion from a rotation matrix.
Itzhack Y Bar-Itzhack, J Guid Contr Dynam. 2000. 23(6): 1085-1087.
(15) Multiple View Geometry in Computer Vision. Hartley and Zissermann.
Cambridge University Press; 2nd Ed. 2004. Chapter 4, Algorithm 4.7, p 130.
(16) Column Vectors vs. Row Vectors.
http://steve.hollasch.net/cgindex/math/matrix/column-vec.html
Examples
--------
>>> alpha, beta, gamma = 0.123, -1.234, 2.345
>>> origin, xaxis, yaxis, zaxis = [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]
>>> I = identity_matrix()
>>> Rx = rotation_matrix(alpha, xaxis)
>>> Ry = rotation_matrix(beta, yaxis)
>>> Rz = rotation_matrix(gamma, zaxis)
>>> R = concatenate_matrices(Rx, Ry, Rz)
>>> euler = euler_from_matrix(R, 'rxyz')
>>> numpy.allclose([alpha, beta, gamma], euler)
True
>>> Re = euler_matrix(alpha, beta, gamma, 'rxyz')
>>> is_same_transform(R, Re)
True
>>> al, be, ga = euler_from_matrix(Re, 'rxyz')
>>> is_same_transform(Re, euler_matrix(al, be, ga, 'rxyz'))
True
>>> qx = quaternion_about_axis(alpha, xaxis)
>>> qy = quaternion_about_axis(beta, yaxis)
>>> qz = quaternion_about_axis(gamma, zaxis)
>>> q = quaternion_multiply(qx, qy)
>>> q = quaternion_multiply(q, qz)
>>> Rq = quaternion_matrix(q)
>>> is_same_transform(R, Rq)
True
>>> S = scale_matrix(1.23, origin)
>>> T = translation_matrix([1, 2, 3])
>>> Z = shear_matrix(beta, xaxis, origin, zaxis)
>>> R = random_rotation_matrix(numpy.random.rand(3))
>>> M = concatenate_matrices(T, R, Z, S)
>>> scale, shear, angles, trans, persp = decompose_matrix(M)
>>> numpy.allclose(scale, 1.23)
True
>>> numpy.allclose(trans, [1, 2, 3])
True
>>> numpy.allclose(shear, [0, math.tan(beta), 0])
True
>>> is_same_transform(R, euler_matrix(axes='sxyz', *angles))
True
>>> M1 = compose_matrix(scale, shear, angles, trans, persp)
>>> is_same_transform(M, M1)
True
>>> v0, v1 = random_vector(3), random_vector(3)
>>> M = rotation_matrix(angle_between_vectors(v0, v1), vector_product(v0, v1))
>>> v2 = numpy.dot(v0, M[:3,:3].T)
>>> numpy.allclose(unit_vector(v1), unit_vector(v2))
True
"""
from __future__ import division, print_function
import math
import numpy
__version__ = '2013.06.29'
__docformat__ = 'restructuredtext en'
__all__ = []
def identity_matrix():
"""Return 4x4 identity/unit matrix.
>>> I = identity_matrix()
>>> numpy.allclose(I, numpy.dot(I, I))
True
>>> numpy.sum(I), numpy.trace(I)
(4.0, 4.0)
>>> numpy.allclose(I, numpy.identity(4))
True
"""
return numpy.identity(4)
def translation_matrix(direction):
"""Return matrix to translate by direction vector.
>>> v = numpy.random.random(3) - 0.5
>>> numpy.allclose(v, translation_matrix(v)[:3, 3])
True
"""
M = numpy.identity(4)
M[:3, 3] = direction[:3]
return M
def translation_from_matrix(matrix):
"""Return translation vector from translation matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = translation_from_matrix(translation_matrix(v0))
>>> numpy.allclose(v0, v1)
True
"""
return numpy.array(matrix, copy=False)[:3, 3].copy()
def reflection_matrix(point, normal):
"""Return matrix to mirror at plane defined by point and normal vector.
>>> v0 = numpy.random.random(4) - 0.5
>>> v0[3] = 1.
>>> v1 = numpy.random.random(3) - 0.5
>>> R = reflection_matrix(v0, v1)
>>> numpy.allclose(2, numpy.trace(R))
True
>>> numpy.allclose(v0, numpy.dot(R, v0))
True
>>> v2 = v0.copy()
>>> v2[:3] += v1
>>> v3 = v0.copy()
>>> v2[:3] -= v1
>>> numpy.allclose(v2, numpy.dot(R, v3))
True
"""
normal = unit_vector(normal[:3])
M = numpy.identity(4)
M[:3, :3] -= 2.0 * numpy.outer(normal, normal)
M[:3, 3] = (2.0 * numpy.dot(point[:3], normal)) * normal
return M
def reflection_from_matrix(matrix):
"""Return mirror plane point and normal vector from reflection matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = numpy.random.random(3) - 0.5
>>> M0 = reflection_matrix(v0, v1)
>>> point, normal = reflection_from_matrix(M0)
>>> M1 = reflection_matrix(point, normal)
>>> is_same_transform(M0, M1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
# normal: unit eigenvector corresponding to eigenvalue -1
w, V = numpy.linalg.eig(M[:3, :3])
i = numpy.where(abs(numpy.real(w) + 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue -1")
normal = numpy.real(V[:, i[0]]).squeeze()
# point: any unit eigenvector corresponding to eigenvalue 1
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
return point, normal
def rotation_matrix(angle, direction, point=None):
"""Return matrix to rotate about axis defined by point and direction.
>>> R = rotation_matrix(math.pi/2, [0, 0, 1], [1, 0, 0])
>>> numpy.allclose(numpy.dot(R, [0, 0, 0, 1]), [1, -1, 0, 1])
True
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(angle-2*math.pi, direc, point)
>>> is_same_transform(R0, R1)
True
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(-angle, -direc, point)
>>> is_same_transform(R0, R1)
True
>>> I = numpy.identity(4, numpy.float64)
>>> numpy.allclose(I, rotation_matrix(math.pi*2, direc))
True
>>> numpy.allclose(2, numpy.trace(rotation_matrix(math.pi/2,
... direc, point)))
True
"""
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
# rotation matrix around unit vector
R = numpy.diag([cosa, cosa, cosa])
R += numpy.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += numpy.array([[ 0.0, -direction[2], direction[1]],
[ direction[2], 0.0, -direction[0]],
[-direction[1], direction[0], 0.0]])
M = numpy.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = numpy.array(point[:3], dtype=numpy.float64, copy=False)
M[:3, 3] = point - numpy.dot(R, point)
return M
def rotation_from_matrix(matrix):
"""Return rotation angle and axis from rotation matrix.
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> angle, direc, point = rotation_from_matrix(R0)
>>> R1 = rotation_matrix(angle, direc, point)
>>> is_same_transform(R0, R1)
True
"""
R = numpy.array(matrix, dtype=numpy.float64, copy=False)
R33 = R[:3, :3]
# direction: unit eigenvector of R33 corresponding to eigenvalue of 1
w, W = numpy.linalg.eig(R33.T)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
direction = numpy.real(W[:, i[-1]]).squeeze()
# point: unit eigenvector of R33 corresponding to eigenvalue of 1
w, Q = numpy.linalg.eig(R)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no unit eigenvector corresponding to eigenvalue 1")
point = numpy.real(Q[:, i[-1]]).squeeze()
point /= point[3]
# rotation angle depending on direction
cosa = (numpy.trace(R33) - 1.0) / 2.0
if abs(direction[2]) > 1e-8:
sina = (R[1, 0] + (cosa-1.0)*direction[0]*direction[1]) / direction[2]
elif abs(direction[1]) > 1e-8:
sina = (R[0, 2] + (cosa-1.0)*direction[0]*direction[2]) / direction[1]
else:
sina = (R[2, 1] + (cosa-1.0)*direction[1]*direction[2]) / direction[0]
angle = math.atan2(sina, cosa)
return angle, direction, point
def scale_matrix(factor, origin=None, direction=None):
"""Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
>>> v = (numpy.random.rand(4, 5) - 0.5) * 20
>>> v[3] = 1
>>> S = scale_matrix(-1.234)
>>> numpy.allclose(numpy.dot(S, v)[:3], -1.234*v[:3])
True
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S = scale_matrix(factor, origin)
>>> S = scale_matrix(factor, origin, direct)
"""
if direction is None:
# uniform scaling
M = numpy.diag([factor, factor, factor, 1.0])
if origin is not None:
M[:3, 3] = origin[:3]
M[:3, 3] *= 1.0 - factor
else:
# nonuniform scaling
direction = unit_vector(direction[:3])
factor = 1.0 - factor
M = numpy.identity(4)
M[:3, :3] -= factor * numpy.outer(direction, direction)
if origin is not None:
M[:3, 3] = (factor * numpy.dot(origin[:3], direction)) * direction
return M
def scale_from_matrix(matrix):
"""Return scaling factor, origin and direction from scaling matrix.
>>> factor = random.random() * 10 - 5
>>> origin = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> S0 = scale_matrix(factor, origin)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
>>> S0 = scale_matrix(factor, origin, direct)
>>> factor, origin, direction = scale_from_matrix(S0)
>>> S1 = scale_matrix(factor, origin, direction)
>>> is_same_transform(S0, S1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
factor = numpy.trace(M33) - 2.0
try:
# direction: unit eigenvector corresponding to eigenvalue factor
w, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(w) - factor) < 1e-8)[0][0]
direction = numpy.real(V[:, i]).squeeze()
direction /= vector_norm(direction)
except IndexError:
# uniform scaling
factor = (factor + 2.0) / 3.0
direction = None
# origin: any eigenvector corresponding to eigenvalue 1
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 1")
origin = numpy.real(V[:, i[-1]]).squeeze()
origin /= origin[3]
return factor, origin, direction
def projection_matrix(point, normal, direction=None,
perspective=None, pseudo=False):
"""Return matrix to project onto plane defined by point and normal.
Using either perspective point, projection direction, or none of both.
If pseudo is True, perspective projections will preserve relative depth
such that Perspective = dot(Orthogonal, PseudoPerspective).
>>> P = projection_matrix([0, 0, 0], [1, 0, 0])
>>> numpy.allclose(P[1:, 1:], numpy.identity(4)[1:, 1:])
True
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(3) - 0.5
>>> P0 = projection_matrix(point, normal)
>>> P1 = projection_matrix(point, normal, direction=direct)
>>> P2 = projection_matrix(point, normal, perspective=persp)
>>> P3 = projection_matrix(point, normal, perspective=persp, pseudo=True)
>>> is_same_transform(P2, numpy.dot(P0, P3))
True
>>> P = projection_matrix([3, 0, 0], [1, 1, 0], [1, 0, 0])
>>> v0 = (numpy.random.rand(4, 5) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = numpy.dot(P, v0)
>>> numpy.allclose(v1[1], v0[1])
True
>>> numpy.allclose(v1[0], 3-v1[1])
True
"""
M = numpy.identity(4)
point = numpy.array(point[:3], dtype=numpy.float64, copy=False)
normal = unit_vector(normal[:3])
if perspective is not None:
# perspective projection
perspective = numpy.array(perspective[:3], dtype=numpy.float64,
copy=False)
M[0, 0] = M[1, 1] = M[2, 2] = numpy.dot(perspective-point, normal)
M[:3, :3] -= numpy.outer(perspective, normal)
if pseudo:
# preserve relative depth
M[:3, :3] -= numpy.outer(normal, normal)
M[:3, 3] = numpy.dot(point, normal) * (perspective+normal)
else:
M[:3, 3] = numpy.dot(point, normal) * perspective
M[3, :3] = -normal
M[3, 3] = numpy.dot(perspective, normal)
elif direction is not None:
# parallel projection
direction = numpy.array(direction[:3], dtype=numpy.float64, copy=False)
scale = numpy.dot(direction, normal)
M[:3, :3] -= numpy.outer(direction, normal) / scale
M[:3, 3] = direction * (numpy.dot(point, normal) / scale)
else:
# orthogonal projection
M[:3, :3] -= numpy.outer(normal, normal)
M[:3, 3] = numpy.dot(point, normal) * normal
return M
def projection_from_matrix(matrix, pseudo=False):
"""Return projection plane and perspective point from projection matrix.
Return values are same as arguments for projection_matrix function:
point, normal, direction, perspective, and pseudo.
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.random.random(3) - 0.5
>>> direct = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(3) - 0.5
>>> P0 = projection_matrix(point, normal)
>>> result = projection_from_matrix(P0)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, direct)
>>> result = projection_from_matrix(P0)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=False)
>>> result = projection_from_matrix(P0, pseudo=False)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
>>> P0 = projection_matrix(point, normal, perspective=persp, pseudo=True)
>>> result = projection_from_matrix(P0, pseudo=True)
>>> P1 = projection_matrix(*result)
>>> is_same_transform(P0, P1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not pseudo and len(i):
# point: any eigenvector corresponding to eigenvalue 1
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
# direction: unit eigenvector corresponding to eigenvalue 0
w, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(w)) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 0")
direction = numpy.real(V[:, i[0]]).squeeze()
direction /= vector_norm(direction)
# normal: unit eigenvector of M33.T corresponding to eigenvalue 0
w, V = numpy.linalg.eig(M33.T)
i = numpy.where(abs(numpy.real(w)) < 1e-8)[0]
if len(i):
# parallel projection
normal = numpy.real(V[:, i[0]]).squeeze()
normal /= vector_norm(normal)
return point, normal, direction, None, False
else:
# orthogonal projection, where normal equals direction vector
return point, direction, None, None, False
else:
# perspective projection
i = numpy.where(abs(numpy.real(w)) > 1e-8)[0]
if not len(i):
raise ValueError(
"no eigenvector not corresponding to eigenvalue 0")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
normal = - M[3, :3]
perspective = M[:3, 3] / numpy.dot(point[:3], normal)
if pseudo:
perspective -= normal
return point, normal, None, perspective, pseudo
def clip_matrix(left, right, bottom, top, near, far, perspective=False):
"""Return matrix to obtain normalized device coordinates from frustum.
The frustum bounds are axis-aligned along x (left, right),
y (bottom, top) and z (near, far).
Normalized device coordinates are in range [-1, 1] if coordinates are
inside the frustum.
If perspective is True the frustum is a truncated pyramid with the
perspective point at origin and direction along z axis, otherwise an
orthographic canonical view volume (a box).
Homogeneous coordinates transformed by the perspective clip matrix
need to be dehomogenized (divided by w coordinate).
>>> frustum = numpy.random.rand(6)
>>> frustum[1] += frustum[0]
>>> frustum[3] += frustum[2]
>>> frustum[5] += frustum[4]
>>> M = clip_matrix(perspective=False, *frustum)
>>> numpy.dot(M, [frustum[0], frustum[2], frustum[4], 1])
array([-1., -1., -1., 1.])
>>> numpy.dot(M, [frustum[1], frustum[3], frustum[5], 1])
array([ 1., 1., 1., 1.])
>>> M = clip_matrix(perspective=True, *frustum)
>>> v = numpy.dot(M, [frustum[0], frustum[2], frustum[4], 1])
>>> v / v[3]
array([-1., -1., -1., 1.])
>>> v = numpy.dot(M, [frustum[1], frustum[3], frustum[4], 1])
>>> v / v[3]
array([ 1., 1., -1., 1.])
"""
if left >= right or bottom >= top or near >= far:
raise ValueError("invalid frustum")
if perspective:
if near <= _EPS:
raise ValueError("invalid frustum: near <= 0")
t = 2.0 * near
M = [[t/(left-right), 0.0, (right+left)/(right-left), 0.0],
[0.0, t/(bottom-top), (top+bottom)/(top-bottom), 0.0],
[0.0, 0.0, (far+near)/(near-far), t*far/(far-near)],
[0.0, 0.0, -1.0, 0.0]]
else:
M = [[2.0/(right-left), 0.0, 0.0, (right+left)/(left-right)],
[0.0, 2.0/(top-bottom), 0.0, (top+bottom)/(bottom-top)],
[0.0, 0.0, 2.0/(far-near), (far+near)/(near-far)],
[0.0, 0.0, 0.0, 1.0]]
return numpy.array(M)
def shear_matrix(angle, direction, point, normal):
"""Return matrix to shear by angle along direction vector on shear plane.
The shear plane is defined by a point and normal vector. The direction
vector must be orthogonal to the plane's normal vector.
A point P is transformed by the shear matrix into P" such that
the vector P-P" is parallel to the direction vector and its extent is
given by the angle of P-P'-P", where P' is the orthogonal projection
of P onto the shear plane.
>>> angle = (random.random() - 0.5) * 4*math.pi
>>> direct = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.cross(direct, numpy.random.random(3))
>>> S = shear_matrix(angle, direct, point, normal)
>>> numpy.allclose(1, numpy.linalg.det(S))
True
"""
normal = unit_vector(normal[:3])
direction = unit_vector(direction[:3])
if abs(numpy.dot(normal, direction)) > 1e-6:
raise ValueError("direction and normal vectors are not orthogonal")
angle = math.tan(angle)
M = numpy.identity(4)
M[:3, :3] += angle * numpy.outer(direction, normal)
M[:3, 3] = -angle * numpy.dot(point[:3], normal) * direction
return M
def shear_from_matrix(matrix):
"""Return shear angle, direction and plane from shear matrix.
>>> angle = (random.random() - 0.5) * 4*math.pi
>>> direct = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> normal = numpy.cross(direct, numpy.random.random(3))
>>> S0 = shear_matrix(angle, direct, point, normal)
>>> angle, direct, point, normal = shear_from_matrix(S0)
>>> S1 = shear_matrix(angle, direct, point, normal)
>>> is_same_transform(S0, S1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)
M33 = M[:3, :3]
# normal: cross independent eigenvectors corresponding to the eigenvalue 1
w, V = numpy.linalg.eig(M33)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-4)[0]
if len(i) < 2:
raise ValueError("no two linear independent eigenvectors found %s" % w)
V = numpy.real(V[:, i]).squeeze().T
lenorm = -1.0
for i0, i1 in ((0, 1), (0, 2), (1, 2)):
n = numpy.cross(V[i0], V[i1])
w = vector_norm(n)
if w > lenorm:
lenorm = w
normal = n
normal /= lenorm
# direction and angle
direction = numpy.dot(M33 - numpy.identity(3), normal)
angle = vector_norm(direction)
direction /= angle
angle = math.atan(angle)
# point: eigenvector corresponding to eigenvalue 1
w, V = numpy.linalg.eig(M)
i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-8)[0]
if not len(i):
raise ValueError("no eigenvector corresponding to eigenvalue 1")
point = numpy.real(V[:, i[-1]]).squeeze()
point /= point[3]
return angle, direction, point, normal
def decompose_matrix(matrix):
"""Return sequence of transformations from transformation matrix.
matrix : array_like
Non-degenerative homogeneous transformation matrix
Return tuple of:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
Raise ValueError if matrix is of wrong type or degenerative.
>>> T0 = translation_matrix([1, 2, 3])
>>> scale, shear, angles, trans, persp = decompose_matrix(T0)
>>> T1 = translation_matrix(trans)
>>> numpy.allclose(T0, T1)
True
>>> S = scale_matrix(0.123)
>>> scale, shear, angles, trans, persp = decompose_matrix(S)
>>> scale[0]
0.123
>>> R0 = euler_matrix(1, 2, 3)
>>> scale, shear, angles, trans, persp = decompose_matrix(R0)
>>> R1 = euler_matrix(*angles)
>>> numpy.allclose(R0, R1)
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=True).T
if abs(M[3, 3]) < _EPS:
raise ValueError("M[3, 3] is zero")
M /= M[3, 3]
P = M.copy()
P[:, 3] = 0.0, 0.0, 0.0, 1.0
if not numpy.linalg.det(P):
raise ValueError("matrix is singular")
scale = numpy.zeros((3, ))
shear = [0.0, 0.0, 0.0]
angles = [0.0, 0.0, 0.0]
if any(abs(M[:3, 3]) > _EPS):
perspective = numpy.dot(M[:, 3], numpy.linalg.inv(P.T))
M[:, 3] = 0.0, 0.0, 0.0, 1.0
else:
perspective = numpy.array([0.0, 0.0, 0.0, 1.0])
translate = M[3, :3].copy()
M[3, :3] = 0.0
row = M[:3, :3].copy()
scale[0] = vector_norm(row[0])
row[0] /= scale[0]
shear[0] = numpy.dot(row[0], row[1])
row[1] -= row[0] * shear[0]
scale[1] = vector_norm(row[1])
row[1] /= scale[1]
shear[0] /= scale[1]
shear[1] = numpy.dot(row[0], row[2])
row[2] -= row[0] * shear[1]
shear[2] = numpy.dot(row[1], row[2])
row[2] -= row[1] * shear[2]
scale[2] = vector_norm(row[2])
row[2] /= scale[2]
shear[1:] /= scale[2]
if numpy.dot(row[0], numpy.cross(row[1], row[2])) < 0:
numpy.negative(scale, scale)
numpy.negative(row, row)
angles[1] = math.asin(-row[0, 2])
if math.cos(angles[1]):
angles[0] = math.atan2(row[1, 2], row[2, 2])
angles[2] = math.atan2(row[0, 1], row[0, 0])
else:
#angles[0] = math.atan2(row[1, 0], row[1, 1])
angles[0] = math.atan2(-row[2, 1], row[1, 1])
angles[2] = 0.0
return scale, shear, angles, translate, perspective
def compose_matrix(scale=None, shear=None, angles=None, translate=None,
perspective=None):
"""Return transformation matrix from sequence of transformations.
This is the inverse of the decompose_matrix function.
Sequence of transformations:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
angles : list of Euler angles about static x, y, z axes
translate : translation vector along x, y, z axes
perspective : perspective partition of matrix
>>> scale = numpy.random.random(3) - 0.5
>>> shear = numpy.random.random(3) - 0.5
>>> angles = (numpy.random.random(3) - 0.5) * (2*math.pi)
>>> trans = numpy.random.random(3) - 0.5
>>> persp = numpy.random.random(4) - 0.5
>>> M0 = compose_matrix(scale, shear, angles, trans, persp)
>>> result = decompose_matrix(M0)
>>> M1 = compose_matrix(*result)
>>> is_same_transform(M0, M1)
True
"""
M = numpy.identity(4)
if perspective is not None:
P = numpy.identity(4)
P[3, :] = perspective[:4]
M = numpy.dot(M, P)
if translate is not None:
T = numpy.identity(4)
T[:3, 3] = translate[:3]
M = numpy.dot(M, T)
if angles is not None:
R = euler_matrix(angles[0], angles[1], angles[2], 'sxyz')
M = numpy.dot(M, R)
if shear is not None:
Z = numpy.identity(4)
Z[1, 2] = shear[2]
Z[0, 2] = shear[1]
Z[0, 1] = shear[0]
M = numpy.dot(M, Z)
if scale is not None:
S = numpy.identity(4)
S[0, 0] = scale[0]
S[1, 1] = scale[1]
S[2, 2] = scale[2]
M = numpy.dot(M, S)
M /= M[3, 3]
return M
def orthogonalization_matrix(lengths, angles):
"""Return orthogonalization matrix for crystallographic cell coordinates.
Angles are expected in degrees.
The de-orthogonalization matrix is the inverse.
>>> O = orthogonalization_matrix([10, 10, 10], [90, 90, 90])
>>> numpy.allclose(O[:3, :3], numpy.identity(3, float) * 10)
True
>>> O = orthogonalization_matrix([9.8, 12.0, 15.5], [87.2, 80.7, 69.7])
>>> numpy.allclose(numpy.sum(O), 43.063229)
True
"""
a, b, c = lengths
angles = numpy.radians(angles)
sina, sinb, _ = numpy.sin(angles)
cosa, cosb, cosg = numpy.cos(angles)
co = (cosa * cosb - cosg) / (sina * sinb)
return numpy.array([
[ a*sinb*math.sqrt(1.0-co*co), 0.0, 0.0, 0.0],
[-a*sinb*co, b*sina, 0.0, 0.0],
[ a*cosb, b*cosa, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0]])
def affine_matrix_from_points(v0, v1, shear=True, scale=True, usesvd=True):
"""Return affine transform matrix to register two point sets.
v0 and v1 are shape (ndims, \*) arrays of at least ndims non-homogeneous
coordinates, where ndims is the dimensionality of the coordinate space.
If shear is False, a similarity transformation matrix is returned.
If also scale is False, a rigid/Euclidean transformation matrix
is returned.
By default the algorithm by Hartley and Zissermann [15] is used.
If usesvd is True, similarity and Euclidean transformation matrices
are calculated by minimizing the weighted sum of squared deviations
(RMSD) according to the algorithm by Kabsch [8].
Otherwise, and if ndims is 3, the quaternion based algorithm by Horn [9]
is used, which is slower when using this Python implementation.
The returned matrix performs rotation, translation and uniform scaling
(if specified).
>>> v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]]
>>> v1 = [[675, 826, 826, 677], [55, 52, 281, 277]]
>>> affine_matrix_from_points(v0, v1)
array([[ 0.14549, 0.00062, 675.50008],
[ 0.00048, 0.14094, 53.24971],
[ 0. , 0. , 1. ]])
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> S = scale_matrix(random.random())
>>> M = concatenate_matrices(T, R, S)
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0, 1e-8, 300).reshape(3, -1)
>>> M = affine_matrix_from_points(v0[:3], v1[:3])
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
More examples in superimposition_matrix()
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=True)
v1 = numpy.array(v1, dtype=numpy.float64, copy=True)
ndims = v0.shape[0]
if ndims < 2 or v0.shape[1] < ndims or v0.shape != v1.shape:
raise ValueError("input arrays are of wrong shape or type")
# move centroids to origin
t0 = -numpy.mean(v0, axis=1)
M0 = numpy.identity(ndims+1)
M0[:ndims, ndims] = t0
v0 += t0.reshape(ndims, 1)
t1 = -numpy.mean(v1, axis=1)
M1 = numpy.identity(ndims+1)
M1[:ndims, ndims] = t1
v1 += t1.reshape(ndims, 1)
if shear:
# Affine transformation
A = numpy.concatenate((v0, v1), axis=0)
u, s, vh = numpy.linalg.svd(A.T)
vh = vh[:ndims].T
B = vh[:ndims]
C = vh[ndims:2*ndims]
t = numpy.dot(C, numpy.linalg.pinv(B))
t = numpy.concatenate((t, numpy.zeros((ndims, 1))), axis=1)
M = numpy.vstack((t, ((0.0,)*ndims) + (1.0,)))
elif usesvd or ndims != 3:
# Rigid transformation via SVD of covariance matrix
u, s, vh = numpy.linalg.svd(numpy.dot(v1, v0.T))
# rotation matrix from SVD orthonormal bases
R = numpy.dot(u, vh)
if numpy.linalg.det(R) < 0.0:
# R does not constitute right handed system
R -= numpy.outer(u[:, ndims-1], vh[ndims-1, :]*2.0)
s[-1] *= -1.0
# homogeneous transformation matrix
M = numpy.identity(ndims+1)
M[:ndims, :ndims] = R
else:
# Rigid transformation matrix via quaternion
# compute symmetric matrix N
xx, yy, zz = numpy.sum(v0 * v1, axis=1)
xy, yz, zx = numpy.sum(v0 * numpy.roll(v1, -1, axis=0), axis=1)
xz, yx, zy = numpy.sum(v0 * numpy.roll(v1, -2, axis=0), axis=1)
N = [[xx+yy+zz, 0.0, 0.0, 0.0],
[yz-zy, xx-yy-zz, 0.0, 0.0],
[zx-xz, xy+yx, yy-xx-zz, 0.0],
[xy-yx, zx+xz, yz+zy, zz-xx-yy]]
# quaternion: eigenvector corresponding to most positive eigenvalue
w, V = numpy.linalg.eigh(N)
q = V[:, numpy.argmax(w)]
q /= vector_norm(q) # unit quaternion
# homogeneous transformation matrix
M = quaternion_matrix(q)
if scale and not shear:
# Affine transformation; scale is ratio of RMS deviations from centroid
v0 *= v0
v1 *= v1
M[:ndims, :ndims] *= math.sqrt(numpy.sum(v1) / numpy.sum(v0))
# move centroids back
M = numpy.dot(numpy.linalg.inv(M1), numpy.dot(M, M0))
M /= M[ndims, ndims]
return M
def superimposition_matrix(v0, v1, scale=False, usesvd=True):
"""Return matrix to transform given 3D point set into second point set.
v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 points.
The parameters scale and usesvd are explained in the more general
affine_matrix_from_points function.
The returned matrix is a similarity or Euclidean transformation matrix.
This function has a fast C implementation in transformations.c.
>>> v0 = numpy.random.rand(3, 10)
>>> M = superimposition_matrix(v0, v0)
>>> numpy.allclose(M, numpy.identity(4))
True
>>> R = random_rotation_matrix(numpy.random.random(3))
>>> v0 = [[1,0,0], [0,1,0], [0,0,1], [1,1,1]]
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20
>>> v0[3] = 1
>>> v1 = numpy.dot(R, v0)
>>> M = superimposition_matrix(v0, v1)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> S = scale_matrix(random.random())
>>> T = translation_matrix(numpy.random.random(3)-0.5)
>>> M = concatenate_matrices(T, R, S)
>>> v1 = numpy.dot(M, v0)
>>> v0[:3] += numpy.random.normal(0, 1e-9, 300).reshape(3, -1)
>>> M = superimposition_matrix(v0, v1, scale=True)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v0))
True
>>> v = numpy.empty((4, 100, 3))
>>> v[:, :, 0] = v0
>>> M = superimposition_matrix(v0, v1, scale=True, usesvd=False)
>>> numpy.allclose(v1, numpy.dot(M, v[:, :, 0]))
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)[:3]
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)[:3]
return affine_matrix_from_points(v0, v1, shear=False,
scale=scale, usesvd=usesvd)
def euler_matrix(ai, aj, ak, axes='sxyz'):
"""Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> numpy.allclose(numpy.sum(R[0]), -1.34786452)
True
>>> R = euler_matrix(1, 2, 3, (0, 1, 0, 1))
>>> numpy.allclose(numpy.sum(R[0]), -0.383436184)
True
>>> ai, aj, ak = (4*math.pi) * (numpy.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... R = euler_matrix(ai, aj, ak, axes)
>>> for axes in _TUPLE2AXES.keys():
... R = euler_matrix(ai, aj, ak, axes)
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes]
except (AttributeError, KeyError):
_TUPLE2AXES[axes] # validation
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
if frame:
ai, ak = ak, ai
if parity:
ai, aj, ak = -ai, -aj, -ak
si, sj, sk = math.sin(ai), math.sin(aj), math.sin(ak)
ci, cj, ck = math.cos(ai), math.cos(aj), math.cos(ak)
cc, cs = ci*ck, ci*sk
sc, ss = si*ck, si*sk
M = numpy.identity(4)
if repetition:
M[i, i] = cj
M[i, j] = sj*si
M[i, k] = sj*ci
M[j, i] = sj*sk
M[j, j] = -cj*ss+cc
M[j, k] = -cj*cs-sc
M[k, i] = -sj*ck
M[k, j] = cj*sc+cs
M[k, k] = cj*cc-ss
else:
M[i, i] = cj*ck
M[i, j] = sj*sc-cs
M[i, k] = sj*cc+ss
M[j, i] = cj*sk
M[j, j] = sj*ss+cc
M[j, k] = sj*cs-sc
M[k, i] = -sj
M[k, j] = cj*si
M[k, k] = cj*ci
return M
def euler_from_matrix(matrix, axes='sxyz'):
"""Return Euler angles from rotation matrix for specified axis sequence.
axes : One of 24 axis sequences as string or encoded tuple
Note that many Euler angle triplets can describe one matrix.
>>> R0 = euler_matrix(1, 2, 3, 'syxz')
>>> al, be, ga = euler_from_matrix(R0, 'syxz')
>>> R1 = euler_matrix(al, be, ga, 'syxz')
>>> numpy.allclose(R0, R1)
True
>>> angles = (4*math.pi) * (numpy.random.random(3) - 0.5)
>>> for axes in _AXES2TUPLE.keys():
... R0 = euler_matrix(axes=axes, *angles)
... R1 = euler_matrix(axes=axes, *euler_from_matrix(R0, axes))
... if not numpy.allclose(R0, R1): print(axes, "failed")
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
_TUPLE2AXES[axes] # validation
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i+parity]
k = _NEXT_AXIS[i-parity+1]
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j]*M[i, j] + M[i, k]*M[i, k])
if sy > _EPS:
ax = math.atan2( M[i, j], M[i, k])
ay = math.atan2( sy, M[i, i])
az = math.atan2( M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2( sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i]*M[i, i] + M[j, i]*M[j, i])
if cy > _EPS:
ax = math.atan2( M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2( M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return ax, ay, az
def euler_from_quaternion(quaternion, axes='sxyz'):
"""Return Euler angles from quaternion for specified axis sequence.
>>> angles = euler_from_quaternion([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(angles, [0.123, 0, 0])
True
"""
return euler_from_matrix(quaternion_matrix(quaternion), axes)
def quaternion_from_euler(ai, aj, ak, axes='sxyz'):
"""Return quaternion from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> q = quaternion_from_euler(1, 2, 3, 'ryxz')
>>> numpy.allclose(q, [0.435953, 0.310622, -0.718287, 0.444435])
True
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
_TUPLE2AXES[axes] # validation
firstaxis, parity, repetition, frame = axes
i = firstaxis + 1
j = _NEXT_AXIS[i+parity-1] + 1
k = _NEXT_AXIS[i-parity] + 1
if frame:
ai, ak = ak, ai
if parity:
aj = -aj
ai /= 2.0
aj /= 2.0
ak /= 2.0
ci = math.cos(ai)
si = math.sin(ai)
cj = math.cos(aj)
sj = math.sin(aj)
ck = math.cos(ak)
sk = math.sin(ak)
cc = ci*ck
cs = ci*sk
sc = si*ck
ss = si*sk
q = numpy.empty((4, ))
if repetition:
q[0] = cj*(cc - ss)
q[i] = cj*(cs + sc)
q[j] = sj*(cc + ss)
q[k] = sj*(cs - sc)
else:
q[0] = cj*cc + sj*ss
q[i] = cj*sc - sj*cs
q[j] = cj*ss + sj*cc
q[k] = cj*cs - sj*sc
if parity:
q[j] *= -1.0
return q
def quaternion_about_axis(angle, axis):
"""Return quaternion for rotation about axis.
>>> q = quaternion_about_axis(0.123, [1, 0, 0])
>>> numpy.allclose(q, [0.99810947, 0.06146124, 0, 0])
True
"""
q = numpy.array([0.0, axis[0], axis[1], axis[2]])
qlen = vector_norm(q)
if qlen > _EPS:
q *= math.sin(angle/2.0) / qlen
q[0] = math.cos(angle/2.0)
return q
def quaternion_matrix(quaternion):
"""Return homogeneous rotation matrix from quaternion.
>>> M = quaternion_matrix([0.99810947, 0.06146124, 0, 0])
>>> numpy.allclose(M, rotation_matrix(0.123, [1, 0, 0]))
True
>>> M = quaternion_matrix([1, 0, 0, 0])
>>> numpy.allclose(M, numpy.identity(4))
True
>>> M = quaternion_matrix([0, 1, 0, 0])
>>> numpy.allclose(M, numpy.diag([1, -1, -1, 1]))
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
n = numpy.dot(q, q)
if n < _EPS:
return numpy.identity(4)
q *= math.sqrt(2.0 / n)
q = numpy.outer(q, q)
return numpy.array([
[1.0-q[2, 2]-q[3, 3], q[1, 2]-q[3, 0], q[1, 3]+q[2, 0], 0.0],
[ q[1, 2]+q[3, 0], 1.0-q[1, 1]-q[3, 3], q[2, 3]-q[1, 0], 0.0],
[ q[1, 3]-q[2, 0], q[2, 3]+q[1, 0], 1.0-q[1, 1]-q[2, 2], 0.0],
[ 0.0, 0.0, 0.0, 1.0]])
def quaternion_from_matrix(matrix, isprecise=False):
"""Return quaternion from rotation matrix.
If isprecise is True, the input matrix is assumed to be a precise rotation
matrix and a faster algorithm is used.
>>> q = quaternion_from_matrix(numpy.identity(4), True)
>>> numpy.allclose(q, [1, 0, 0, 0])
True
>>> q = quaternion_from_matrix(numpy.diag([1, -1, -1, 1]))
>>> numpy.allclose(q, [0, 1, 0, 0]) or numpy.allclose(q, [0, -1, 0, 0])
True
>>> R = rotation_matrix(0.123, (1, 2, 3))
>>> q = quaternion_from_matrix(R, True)
>>> numpy.allclose(q, [0.9981095, 0.0164262, 0.0328524, 0.0492786])
True
>>> R = [[-0.545, 0.797, 0.260, 0], [0.733, 0.603, -0.313, 0],
... [-0.407, 0.021, -0.913, 0], [0, 0, 0, 1]]
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.19069, 0.43736, 0.87485, -0.083611])
True
>>> R = [[0.395, 0.362, 0.843, 0], [-0.626, 0.796, -0.056, 0],
... [-0.677, -0.498, 0.529, 0], [0, 0, 0, 1]]
>>> q = quaternion_from_matrix(R)
>>> numpy.allclose(q, [0.82336615, -0.13610694, 0.46344705, -0.29792603])
True
>>> R = random_rotation_matrix()
>>> q = quaternion_from_matrix(R)
>>> is_same_transform(R, quaternion_matrix(q))
True
"""
M = numpy.array(matrix, dtype=numpy.float64, copy=False)[:4, :4]
if isprecise:
q = numpy.empty((4, ))
t = numpy.trace(M)
if t > M[3, 3]:
q[0] = t
q[3] = M[1, 0] - M[0, 1]
q[2] = M[0, 2] - M[2, 0]
q[1] = M[2, 1] - M[1, 2]
else:
i, j, k = 1, 2, 3
if M[1, 1] > M[0, 0]:
i, j, k = 2, 3, 1
if M[2, 2] > M[i, i]:
i, j, k = 3, 1, 2
t = M[i, i] - (M[j, j] + M[k, k]) + M[3, 3]
q[i] = t
q[j] = M[i, j] + M[j, i]
q[k] = M[k, i] + M[i, k]
q[3] = M[k, j] - M[j, k]
q *= 0.5 / math.sqrt(t * M[3, 3])
else:
m00 = M[0, 0]
m01 = M[0, 1]
m02 = M[0, 2]
m10 = M[1, 0]
m11 = M[1, 1]
m12 = M[1, 2]
m20 = M[2, 0]
m21 = M[2, 1]
m22 = M[2, 2]
# symmetric matrix K
K = numpy.array([[m00-m11-m22, 0.0, 0.0, 0.0],
[m01+m10, m11-m00-m22, 0.0, 0.0],
[m02+m20, m12+m21, m22-m00-m11, 0.0],
[m21-m12, m02-m20, m10-m01, m00+m11+m22]])
K /= 3.0
# quaternion is eigenvector of K that corresponds to largest eigenvalue
w, V = numpy.linalg.eigh(K)
q = V[[3, 0, 1, 2], numpy.argmax(w)]
if q[0] < 0.0:
numpy.negative(q, q)
return q
def quaternion_multiply(quaternion1, quaternion0):
"""Return multiplication of two quaternions.
>>> q = quaternion_multiply([4, 1, -2, 3], [8, -5, 6, 7])
>>> numpy.allclose(q, [28, -44, -14, 48])
True
"""
w0, x0, y0, z0 = quaternion0
w1, x1, y1, z1 = quaternion1
return numpy.array([-x1*x0 - y1*y0 - z1*z0 + w1*w0,
x1*w0 + y1*z0 - z1*y0 + w1*x0,
-x1*z0 + y1*w0 + z1*x0 + w1*y0,
x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=numpy.float64)
def quaternion_conjugate(quaternion):
"""Return conjugate of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_conjugate(q0)
>>> q1[0] == q0[0] and all(q1[1:] == -q0[1:])
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
numpy.negative(q[1:], q[1:])
return q
def quaternion_inverse(quaternion):
"""Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
numpy.negative(q[1:], q[1:])
return q / numpy.dot(q, q)
def quaternion_real(quaternion):
"""Return real part of quaternion.
>>> quaternion_real([3, 0, 1, 2])
3.0
"""
return float(quaternion[0])
def quaternion_imag(quaternion):
"""Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([ 0., 1., 2.])
"""
return numpy.array(quaternion[1:4], dtype=numpy.float64, copy=True)
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0)
>>> numpy.allclose(q, q0)
True
>>> q = quaternion_slerp(q0, q1, 1, 1)
>>> numpy.allclose(q, q1)
True
>>> q = quaternion_slerp(q0, q1, 0.5)
>>> angle = math.acos(numpy.dot(q0, q))
>>> numpy.allclose(2, math.acos(numpy.dot(q0, q1)) / angle) or \
numpy.allclose(2, math.acos(-numpy.dot(q0, q1)) / angle)
True
"""
q0 = unit_vector(quat0[:4])
q1 = unit_vector(quat1[:4])
if fraction == 0.0:
return q0
elif fraction == 1.0:
return q1
d = numpy.dot(q0, q1)
if abs(abs(d) - 1.0) < _EPS:
return q0
if shortestpath and d < 0.0:
# invert rotation
d = -d
numpy.negative(q1, q1)
angle = math.acos(d) + spin * math.pi
if abs(angle) < _EPS:
return q0
isin = 1.0 / math.sin(angle)
q0 *= math.sin((1.0 - fraction) * angle) * isin
q1 *= math.sin(fraction * angle) * isin
q0 += q1
return q0
def random_quaternion(rand=None):
"""Return uniform random unit quaternion.
rand: array like or None
Three independent random variables that are uniformly distributed
between 0 and 1.
>>> q = random_quaternion()
>>> numpy.allclose(1, vector_norm(q))
True
>>> q = random_quaternion(numpy.random.random(3))
>>> len(q.shape), q.shape[0]==4
(1, True)
"""
if rand is None:
rand = numpy.random.rand(3)
else:
assert len(rand) == 3
r1 = numpy.sqrt(1.0 - rand[0])
r2 = numpy.sqrt(rand[0])
pi2 = math.pi * 2.0
t1 = pi2 * rand[1]
t2 = pi2 * rand[2]
return numpy.array([numpy.cos(t2)*r2, numpy.sin(t1)*r1,
numpy.cos(t1)*r1, numpy.sin(t2)*r2])
def random_rotation_matrix(rand=None):
"""Return uniform random rotation matrix.
rand: array like
Three independent random variables that are uniformly distributed
between 0 and 1 for each returned quaternion.
>>> R = random_rotation_matrix()
>>> numpy.allclose(numpy.dot(R.T, R), numpy.identity(4))
True
"""
return quaternion_matrix(random_quaternion(rand))
class Arcball(object):
"""Virtual Trackball Control.
>>> ball = Arcball()
>>> ball = Arcball(initial=numpy.identity(4))
>>> ball.place([320, 320], 320)
>>> ball.down([500, 250])
>>> ball.drag([475, 275])
>>> R = ball.matrix()
>>> numpy.allclose(numpy.sum(R), 3.90583455)
True
>>> ball = Arcball(initial=[1, 0, 0, 0])
>>> ball.place([320, 320], 320)
>>> ball.setaxes([1, 1, 0], [-1, 1, 0])
>>> ball.constrain = True
>>> ball.down([400, 200])
>>> ball.drag([200, 400])
>>> R = ball.matrix()
>>> numpy.allclose(numpy.sum(R), 0.2055924)
True
>>> ball.next()
"""
def __init__(self, initial=None):
"""Initialize virtual trackball control.
initial : quaternion or rotation matrix
"""
self._axis = None
self._axes = None
self._radius = 1.0
self._center = [0.0, 0.0]
self._vdown = numpy.array([0.0, 0.0, 1.0])
self._constrain = False
if initial is None:
self._qdown = numpy.array([1.0, 0.0, 0.0, 0.0])
else:
initial = numpy.array(initial, dtype=numpy.float64)
if initial.shape == (4, 4):
self._qdown = quaternion_from_matrix(initial)
elif initial.shape == (4, ):
initial /= vector_norm(initial)
self._qdown = initial
else:
raise ValueError("initial not a quaternion or matrix")
self._qnow = self._qpre = self._qdown
def place(self, center, radius):
"""Place Arcball, e.g. when window size changes.
center : sequence[2]
Window coordinates of trackball center.
radius : float
Radius of trackball in window coordinates.
"""
self._radius = float(radius)
self._center[0] = center[0]
self._center[1] = center[1]
def setaxes(self, *axes):
"""Set axes to constrain rotations."""
if axes is None:
self._axes = None
else:
self._axes = [unit_vector(axis) for axis in axes]
@property
def constrain(self):
"""Return state of constrain to axis mode."""
return self._constrain
@constrain.setter
def constrain(self, value):
"""Set state of constrain to axis mode."""
self._constrain = bool(value)
def down(self, point):
"""Set initial cursor window coordinates and pick constrain-axis."""
self._vdown = arcball_map_to_sphere(point, self._center, self._radius)
self._qdown = self._qpre = self._qnow
if self._constrain and self._axes is not None:
self._axis = arcball_nearest_axis(self._vdown, self._axes)
self._vdown = arcball_constrain_to_axis(self._vdown, self._axis)
else:
self._axis = None
def drag(self, point):
"""Update current cursor window coordinates."""
vnow = arcball_map_to_sphere(point, self._center, self._radius)
if self._axis is not None:
vnow = arcball_constrain_to_axis(vnow, self._axis)
self._qpre = self._qnow
t = numpy.cross(self._vdown, vnow)
if numpy.dot(t, t) < _EPS:
self._qnow = self._qdown
else:
q = [numpy.dot(self._vdown, vnow), t[0], t[1], t[2]]
self._qnow = quaternion_multiply(q, self._qdown)
def next(self, acceleration=0.0):
"""Continue rotation in direction of last drag."""
q = quaternion_slerp(self._qpre, self._qnow, 2.0+acceleration, False)
self._qpre, self._qnow = self._qnow, q
def matrix(self):
"""Return homogeneous rotation matrix."""
return quaternion_matrix(self._qnow)
def arcball_map_to_sphere(point, center, radius):
"""Return unit sphere coordinates from window coordinates."""
v0 = (point[0] - center[0]) / radius
v1 = (center[1] - point[1]) / radius
n = v0*v0 + v1*v1
if n > 1.0:
# position outside of sphere
n = math.sqrt(n)
return numpy.array([v0/n, v1/n, 0.0])
else:
return numpy.array([v0, v1, math.sqrt(1.0 - n)])
def arcball_constrain_to_axis(point, axis):
"""Return sphere point perpendicular to axis."""
v = numpy.array(point, dtype=numpy.float64, copy=True)
a = numpy.array(axis, dtype=numpy.float64, copy=True)
v -= a * numpy.dot(a, v) # on plane
n = vector_norm(v)
if n > _EPS:
if v[2] < 0.0:
numpy.negative(v, v)
v /= n
return v
if a[2] == 1.0:
return numpy.array([1.0, 0.0, 0.0])
return unit_vector([-a[1], a[0], 0.0])
def arcball_nearest_axis(point, axes):
"""Return axis, which arc is nearest to point."""
point = numpy.array(point, dtype=numpy.float64, copy=False)
nearest = None
mx = -1.0
for axis in axes:
t = numpy.dot(arcball_constrain_to_axis(point, axis), point)
if t > mx:
nearest = axis
mx = t
return nearest
# epsilon for testing whether a number is close to zero
_EPS = numpy.finfo(float).eps * 4.0
# axis sequences for Euler angles
_NEXT_AXIS = [1, 2, 0, 1]
# map axes strings to/from tuples of inner axis, parity, repetition, frame
_AXES2TUPLE = {
'sxyz': (0, 0, 0, 0), 'sxyx': (0, 0, 1, 0), 'sxzy': (0, 1, 0, 0),
'sxzx': (0, 1, 1, 0), 'syzx': (1, 0, 0, 0), 'syzy': (1, 0, 1, 0),
'syxz': (1, 1, 0, 0), 'syxy': (1, 1, 1, 0), 'szxy': (2, 0, 0, 0),
'szxz': (2, 0, 1, 0), 'szyx': (2, 1, 0, 0), 'szyz': (2, 1, 1, 0),
'rzyx': (0, 0, 0, 1), 'rxyx': (0, 0, 1, 1), 'ryzx': (0, 1, 0, 1),
'rxzx': (0, 1, 1, 1), 'rxzy': (1, 0, 0, 1), 'ryzy': (1, 0, 1, 1),
'rzxy': (1, 1, 0, 1), 'ryxy': (1, 1, 1, 1), 'ryxz': (2, 0, 0, 1),
'rzxz': (2, 0, 1, 1), 'rxyz': (2, 1, 0, 1), 'rzyz': (2, 1, 1, 1)}
_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items())
def vector_norm(data, axis=None, out=None):
"""Return length, i.e. Euclidean norm, of ndarray along axis.
>>> v = numpy.random.random(3)
>>> n = vector_norm(v)
>>> numpy.allclose(n, numpy.linalg.norm(v))
True
>>> v = numpy.random.rand(6, 5, 3)
>>> n = vector_norm(v, axis=-1)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2)))
True
>>> n = vector_norm(v, axis=1)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
True
>>> v = numpy.random.rand(5, 4, 3)
>>> n = numpy.empty((5, 3))
>>> vector_norm(v, axis=1, out=n)
>>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
True
>>> vector_norm([])
0.0
>>> vector_norm([1])
1.0
"""
data = numpy.array(data, dtype=numpy.float64, copy=True)
if out is None:
if data.ndim == 1:
return math.sqrt(numpy.dot(data, data))
data *= data
out = numpy.atleast_1d(numpy.sum(data, axis=axis))
numpy.sqrt(out, out)
return out
else:
data *= data
numpy.sum(data, axis=axis, out=out)
numpy.sqrt(out, out)
def unit_vector(data, axis=None, out=None):
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis.
>>> v0 = numpy.random.random(3)
>>> v1 = unit_vector(v0)
>>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0))
True
>>> v0 = numpy.random.rand(5, 4, 3)
>>> v1 = unit_vector(v0, axis=-1)
>>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2)
>>> numpy.allclose(v1, v2)
True
>>> v1 = unit_vector(v0, axis=1)
>>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1)
>>> numpy.allclose(v1, v2)
True
>>> v1 = numpy.empty((5, 4, 3))
>>> unit_vector(v0, axis=1, out=v1)
>>> numpy.allclose(v1, v2)
True
>>> list(unit_vector([]))
[]
>>> list(unit_vector([1]))
[1.0]
"""
if out is None:
data = numpy.array(data, dtype=numpy.float64, copy=True)
if data.ndim == 1:
data /= math.sqrt(numpy.dot(data, data))
return data
else:
if out is not data:
out[:] = numpy.array(data, copy=False)
data = out
length = numpy.atleast_1d(numpy.sum(data*data, axis))
numpy.sqrt(length, length)
if axis is not None:
length = numpy.expand_dims(length, axis)
data /= length
if out is None:
return data
def random_vector(size):
"""Return array of random doubles in the half-open interval [0.0, 1.0).
>>> v = random_vector(10000)
>>> numpy.all(v >= 0) and numpy.all(v < 1)
True
>>> v0 = random_vector(10)
>>> v1 = random_vector(10)
>>> numpy.any(v0 == v1)
False
"""
return numpy.random.random(size)
def vector_product(v0, v1, axis=0):
"""Return vector perpendicular to vectors.
>>> v = vector_product([2, 0, 0], [0, 3, 0])
>>> numpy.allclose(v, [0, 0, 6])
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> v = vector_product(v0, v1)
>>> numpy.allclose(v, [[0, 0, 0, 0], [0, 0, 6, 6], [0, -6, 0, -6]])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> v = vector_product(v0, v1, axis=1)
>>> numpy.allclose(v, [[0, 0, 6], [0, -6, 0], [6, 0, 0], [0, -6, 6]])
True
"""
return numpy.cross(v0, v1, axis=axis)
def angle_between_vectors(v0, v1, directed=True, axis=0):
"""Return angle between vectors.
If directed is False, the input vectors are interpreted as undirected axes,
i.e. the maximum angle is pi/2.
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3])
>>> numpy.allclose(a, math.pi)
True
>>> a = angle_between_vectors([1, -2, 3], [-1, 2, -3], directed=False)
>>> numpy.allclose(a, 0)
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> a = angle_between_vectors(v0, v1)
>>> numpy.allclose(a, [0, 1.5708, 1.5708, 0.95532])
True
>>> v0 = [[2, 0, 0], [2, 0, 0], [0, 2, 0], [2, 0, 0]]
>>> v1 = [[0, 3, 0], [0, 0, 3], [0, 0, 3], [3, 3, 3]]
>>> a = angle_between_vectors(v0, v1, axis=1)
>>> numpy.allclose(a, [1.5708, 1.5708, 1.5708, 0.95532])
True
"""
v0 = numpy.array(v0, dtype=numpy.float64, copy=False)
v1 = numpy.array(v1, dtype=numpy.float64, copy=False)
dot = numpy.sum(v0 * v1, axis=axis)
dot /= vector_norm(v0, axis=axis) * vector_norm(v1, axis=axis)
return numpy.arccos(dot if directed else numpy.fabs(dot))
def inverse_matrix(matrix):
"""Return inverse of square transformation matrix.
>>> M0 = random_rotation_matrix()
>>> M1 = inverse_matrix(M0.T)
>>> numpy.allclose(M1, numpy.linalg.inv(M0.T))
True
>>> for size in range(1, 7):
... M0 = numpy.random.rand(size, size)
... M1 = inverse_matrix(M0)
... if not numpy.allclose(M1, numpy.linalg.inv(M0)): print(size)
"""
return numpy.linalg.inv(matrix)
def concatenate_matrices(*matrices):
"""Return concatenation of series of transformation matrices.
>>> M = numpy.random.rand(16).reshape((4, 4)) - 0.5
>>> numpy.allclose(M, concatenate_matrices(M))
True
>>> numpy.allclose(numpy.dot(M, M.T), concatenate_matrices(M, M.T))
True
"""
M = numpy.identity(4)
for i in matrices:
M = numpy.dot(M, i)
return M
def is_same_transform(matrix0, matrix1):
"""Return True if two matrices perform same transformation.
>>> is_same_transform(numpy.identity(4), numpy.identity(4))
True
>>> is_same_transform(numpy.identity(4), random_rotation_matrix())
False
"""
matrix0 = numpy.array(matrix0, dtype=numpy.float64, copy=True)
matrix0 /= matrix0[3, 3]
matrix1 = numpy.array(matrix1, dtype=numpy.float64, copy=True)
matrix1 /= matrix1[3, 3]
return numpy.allclose(matrix0, matrix1)
def matrixToEuler(mat):
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'
notes : this conversion uses conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm'
Coordinate System: right hand
Positive angle: right hand
Order of euler angles: heading first, then attitude, then bank
matrix row column ordering:
[m00 m01 m02]
[m10 m11 m12]
[m20 m21 m22]
@type mat: 4x4array
@param mat: the matrix to convert in euler angle (heading,attitude,bank)
@rtype: 3d array
@return: the computed euler angle from the matrice
"""
#Assuming the angles are in radians.
#3,3 matrix m[0:3,0:3]
#return heading,attitude,bank Y,Z,X
import math
if (mat[1][0] > 0.998) : # singularity at north pole
heading = math.atan2(mat[0][2],mat[2][2])
attitude = math.pi/2.
bank = 0
return (heading,attitude,bank)
if (mat[1][0] < -0.998) : # singularity at south pole
heading = math.atan2(mat[0][2],mat[2][2])
attitude = -math.pi/2.
bank = 0
return (heading,attitude,bank)
heading = math.atan2(-mat[2][0],mat[0][0])
bank = math.atan2(-mat[1][2],mat[1][1])
attitude = math.asin(mat[1][0])
if mat[0][0] < 0 :
if (attitude < 0.) and (math.degrees(attitude) > -90.):
attitude = -math.pi-attitude
elif (attitude > 0.) and (math.degrees(attitude) < 90.):
attitude = math.pi-attitude
return (heading,attitude,bank)
def unbiasedRotationXYZ(ex,ey,ez):
M=numpy.identity(3)
e=math.sqrt((ex*ex)+(ey*ey)+(ez*ez))
e2=(ex*ex)+(ey*ey)+(ez*ez)
M[0,0] = M11 = ((ey*ey)+(ez*ez)*math.cos(e)+(ex*ex))/(e*e)
M[0,1] = M12 = ((ex*ey)/(e*e))*(1-math.cos(e))-(ez/e)*math.sin(e)
M[0,2] = M13 = ((ex*ez)/(e*e))*(1-math.cos(e))-(ey/e)*math.sin(e)
M[1,0] = M21 = ((ex*ey)/(e*e))*(1-math.cos(e))+(ez/e)*math.sin(e)
M[1,1] = M22 = ((ex*ex)+(ez*ez)*math.cos(e)+(ey*ey))/(e*e)
M[1,2] = M23 = ((ey*ez)/(e*e))*(1-math.cos(e))-(ex/e)*math.sin(e)
M[2,0] = M31 = ((ex*ez)/(e*e))*(1-math.cos(e))-(ey/e)*math.sin(e)
M[2,1] = M32 = ((ey*ez)/(e*e))*(1-math.cos(e))+(ex/e)*math.sin(e)
M[2,2] = M33 = ((ex*ex)+(ey*ey)*math.cos(e)+(ez*ez))/(e*e)
return M
def ApplyMatrix(coords,mat):
"""
Apply the 4x4 transformation matrix to the given list of 3d points.
@type coords: array
@param coords: the list of point to transform.
@type mat: 4x4array
@param mat: the matrix to apply to the 3d points
@rtype: array
@return: the transformed list of 3d points
"""
#4x4matrix"
mat = numpy.array(mat)
coords = numpy.array(coords)
one = numpy.ones( (coords.shape[0], 1), coords.dtype.char )
c = numpy.concatenate( (coords, one), 1 )
return numpy.dot(c, numpy.transpose(mat))[:, :3]
#def _import_module(name, package=None, warn=True, prefix='_py_', ignore='_'):
# """Try import all public attributes from module into global namespace.
#
# Existing attributes with name clashes are renamed with prefix.
# Attributes starting with underscore are ignored by default.
#
# Return True on successful import.
#
# """
# import warnings
# from importlib import import_module
# try:
# if not package:
# module = import_module(name)
# else:
# module = import_module('.' + name, package=package)
# except ImportError:
# if warn:
# warnings.warn("failed to import module %s" % name)
# else:
# for attr in dir(module):
# if ignore and attr.startswith(ignore):
# continue
# if prefix:
# if attr in globals():
# globals()[prefix + attr] = globals()[attr]
# elif warn:
# warnings.warn("no Python implementation of " + attr)
# globals()[attr] = getattr(module, attr)
# return True
#
#
#_import_module('_transformations')
#
#if __name__ == "__main__":
# import doctest
# import random # used in doctests
# numpy.set_printoptions(suppress=True, precision=5)
# doctest.testmod()
|
gpl-3.0
| -2,078,898,188,954,768,100
| 33.503778
| 83
| 0.578706
| false
| 2.98935
| false
| false
| false
|
bepress/xavier
|
xavier/taskqueue.py
|
1
|
2517
|
"""
Offline Manager for Xavier
"""
import logging
import jsonpickle
logger = logging.getLogger(__name__)
class Task(object):
def __init__(self, func):
self.func = func
self.path = '%s.%s' % (func.__name__, func.__module__)
self.publish_event = None
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def delay(self, *args, **kwargs):
event = jsonpickle.dumps((self.path, args, kwargs))
if not self.publish_event:
logger.error("This task has not yet been registered with a task queue")
return False
self.publish_event(event)
return True
def register_with_queue(self, publish_event):
self.publish_event = publish_event
def __repr__(self):
return self.__unicode__()
def __unicode__(self):
return "BackgroundTask(path='{}')".format(self.path)
class TaskQueue(object):
def __init__(self, publish_event):
self.functions = {}
self.publish_event = publish_event
self.schedules = {}
def process_event(self, event):
name, args, kwargs = jsonpickle.loads(event)
func = self.functions.get(name)
if not func:
logger.info("processing event - missing function name: %s", name)
raise Exception("Missing function")
try:
func(*args, **kwargs)
except Exception as e:
return False
return True
def process_schedule(self, schedule):
if schedule not in self.schedules:
logger.info("Trying to process schedule for unknown schedule: %s", schedule)
return
scheduled_functions = self.schedules[schedule]
logger.info("Running schedule %s registered functions: %s", schedule, scheduled_functions)
for func in scheduled_functions:
func.delay()
def register_task(self, task, schedules):
self.functions[task.path] = task
for schedule in schedules:
if schedule not in self.schedules:
self.schedules[schedule] = []
if task.path not in self.schedules[schedule]:
self.schedules[schedule].append(task)
task.register_with_queue(self.publish_event)
def task(self, schedules=None):
schedules = schedules if schedules else []
def wrapper(func):
func = Task(func)
self.register_task(func, schedules)
return func
return wrapper
|
mit
| -8,391,339,796,450,315,000
| 26.064516
| 98
| 0.594358
| false
| 4.237374
| false
| false
| false
|
zestrada/nova-cs498cc
|
nova/cells/manager.py
|
1
|
15722
|
# Copyright (c) 2012 Rackspace Hosting
# 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 implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Cells Service Manager
"""
import datetime
import time
from oslo.config import cfg
from nova.cells import messaging
from nova.cells import state as cells_state
from nova.cells import utils as cells_utils
from nova import context
from nova import exception
from nova import manager
from nova.openstack.common import importutils
from nova.openstack.common import timeutils
cell_manager_opts = [
cfg.StrOpt('driver',
default='nova.cells.rpc_driver.CellsRPCDriver',
help='Cells communication driver to use'),
cfg.IntOpt("instance_updated_at_threshold",
default=3600,
help="Number of seconds after an instance was updated "
"or deleted to continue to update cells"),
cfg.IntOpt("instance_update_num_instances",
default=1,
help="Number of instances to update per periodic task run")
]
CONF = cfg.CONF
CONF.register_opts(cell_manager_opts, group='cells')
class CellsManager(manager.Manager):
"""The nova-cells manager class. This class defines RPC
methods that the local cell may call. This class is NOT used for
messages coming from other cells. That communication is
driver-specific.
Communication to other cells happens via the messaging module. The
MessageRunner from that module will handle routing the message to
the correct cell via the communications driver. Most methods below
create 'targeted' (where we want to route a message to a specific cell)
or 'broadcast' (where we want a message to go to multiple cells)
messages.
Scheduling requests get passed to the scheduler class.
"""
RPC_API_VERSION = '1.6'
def __init__(self, *args, **kwargs):
# Mostly for tests.
cell_state_manager = kwargs.pop('cell_state_manager', None)
super(CellsManager, self).__init__(*args, **kwargs)
if cell_state_manager is None:
cell_state_manager = cells_state.CellStateManager
self.state_manager = cell_state_manager()
self.msg_runner = messaging.MessageRunner(self.state_manager)
cells_driver_cls = importutils.import_class(
CONF.cells.driver)
self.driver = cells_driver_cls()
self.instances_to_heal = iter([])
def post_start_hook(self):
"""Have the driver start its consumers for inter-cell communication.
Also ask our child cells for their capacities and capabilities so
we get them more quickly than just waiting for the next periodic
update. Receiving the updates from the children will cause us to
update our parents. If we don't have any children, just update
our parents immediately.
"""
# FIXME(comstud): There's currently no hooks when services are
# stopping, so we have no way to stop consumers cleanly.
self.driver.start_consumers(self.msg_runner)
ctxt = context.get_admin_context()
if self.state_manager.get_child_cells():
self.msg_runner.ask_children_for_capabilities(ctxt)
self.msg_runner.ask_children_for_capacities(ctxt)
else:
self._update_our_parents(ctxt)
@manager.periodic_task
def _update_our_parents(self, ctxt):
"""Update our parent cells with our capabilities and capacity
if we're at the bottom of the tree.
"""
self.msg_runner.tell_parents_our_capabilities(ctxt)
self.msg_runner.tell_parents_our_capacities(ctxt)
@manager.periodic_task
def _heal_instances(self, ctxt):
"""Periodic task to send updates for a number of instances to
parent cells.
On every run of the periodic task, we will attempt to sync
'CONF.cells.instance_update_num_instances' number of instances.
When we get the list of instances, we shuffle them so that multiple
nova-cells services aren't attempting to sync the same instances
in lockstep.
If CONF.cells.instance_update_at_threshold is set, only attempt
to sync instances that have been updated recently. The CONF
setting defines the maximum number of seconds old the updated_at
can be. Ie, a threshold of 3600 means to only update instances
that have modified in the last hour.
"""
if not self.state_manager.get_parent_cells():
# No need to sync up if we have no parents.
return
info = {'updated_list': False}
def _next_instance():
try:
instance = self.instances_to_heal.next()
except StopIteration:
if info['updated_list']:
return
threshold = CONF.cells.instance_updated_at_threshold
updated_since = None
if threshold > 0:
updated_since = timeutils.utcnow() - datetime.timedelta(
seconds=threshold)
self.instances_to_heal = cells_utils.get_instances_to_sync(
ctxt, updated_since=updated_since, shuffle=True,
uuids_only=True)
info['updated_list'] = True
try:
instance = self.instances_to_heal.next()
except StopIteration:
return
return instance
rd_context = ctxt.elevated(read_deleted='yes')
for i in xrange(CONF.cells.instance_update_num_instances):
while True:
# Yield to other greenthreads
time.sleep(0)
instance_uuid = _next_instance()
if not instance_uuid:
return
try:
instance = self.db.instance_get_by_uuid(rd_context,
instance_uuid)
except exception.InstanceNotFound:
continue
self._sync_instance(ctxt, instance)
break
def _sync_instance(self, ctxt, instance):
"""Broadcast an instance_update or instance_destroy message up to
parent cells.
"""
if instance['deleted']:
self.instance_destroy_at_top(ctxt, instance)
else:
self.instance_update_at_top(ctxt, instance)
def schedule_run_instance(self, ctxt, host_sched_kwargs):
"""Pick a cell (possibly ourselves) to build new instance(s)
and forward the request accordingly.
"""
# Target is ourselves first.
our_cell = self.state_manager.get_my_state()
self.msg_runner.schedule_run_instance(ctxt, our_cell,
host_sched_kwargs)
def get_cell_info_for_neighbors(self, _ctxt):
"""Return cell information for our neighbor cells."""
return self.state_manager.get_cell_info_for_neighbors()
def run_compute_api_method(self, ctxt, cell_name, method_info, call):
"""Call a compute API method in a specific cell."""
response = self.msg_runner.run_compute_api_method(ctxt,
cell_name,
method_info,
call)
if call:
return response.value_or_raise()
def instance_update_at_top(self, ctxt, instance):
"""Update an instance at the top level cell."""
self.msg_runner.instance_update_at_top(ctxt, instance)
def instance_destroy_at_top(self, ctxt, instance):
"""Destroy an instance at the top level cell."""
self.msg_runner.instance_destroy_at_top(ctxt, instance)
def instance_delete_everywhere(self, ctxt, instance, delete_type):
"""This is used by API cell when it didn't know what cell
an instance was in, but the instance was requested to be
deleted or soft_deleted. So, we'll broadcast this everywhere.
"""
self.msg_runner.instance_delete_everywhere(ctxt, instance,
delete_type)
def instance_fault_create_at_top(self, ctxt, instance_fault):
"""Create an instance fault at the top level cell."""
self.msg_runner.instance_fault_create_at_top(ctxt, instance_fault)
def bw_usage_update_at_top(self, ctxt, bw_update_info):
"""Update bandwidth usage at top level cell."""
self.msg_runner.bw_usage_update_at_top(ctxt, bw_update_info)
def sync_instances(self, ctxt, project_id, updated_since, deleted):
"""Force a sync of all instances, potentially by project_id,
and potentially since a certain date/time.
"""
self.msg_runner.sync_instances(ctxt, project_id, updated_since,
deleted)
def service_get_all(self, ctxt, filters):
"""Return services in this cell and in all child cells."""
responses = self.msg_runner.service_get_all(ctxt, filters)
ret_services = []
# 1 response per cell. Each response is a list of services.
for response in responses:
services = response.value_or_raise()
for service in services:
cells_utils.add_cell_to_service(service, response.cell_name)
ret_services.append(service)
return ret_services
def service_get_by_compute_host(self, ctxt, host_name):
"""Return a service entry for a compute host in a certain cell."""
cell_name, host_name = cells_utils.split_cell_and_item(host_name)
response = self.msg_runner.service_get_by_compute_host(ctxt,
cell_name,
host_name)
service = response.value_or_raise()
cells_utils.add_cell_to_service(service, response.cell_name)
return service
def proxy_rpc_to_manager(self, ctxt, topic, rpc_message, call, timeout):
"""Proxy an RPC message as-is to a manager."""
compute_topic = CONF.compute_topic
cell_and_host = topic[len(compute_topic) + 1:]
cell_name, host_name = cells_utils.split_cell_and_item(cell_and_host)
response = self.msg_runner.proxy_rpc_to_manager(ctxt, cell_name,
host_name, topic, rpc_message, call, timeout)
return response.value_or_raise()
def task_log_get_all(self, ctxt, task_name, period_beginning,
period_ending, host=None, state=None):
"""Get task logs from the DB from all cells or a particular
cell.
If 'host' is not None, host will be of the format 'cell!name@host',
with '@host' being optional. The query will be directed to the
appropriate cell and return all task logs, or task logs matching
the host if specified.
'state' also may be None. If it's not, filter by the state as well.
"""
if host is None:
cell_name = None
else:
cell_name, host = cells_utils.split_cell_and_item(host)
# If no cell name was given, assume that the host name is the
# cell_name and that the target is all hosts
if cell_name is None:
cell_name, host = host, cell_name
responses = self.msg_runner.task_log_get_all(ctxt, cell_name,
task_name, period_beginning, period_ending,
host=host, state=state)
# 1 response per cell. Each response is a list of task log
# entries.
ret_task_logs = []
for response in responses:
task_logs = response.value_or_raise()
for task_log in task_logs:
cells_utils.add_cell_to_task_log(task_log,
response.cell_name)
ret_task_logs.append(task_log)
return ret_task_logs
def compute_node_get(self, ctxt, compute_id):
"""Get a compute node by ID in a specific cell."""
cell_name, compute_id = cells_utils.split_cell_and_item(
compute_id)
response = self.msg_runner.compute_node_get(ctxt, cell_name,
compute_id)
node = response.value_or_raise()
cells_utils.add_cell_to_compute_node(node, cell_name)
return node
def compute_node_get_all(self, ctxt, hypervisor_match=None):
"""Return list of compute nodes in all cells."""
responses = self.msg_runner.compute_node_get_all(ctxt,
hypervisor_match=hypervisor_match)
# 1 response per cell. Each response is a list of compute_node
# entries.
ret_nodes = []
for response in responses:
nodes = response.value_or_raise()
for node in nodes:
cells_utils.add_cell_to_compute_node(node,
response.cell_name)
ret_nodes.append(node)
return ret_nodes
def compute_node_stats(self, ctxt):
"""Return compute node stats totals from all cells."""
responses = self.msg_runner.compute_node_stats(ctxt)
totals = {}
for response in responses:
data = response.value_or_raise()
for key, val in data.iteritems():
totals.setdefault(key, 0)
totals[key] += val
return totals
def actions_get(self, ctxt, cell_name, instance_uuid):
response = self.msg_runner.actions_get(ctxt, cell_name, instance_uuid)
return response.value_or_raise()
def action_get_by_request_id(self, ctxt, cell_name, instance_uuid,
request_id):
response = self.msg_runner.action_get_by_request_id(ctxt, cell_name,
instance_uuid,
request_id)
return response.value_or_raise()
def action_events_get(self, ctxt, cell_name, action_id):
response = self.msg_runner.action_events_get(ctxt, cell_name,
action_id)
return response.value_or_raise()
def consoleauth_delete_tokens(self, ctxt, instance_uuid):
"""Delete consoleauth tokens for an instance in API cells."""
self.msg_runner.consoleauth_delete_tokens(ctxt, instance_uuid)
def validate_console_port(self, ctxt, instance_uuid, console_port,
console_type):
"""Validate console port with child cell compute node."""
instance = self.db.instance_get_by_uuid(ctxt, instance_uuid)
if not instance['cell_name']:
raise exception.InstanceUnknownCell(instance_uuid=instance_uuid)
response = self.msg_runner.validate_console_port(ctxt,
instance['cell_name'], instance_uuid, console_port,
console_type)
return response.value_or_raise()
|
apache-2.0
| -814,845,744,529,827,200
| 42.551247
| 78
| 0.596871
| false
| 4.357539
| false
| false
| false
|
ShaguptaS/moviepy
|
moviepy/video/fx/resize.py
|
1
|
3276
|
resize_possible = True
try:
import cv2
resizer = lambda pic, newsize : cv2.resize(pic.astype('uint8'),
tuple(map(int, newsize)),
interpolation=cv2.INTER_AREA)
except ImportError:
try:
import Image
import numpy as np
def resizer(pic, newsize):
newsize = map(int, newsize)[::-1]
shape = pic.shape
newshape = (newsize[0],newsize[1],shape[2])
pilim = Image.fromarray(pic)
resized_pil = pilim.resize(newsize[::-1], Image.ANTIALIAS)
arr = np.fromstring(resized_pil.tostring(), dtype='uint8')
return arr.reshape(newshape)
except ImportError:
try:
import scipy.misc.imresize as imresize
resizer = lambda pic, newsize : imresize(pic,
map(int, newsize[::-1]))
except ImportError:
resize_possible = False
from moviepy.decorators import apply_to_mask
@apply_to_mask
def resize(clip, newsize=None, height=None, width=None):
"""
Returns a video clip that is a resized version of the clip.
:param newsize: can be either ``(height,width)`` in pixels or
a float representing a scaling factor. Or a function of time
returning one of these.
:param width: width of the new clip in pixel. The height is
then computed so that the width/height ratio is conserved.
:param height: height of the new clip in pixel. The width is
then computed so that the width/height ratio is conserved.
>>> myClip.resize( (460,720) ) # New resolution: (460,720)
>>> myClip.resize(0.6) # width and heigth multiplied by 0.6
>>> myClip.resize(width=800) # height computed automatically.
>>> myClip.resize(lambda t : 1+0.02*t) # slow swelling of the clip
"""
w, h = clip.size
if newsize != None:
def trans_newsize(ns):
if isinstance(ns, (int, float)):
return [ns * w, ns * h]
else:
return ns
if hasattr(newsize, "__call__"):
newsize2 = lambda t : trans_newsize(newsize(t))
if clip.ismask:
fl = lambda gf,t: 1.0*resizer((255 * gf(t)).astype('uint8'),
newsize2(t))/255
else:
fl = lambda gf,t: resizer(gf(t).astype('uint8'),newsize2(t))
return clip.fl(fl)
else:
newsize = trans_newsize(newsize)
elif height != None:
newsize = [w * height / h, height]
elif width != None:
newsize = [width, h * width / w]
if clip.ismask:
fl = lambda pic: 1.0*resizer((255 * pic).astype('uint8'),
newsize)/255
else:
fl = lambda pic: resizer(pic.astype('uint8'), newsize)
return clip.fl_image(fl)
if not resize_possible:
doc = resize.__doc__
def resize(clip, newsize=None, height=None, width=None):
raise ImportError("fx resize needs OpenCV or Scipy or PIL")
resize.__doc__ = doc
|
mit
| -3,920,737,535,064,460,300
| 31.117647
| 76
| 0.53083
| false
| 3.995122
| false
| false
| false
|
BrendanLeber/adventofcode
|
2016/20-firewall_rules/firewall_rules.py
|
1
|
1586
|
# -*- coding: utf-8 -*-
import argparse
import pdb
import traceback
from typing import List, Tuple
def test_ip(ip: int, rules: List[Tuple[int, int]], max_addr: int) -> bool:
for (start, end) in rules:
if start <= ip <= end:
break
else:
if ip < max_addr:
return True
return False
def solve(rules: List[Tuple[int, int]], max_addr: int) -> Tuple[int, int]:
candidates = [rule[1] + 1 for rule in rules]
valids = [candidate for candidate in candidates if test_ip(candidate, rules, max_addr)]
one: int = valids[0]
two: int = 0
for ip in valids:
while test_ip(ip, rules, max_addr):
two += 1
ip += 1
return (one, two)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Advent of Code - 2016 - Day 20 - Firewall Rules.")
parser.add_argument(
"input",
type=str,
default="input.txt",
nargs="?",
help="The puzzle input. (Default %(default)s)",
)
parser.add_argument(
"max_addr",
type=int,
default=4294967296,
nargs="?",
help="The largest address. (Default %(default)s)",
)
args = parser.parse_args()
rules: List[Tuple[int, int]] = []
with open(args.input, "rt") as inf:
for line in inf:
parts = line.strip().split("-")
rules.append((int(parts[0]), int(parts[1])))
rules.sort()
try:
print(solve(rules, args.max_addr))
except Exception:
traceback.print_exc()
pdb.post_mortem()
|
mit
| 2,803,982,701,570,625,000
| 24.580645
| 100
| 0.552333
| false
| 3.580135
| false
| false
| false
|
uwosh/UWOshOIE
|
tests/testTransitionApproveForFA.py
|
1
|
4225
|
import os, sys
if __name__ == '__main__':
execfile(os.path.join(sys.path[0], 'framework.py'))
from Products.UWOshOIE.tests.uwoshoietestcase import UWOshOIETestCase
from Products.CMFCore.WorkflowCore import WorkflowException
class TestTransitionApproveForFA(UWOshOIETestCase):
"""Ensure product is properly installed"""
def createApplication(self):
self.login(self._default_user)
self.portal.invokeFactory(type_name="OIEStudentApplication", id="testapplication")
app = self.portal['testapplication']
self.fill_out_application(app)
app.setHoldApplication('HOLD')
self.portal_workflow.doActionFor(app, 'submit')
return app
def test_program_manager_should_be_able_to_do_action(self):
app = self.createApplication()
self.login('program_manager')
self.portal_workflow.doActionFor(app, 'approveForFA')
self.assertEquals('waitingForPrintMaterials', self.getState(app))
def test_front_line_advisor_should_be_able_to_do_action(self):
app = self.createApplication()
self.login('front_line_advisor')
self.portal_workflow.doActionFor(app, 'approveForFA')
self.assertEquals('waitingForPrintMaterials', self.getState(app))
def test_all_other_roles_should_not_be_able_able_to_perform_action(self):
app = self.createApplication
for user in self._all_users:
if user != 'program_maanger' and user != 'front_line_advisor':
self.login(user)
self.assertRaises(WorkflowException, self.portal_workflow.doActionFor, app, 'approveForFA')
self.logout()
def test_should_send_email_when_fired(self):
app = self.createApplication()
self.portal.MailHost.clearEmails()
self.login('program_manager')
self.portal_workflow.doActionFor(app, 'approveForFA')
self.assertEquals(1, self.portal.MailHost.getEmailCount())
def test_should_send_correct_email_program_maanger(self):
app = self.createApplication()
self.portal.MailHost.clearEmails()
self.login('program_manager')
self.portal_workflow.doActionFor(app, 'approveForFA')
to = self.portal.MailHost.getTo()
f = self.portal.MailHost.getFrom()
subject = self.portal.MailHost.getSubject()
message = self.portal.MailHost.getMessage()
self.assertEquals(['applicant@uwosh.edu', 'oie@uwosh.edu'], to)
self.assertEquals('program_manager@oie.com', f)
self.assertEquals('Your study abroad application update (UW Oshkosh Office of International Education)', subject)
self.assertEquals("\n\nYour UW Oshkosh Office of International Education study abroad application has been updated.\n\nName: John Doe\nProgram Name: test\nProgram Year: 2009\n\nTransition\n\n\n\nYou can view your application here: http://nohost/plone/testapplication\n\nComment: \n\n\n", message)
def test_should_send_correct_email_front_line_advisor(self):
app = self.createApplication()
self.portal.MailHost.clearEmails()
self.login('front_line_advisor')
self.portal_workflow.doActionFor(app, 'approveForFA')
to = self.portal.MailHost.getTo()
f = self.portal.MailHost.getFrom()
subject = self.portal.MailHost.getSubject()
message = self.portal.MailHost.getMessage()
self.assertEquals(['applicant@uwosh.edu', 'oie@uwosh.edu'], to)
self.assertEquals('front_line_advisor@oie.com', f)
self.assertEquals('Your study abroad application update (UW Oshkosh Office of International Education)', subject)
self.assertEquals("\n\nYour UW Oshkosh Office of International Education study abroad application has been updated.\n\nName: John Doe\nProgram Name: test\nProgram Year: 2009\n\nTransition\n\n\n\nYou can view your application here: http://nohost/plone/testapplication\n\nComment: \n\n\n", message)
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
suite.addTest(makeSuite(TestTransitionApproveForFA))
return suite
if __name__ == '__main__':
framework()
|
gpl-2.0
| 7,559,430,899,610,069,000
| 41.676768
| 304
| 0.68213
| false
| 3.648532
| true
| false
| false
|
dpshelio/sunpy
|
sunpy/util/net.py
|
2
|
6983
|
"""
This module provides general net utility functions.
"""
import os
import re
import sys
import shutil
from unicodedata import normalize
from email.parser import FeedParser
from urllib.parse import urljoin, urlparse
from urllib.request import urlopen
from sunpy.util import replacement_filename
__all__ = ['slugify', 'get_content_disposition', 'get_filename', 'get_system_filename',
'download_file', 'download_fileobj', 'check_download_file']
# Characters not allowed in slugified version.
_punct_re = re.compile(r'[:\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
def slugify(text, delim='_'):
"""
Slugify given unicode text.
Parameters
----------
text : `str`
A `str` to slugify.
delim : `str`, optional
The delimiter for the input ``text``. Default is "_".
Returns
-------
`str` :
The slugify `str` name.
"""
text = normalize('NFKD', text)
period = '.'
name_and_extension = text.rsplit(period, 1)
name = name_and_extension[0]
name = str(delim).join(
filter(None, (word for word in _punct_re.split(name.lower()))))
if len(name_and_extension) == 2:
extension = name_and_extension[1]
return str(period).join([name, extension])
else:
return name
def get_content_disposition(content_disposition):
"""
Get the content disposition filename from given header.
**Do not include "Content-Disposition:".**
Parameters
----------
content_disposition : `str`
The content disposition header.
Returns
-------
`str` :
The content disposition filename.
"""
parser = FeedParser()
parser.feed('Content-Disposition: ' + content_disposition)
name = parser.close().get_filename()
if name and not isinstance(name, str):
name = name.decode('latin1', 'ignore')
return name
def get_filename(sock, url):
"""
Get filename from given `~urllib.request.urlopen` object and URL.
First, tries the "Content-Disposition", if unavailable, extracts name from the URL.
Parameters
----------
sock : `~urllib.request.urlopen`
The `~urllib.request.urlopen` to parse for the filename.
url : `str`
The URL to parse for the filename.
Returns
-------
`str`:
The filename.
"""
name = None
cd = sock.headers.get('Content-Disposition', None)
if cd is not None:
try:
name = get_content_disposition(cd)
except IndexError:
pass
if not name:
parsed = urlparse(url)
name = parsed.path.rstrip('/').rsplit('/', 1)[-1]
return str(name)
def get_system_filename(sock, url, default="file"):
"""
Get filename from given `~urllib.request.urlopen` object and URL.
First, tries the "Content-Disposition", if unavailable, extracts name from the URL.
If this fails, the ``default`` keyword will be used.
Parameters
----------
sock : `~urllib.request.urlopen`
The `~urllib.request.urlopen` to parse for the filename.
url : `str`
The URL to parse for the filename.
default : `str`, optional
The name to use if the first two methods fail. Defaults to "file".
Returns
-------
`bytes`:
The filename in file system encoding.
"""
name = get_filename(sock, url)
if not name:
name = str(default)
return name.encode(sys.getfilesystemencoding(), 'ignore')
def download_fileobj(opn, directory, url='', default="file", overwrite=False):
"""
Download a file from a url into a directory.
Tries the "Content-Disposition", if unavailable, extracts name from the URL.
If this fails, the ``default`` keyword will be used.
Parameters
----------
opn : `~urllib.request.urlopen`
The `~urllib.request.urlopen` to download.
directory : `str`
The directory path to download the file in to.
url : `str`
The URL to parse for the filename.
default : `str`, optional
The name to use if the first two methods fail. Defaults to "file".
overwrite: `bool`, optional
If `True` will overwrite a file of the same name. Defaults to `False`.
Returns
-------
`str`:
The file path for the downloaded file.
"""
filename = get_system_filename(opn, url, default)
path = os.path.join(directory, filename.decode('utf-8'))
if overwrite and os.path.exists(path):
path = replacement_filename(path)
with open(path, 'wb') as fd:
shutil.copyfileobj(opn, fd)
return path
def download_file(url, directory, default="file", overwrite=False):
"""
Download a file from a url into a directory.
Tries the "Content-Disposition", if unavailable, extracts name from the URL.
If this fails, the ``default`` keyword will be used.
Parameters
----------
url : `str`
The file URL download.
directory : `str`
The directory path to download the file in to.
default : `str`, optional
The name to use if the first two methods fail. Defaults to "file".
overwrite: `bool`, optional
If `True` will overwrite a file of the same name. Defaults to `False`.
Returns
-------
`str`:
The file path for the downloaded file.
"""
opn = urlopen(url)
try:
path = download_fileobj(opn, directory, url, default, overwrite)
finally:
opn.close()
return path
def check_download_file(filename, remotepath, download_dir, remotename=None, replace=False):
"""
Downloads a file from a remotepath to a localpath if it isn't there.
This function checks whether a file with name ``filename`` exists in the user's local machine.
If it doesn't, it downloads the file from ``remotepath``.
Parameters
----------
filename : `str`
Name of file.
remotepath : `str`
URL of the remote location from which filename can be downloaded.
download_dir : `str`
The files directory.
remotename : `str`, optional
Filename under which the file is stored remotely.
Default is same as filename.
replace : `bool`, optional
If `True`, file will be downloaded whether or not file already exists locally.
Examples
--------
>>> from sunpy.util.net import check_download_file
>>> remotepath = "https://www.download_repository.com/downloads/"
>>> check_download_file("filename.txt", remotepath, download_dir='.') # doctest: +SKIP
"""
# Check if file already exists locally. If not, try downloading it.
if replace or not os.path.isfile(os.path.join(download_dir, filename)):
# set local and remote file names be the same unless specified
# by user.
if not isinstance(remotename, str):
remotename = filename
download_file(urljoin(remotepath, remotename),
download_dir, default=filename, overwrite=replace)
|
bsd-2-clause
| 134,006,119,759,047,330
| 28.340336
| 98
| 0.622798
| false
| 4.117335
| false
| false
| false
|
msherry/PyXB-1.1.4
|
tests/bugs/test-200908271556.py
|
1
|
1990
|
import pyxb_114.binding.generate
import pyxb_114.binding.datatypes as xs
import pyxb_114.binding.basis
import pyxb_114.utils.domutils
import gc
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="instance">
<xs:complexType>
<xs:all>
<xs:element name="inner" maxOccurs="unbounded">
<xs:complexType>
<xs:all>
<xs:element name="text" type="xs:string"/>
<xs:element name="number" type="xs:integer"/>
</xs:all>
</xs:complexType>
</xs:element>
</xs:all>
</xs:complexType>
</xs:element>
</xs:schema>
'''
#file('schema.xsd', 'w').write(xsd)
code = pyxb_114.binding.generate.GeneratePython(schema_text=xsd)
#file('code.py', 'w').write(code)
#print code
rv = compile(code, 'test', 'exec')
eval(rv)
from pyxb_114.exceptions_ import *
import unittest
import os
class TestBug_200908271556(unittest.TestCase):
# No, this isn't portable. No, I don't care.
__statm = file('/proc/%d/statm' % (os.getpid(),))
def __getMem (self):
self.__statm.seek(0)
return int(self.__statm.read().split()[0])
def testMemory (self):
xmls = '<instance><inner><text>text</text><number>45</number></inner></instance>'
base_at = 10
check_at = 20
growth_limit = 1.10
iter = 0
gc.collect()
while True:
iter += 1
if base_at == iter:
gc.collect()
base_mem = self.__getMem()
elif check_at == iter:
gc.collect()
check_mem = self.__getMem()
growth = check_mem - base_mem
self.assertTrue(0 == growth, 'growth %s' % (growth,))
break
instance = CreateFromDocument(xmls)
xmls = instance.toxml("utf-8", root_only=True)
if __name__ == '__main__':
unittest.main()
|
apache-2.0
| 223,691,252,362,142,340
| 27.028169
| 89
| 0.554271
| false
| 3.390119
| true
| false
| false
|
deuscoin-org/deuscoin-core
|
qa/rpc-tests/test_framework/authproxy.py
|
1
|
6097
|
"""
Copyright 2011 Jeff Garzik
AuthServiceProxy has the following improvements over python-jsonrpc's
ServiceProxy class:
- HTTP connections persist for the life of the AuthServiceProxy object
(if server supports HTTP/1.1)
- sends protocol 'version', per JSON-RPC 1.1
- sends proper, incrementing 'id'
- sends Basic HTTP authentication headers
- parses all JSON numbers that look like floats as Decimal
- uses standard Python json lib
Previous copyright, from python-jsonrpc/jsonrpc/proxy.py:
Copyright (c) 2007 Jan-Klaas Kollhof
This file is part of jsonrpc.
jsonrpc 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 of the License, or
(at your option) any later version.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this software; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
try:
import http.client as httplib
except ImportError:
import httplib
import base64
import decimal
import json
import logging
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
USER_AGENT = "AuthServiceProxy/0.1"
HTTP_TIMEOUT = 30
log = logging.getLogger("DeuscoinRPC")
class JSONRPCException(Exception):
def __init__(self, rpc_error):
Exception.__init__(self)
self.error = rpc_error
def EncodeDecimal(o):
if isinstance(o, decimal.Decimal):
return round(o, 8)
raise TypeError(repr(o) + " is not JSON serializable")
class AuthServiceProxy(object):
__id_count = 0
def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None):
self.__service_url = service_url
self._service_name = service_name
self.__url = urlparse.urlparse(service_url)
if self.__url.port is None:
port = 80
else:
port = self.__url.port
(user, passwd) = (self.__url.username, self.__url.password)
try:
user = user.encode('utf8')
except AttributeError:
pass
try:
passwd = passwd.encode('utf8')
except AttributeError:
pass
authpair = user + b':' + passwd
self.__auth_header = b'Basic ' + base64.b64encode(authpair)
if connection:
# Callables re-use the connection of the original proxy
self.__conn = connection
elif self.__url.scheme == 'https':
self.__conn = httplib.HTTPSConnection(self.__url.hostname, port,
None, None, False,
timeout)
else:
self.__conn = httplib.HTTPConnection(self.__url.hostname, port,
False, timeout)
def __getattr__(self, name):
if name.startswith('__') and name.endswith('__'):
# Python internal stuff
raise AttributeError
if self._service_name is not None:
name = "%s.%s" % (self._service_name, name)
return AuthServiceProxy(self.__service_url, name, connection=self.__conn)
def _request(self, method, path, postdata):
'''
Do a HTTP request, with retry if we get disconnected (e.g. due to a timeout).
This is a workaround for https://bugs.python.org/issue3566 which is fixed in Python 3.5.
'''
headers = {'Host': self.__url.hostname,
'User-Agent': USER_AGENT,
'Authorization': self.__auth_header,
'Content-type': 'application/json'}
try:
self.__conn.request(method, path, postdata, headers)
return self._get_response()
except httplib.BadStatusLine as e:
if e.line == "''": # if connection was closed, try again
self.__conn.close()
self.__conn.request(method, path, postdata, headers)
return self._get_response()
else:
raise
def __call__(self, *args):
AuthServiceProxy.__id_count += 1
log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self._service_name,
json.dumps(args, default=EncodeDecimal)))
postdata = json.dumps({'version': '1.1',
'method': self._service_name,
'params': args,
'id': AuthServiceProxy.__id_count}, default=EncodeDecimal)
response = self._request('POST', self.__url.path, postdata)
if response['error'] is not None:
raise JSONRPCException(response['error'])
elif 'result' not in response:
raise JSONRPCException({
'code': -343, 'message': 'missing JSON-RPC result'})
else:
return response['result']
def _batch(self, rpc_call_list):
postdata = json.dumps(list(rpc_call_list), default=EncodeDecimal)
log.debug("--> "+postdata)
return self._request('POST', self.__url.path, postdata)
def _get_response(self):
http_response = self.__conn.getresponse()
if http_response is None:
raise JSONRPCException({
'code': -342, 'message': 'missing HTTP response from server'})
responsedata = http_response.read().decode('utf8')
response = json.loads(responsedata, parse_float=decimal.Decimal)
if "error" in response and response["error"] is None:
log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal)))
else:
log.debug("<-- "+responsedata)
return response
|
mit
| -2,653,445,764,162,595,300
| 36.176829
| 105
| 0.599803
| false
| 4.345688
| false
| false
| false
|
JasonLai256/plumbca
|
plumbca/cache.py
|
1
|
2429
|
# -*- coding:utf-8 -*-
"""
plumbca.cache
~~~~~~~~~~~~~
CacheHandler for the collections control.
:copyright: (c) 2015 by Jason Lai.
:license: BSD, see LICENSE for more details.
"""
import asyncio
import logging
import re
import os
from .config import DefaultConf
from .collection import IncreaseCollection
from .backend import BackendFactory
actlog = logging.getLogger('activity')
err_logger = logging.getLogger('errors')
class CacheCtl(object):
def __init__(self):
self.collmap = {}
self.info = {}
self.bk = BackendFactory(DefaultConf['backend'])
loop = asyncio.get_event_loop()
loop.run_until_complete(self.bk.init_connection())
def get_collection(self, name):
if name not in self.collmap:
actlog.info("Collection %s not exists.", name)
return
return self.collmap[name]
async def ensure_collection(self, name, ctype, expire, **kwargs):
rv = await self.bk.get_collection_index(name)
if name not in self.collmap and not rv:
actlog.info("Ensure collection - not exists in plumbca and redis")
self.collmap[name] = globals()[ctype](name, expire=expire, **kwargs)
await self.bk.set_collection_index(name, self.collmap[name])
actlog.info("Ensure collection - not exists in plumbca and redis, "
"create it, `%s`.", self.collmap[name])
elif name not in self.collmap and rv:
actlog.info("Ensure collection - not exists in plumbca")
rv_name, rv_instance_name = rv
assert name == rv_name
assert rv_instance_name == globals()[ctype].__class__.__name__
self.collmap[name] = globals()[ctype](name, expire=expire, **kwargs)
actlog.info("Ensure collection - not exists in plumbca, "
"create it, `%s`.", self.collmap[name])
elif name in self.collmap and not rv:
actlog.info("Ensure collection - not exists in redis")
await self.bk.set_collection_index(name, self.collmap[name])
actlog.info("Ensure collection - not exists in redis, "
"create it, `%s`.", self.collmap[name])
else:
actlog.info("Ensure collection already exists, `%s`.",
self.collmap[name])
def info(self):
pass
CacheCtl = CacheCtl()
|
bsd-3-clause
| -7,146,317,080,230,869,000
| 31.386667
| 80
| 0.599012
| false
| 3.968954
| false
| false
| false
|
sdrogers/lda
|
code/lda_utilities.py
|
1
|
14058
|
import numpy as np
import pickle
import jsonpickle
def match_topics_across_dictionaries(lda1 = None,lda2 = None,file1 = None,file2 = None,
same_corpus = True,copy_annotations = False,copy_threshold = 0.5,summary_file = None,
new_file2 = None,mass_tol = 5.0):
# finds the closest topic matches from lda2 to lda1
if lda1 == None:
if file1 == None:
print "Must specify either an lda dictionary object or a dictionary file for lda1"
return
else:
with open(file1,'r') as f:
lda1 = pickle.load(f)
print "Loaded lda1 from {}".format(file1)
if lda2 == None:
if file2 == None:
print "Must specify either an lda dictionary object or a dictionary file for lda1"
return
else:
with open(file2,'r') as f:
lda2 = pickle.load(f)
print "Loaded lda2 from {}".format(file2)
word_index = lda1['word_index']
n_words = len(word_index)
n_topics1 = lda1['K']
n_topics2 = lda2['K']
# Put lda1's topics into a nice matrix
beta = np.zeros((n_topics1,n_words),np.float)
topic_pos = 0
topic_index1 = {}
for topic in lda1['beta']:
topic_index1[topic] = topic_pos
for word in lda1['beta'][topic]:
word_pos = word_index[word]
beta[topic_pos,word_pos] = lda1['beta'][topic][word]
topic_pos += 1
# Make the reverse index
ti = [(topic,topic_index1[topic]) for topic in topic_index1]
ti = sorted(ti,key = lambda x: x[1])
reverse1,_ = zip(*ti)
if not same_corpus:
fragment_masses = np.array([float(f.split('_')[1]) for f in word_index if f.startswith('fragment')])
fragment_names = [f for f in word_index if f.startswith('fragment')]
loss_masses = np.array([float(f.split('_')[1]) for f in word_index if f.startswith('loss')])
loss_names = [f for f in word_index if f.startswith('loss')]
beta /= beta.sum(axis=1)[:,None]
best_match = {}
temp_topics2 = {}
for topic2 in lda2['beta']:
temp_topics2[topic2] = {}
temp_beta = np.zeros((1,n_words))
if same_corpus:
total_probability = 0.0
for word in lda2['beta'][topic2]:
word_pos = word_index[word]
temp_beta[0,word_pos] = lda2['beta'][topic2][word]
temp_topics2[topic2][word] = lda2['beta'][topic2][word]
total_probability += temp_topics2[topic2][word]
for word in temp_topics2[topic2]:
temp_topics2[topic2][word] /= total_probability
temp_beta /= temp_beta.sum(axis=1)[:,None]
else:
# we need to match across corpus
total_probability = 0.0
for word in lda2['beta'][topic2]:
# try and match to a word in word_index
split_word = word.split('_')
word_mass = float(split_word[1])
if split_word[0].startswith('fragment'):
ppm_errors = 1e6*np.abs((fragment_masses - word_mass)/fragment_masses)
smallest_pos = ppm_errors.argmin()
if ppm_errors[smallest_pos] < mass_tol:
word1 = fragment_names[smallest_pos]
temp_topics2[topic2][word1] = lda2['beta'][topic2][word]
temp_beta[0,word_index[word1]] = lda2['beta'][topic2][word]
if split_word[0].startswith('loss'):
ppm_errors = 1e6*np.abs((loss_masses - word_mass)/loss_masses)
smallest_pos = ppm_errors.argmin()
if ppm_errors[smallest_pos] < 2*mass_tol:
word1 = loss_names[smallest_pos]
temp_topics2[topic2][word1] = lda2['beta'][topic2][word]
temp_beta[0,word_index[word1]] = lda2['beta'][topic2][word]
total_probability += lda2['beta'][topic2][word]
for word in temp_topics2[topic2]:
temp_topics2[topic2][word] /= total_probability
temp_beta /= total_probability
match_scores = np.dot(beta,temp_beta.T)
best_score = match_scores.max()
best_pos = match_scores.argmax()
topic1 = reverse1[best_pos]
w1 = lda1['beta'][topic1].keys()
if same_corpus:
w2 = lda2['beta'][topic2].keys()
else:
w2 = temp_topics2[topic2].keys()
union = set(w1) | set(w2)
intersect = set(w1) & set(w2)
p1 = 0.0
p2 = 0.0
for word in intersect:
word_pos = word_index[word]
p1 += beta[topic_index1[topic1],word_pos]
p2 += temp_topics2[topic2][word]
annotation = ""
if 'topic_metadata' in lda1:
if topic1 in lda1['topic_metadata']:
if type(lda1['topic_metadata'][topic1]) == str:
annotation = lda1['topic_metadata'][topic1]
else:
annotation = lda1['topic_metadata'][topic1].get('annotation',"")
best_match[topic2] = (topic1,best_score,len(union),len(intersect),p2,p1,annotation)
if summary_file:
with open(summary_file,'w') as f:
f.write('lda2_topic,lda1_topic,match_score,unique_words,shared_words,shared_p_lda2,shared_p_lda1,lda1_annotation\n')
for topic2 in best_match:
topic1 = best_match[topic2][0]
line = "{},{},{}".format(topic2,topic1,best_match[topic2][1])
line += ",{},{}".format(best_match[topic2][2],best_match[topic2][3])
line += ",{},{}".format(best_match[topic2][4],best_match[topic2][5])
line += ",{}".format(best_match[topic2][6])
f.write(line+'\n')
if copy_annotations and 'topic_metadata' in lda1:
print "Copying annotations"
if not 'topic_metadata' in lda2:
lda2['topic_metadata'] = {}
for topic2 in best_match:
lda2['topic_metadata'][topic2] = {'name':topic2}
topic1 = best_match[topic2][0]
p2 = best_match[topic2][4]
p1 = best_match[topic2][5]
if p1 >= copy_threshold and p2 >= copy_threshold:
annotation = best_match[topic2][6]
if len(annotation) > 0:
lda2['topic_metadata'][topic2]['annotation'] = annotation
if new_file2 == None:
with open(file2,'w') as f:
pickle.dump(lda2,f)
print "Dictionary with copied annotations saved to {}".format(file2)
else:
with open(new_file2,'w') as f:
pickle.dump(lda2,f)
print "Dictionary with copied annotations saved to {}".format(new_file2)
return best_match,lda2
def find_standards_in_dict(standards_file,lda_dict=None,lda_dict_file=None,mode='pos',mass_tol = 3,rt_tol = 12,new_lda_file = None):
if lda_dict == None:
if lda_dict_file == None:
print "Must provide either an lda dictionary or an lda dictionary file"
return
else:
with open(lda_dict_file,'r') as f:
lda_dict = pickle.load(f)
print "Loaded lda dictionary from {}".format(lda_dict_file)
# Load the standards
standard_molecules = []
found_heads = False
with open(standards_file,'r') as f:
for line in f:
if found_heads == False and line.startswith('Peak Num'):
found_heads = True
continue
elif found_heads == False:
continue
else:
split_line = line.rstrip().split(',')
if (mode == 'pos' and split_line[4] == '+') or (mode == 'neg' and split_line[3] == '-'):
# It's a keeper
name = split_line[2]
mz = split_line[6]
if mz == 'N':
continue
mz = float(mz)
rt = split_line[9]
if rt == '-':
continue
rt = float(rt)*60.0 # converted to seconds
formula = split_line[3]
standard_molecules.append((name,mz,rt,formula))
# mol = ()
print "Loaded {} molecules".format(len(standard_molecules))
doc_masses = np.array([float(d.split('_')[0]) for d in lda_dict['corpus']])
doc_names = [d for d in lda_dict['corpus']]
doc_rt = np.array([float(d.split('_')[1]) for d in lda_dict['corpus']])
hits = {}
for mol in standard_molecules:
mass_delta = mol[1]*mass_tol*1e-6
mass_hit = (doc_masses < mol[1] + mass_delta) & (doc_masses > mol[1] - mass_delta)
rt_hit = (doc_rt < mol[2] + rt_tol) & (doc_rt > mol[2] - rt_tol)
match = np.where(mass_hit & rt_hit)[0]
if len(match) > 0:
if len(match) == 1:
hits[mol] = doc_names[match[0]]
else:
# Multiple hits
min_dist = 1e6
best_match = match[0]
for individual_match in match:
match_mass = doc_masses[individual_match]
match_rt = doc_rt[individual_match]
dist = np.sqrt((match_rt - mol[2])**2 + (match_mass - mol[1])**2)
if dist < min_dist:
best_match = individual_match
hits[mol] = doc_names[best_match]
print "Found hits for {} standard molecules".format(len(hits))
# Add the hits to the lda_dict as document metadata
for mol in hits:
doc_name = hits[mol]
lda_dict['doc_metadata'][doc_name]['standard_mol'] = mol[0]
lda_dict['doc_metadata'][doc_name]['annotation'] = mol[0]
if new_lda_file:
with open(new_lda_file,'w') as f:
pickle.dump(lda_dict,f)
print "Wrote annotated dictionary to {}".format(new_lda_file)
return lda_dict
def alpha_report(vlda,overlap_scores = None,overlap_thresh = 0.3):
ta = []
for topic,ti in vlda.topic_index.items():
ta.append((topic,vlda.alpha[ti]))
ta = sorted(ta,key = lambda x: x[1],reverse = True)
for t,a in ta:
to = []
if overlap_scores:
for doc in overlap_scores:
if t in overlap_scores[doc]:
if overlap_scores[doc][t]>=overlap_thresh:
to.append((doc,overlap_scores[doc][t]))
print t,vlda.topic_metadata[t].get('SHORT_ANNOTATION',None),a
to = sorted(to,key = lambda x: x[1],reverse = True)
for t,o in to:
print '\t',t,o
def decompose(vlda,corpus):
# decompose the documents in corpus
# CHECK THE INTENSITY NORMALISATION
K = vlda.K
phi = {}
gamma_mat = {}
n_done = 0
n_total = len(corpus)
p_in = {}
for doc,spectrum in corpus.items():
intensity_in = 0.0
intensity_out = 0.0
max_i = 0.0
for word in spectrum:
if spectrum[word] > max_i:
max_i = spectrum[word]
if word in vlda.word_index:
intensity_in += spectrum[word]
else:
intensity_out += spectrum[word]
p_in[doc] = (1.0*intensity_in)/(intensity_in + intensity_out)
# print max_i
print "Decomposing document {} ({}/{})".format(doc,n_done,n_total)
phi[doc] = {}
# gamma_mat[doc] = np.zeros(K) + vlda.alpha
gamma_mat[doc] = np.ones(K)
for it in range(20):
# temp_gamma = np.zeros(K) + vlda.alpha
temp_gamma = np.ones(K)
for word in spectrum:
if word in vlda.word_index:
w = vlda.word_index[word]
log_phi_matrix = np.log(vlda.beta_matrix[:,w]) + psi(gamma_mat[doc])
log_phi_matrix = np.exp(log_phi_matrix - log_phi_matrix.max())
phi[doc][word] = log_phi_matrix/log_phi_matrix.sum()
temp_gamma += phi[doc][word]*spectrum[word]
gamma_mat[doc] = temp_gamma
n_done += 1
return gamma_mat,phi,p_in
def decompose_overlap(vlda,decomp_phi):
# computes the overlap score for a decomposition phi
o = {}
K = vlda.K
for doc in decomp_phi:
o[doc] = {}
os = np.zeros(K)
for word,phi_vec in decomp_phi[doc].items():
word_pos = vlda.word_index[word]
os += phi_vec*vlda.beta_matrix[:,word_pos]
for topic,pos in vlda.topic_index.items():
o[doc][topic] = os[pos]
return o
def decompose_from_dict(vlda_dict,corpus):
# step 1, get the betas into a matrix
K = vlda_dict['K']
skeleton = VariationalLDA({},K)
skeleton.word_index = vlda_dict['word_index']
skeleton.topic_index = vlda_dict['topic_index']
n_words = len(skeleton.word_index)
skeleton.beta_matrix = np.zeros((K,n_words),np.double) + 1e-6
beta_dict = vlda_dict['beta']
for topic in beta_dict:
topic_pos = skeleton.topic_index[topic]
for word,prob in beta_dict[topic].items():
word_pos = skeleton.word_index[word]
skeleton.beta_matrix[topic_pos,word_pos] = prob
# normalise
skeleton.beta_matrix /= skeleton.beta_matrix.sum(axis=1)[:,None]
g,phi,p_in = decompose(skeleton,corpus)
return g,phi,p_in,skeleton
def doc_feature_counts(vlda_dict,p_thresh = 0.01,o_thresh = 0.3):
theta = vlda_dict['theta']
decomp_gamma,decomp_phi,decomp_p_in,skeleton = decompose_from_dict(vlda_dict,vlda_dict['corpus'])
overlap_scores = decompose_overlap(skeleton,vlda_dict['corpus'])
phi_thresh = 0.5
motif_doc_counts = {}
motif_word_counts = {}
for doc in theta:
for motif in theta[doc]:
if theta[doc][motif] >= p_thresh and overlap_scores[doc][motif] >= o_thresh:
if not motif in motif_doc_counts:
motif_doc_counts[motif] = 0
motif_doc_counts[motif] += 1
for word,phi_vec in decomp_phi[doc].items():
motif_pos = vlda_dict['topic_index'][motif]
if phi_vec[motif_pos] >= phi_thresh:
if not motif in motif_word_counts:
motif_word_counts[motif] = {}
if not word in motif_word_counts[motif]:
motif_word_counts[motif][word] = 0
motif_word_counts[motif][word] += 1
word_total_counts = {}
for doc,spectrum in vlda_dict['corpus'].items():
for word,intensity in spectrum.items():
if not word in word_total_counts:
word_total_counts[word] = 0
word_total_counts[word] += 1
return motif_doc_counts,motif_word_counts,word_total_counts
def compute_overlap_scores(vlda):
import numpy as np
K = len(vlda.topic_index)
overlap_scores = {}
for doc in vlda.doc_index:
overlap_scores[doc] = {}
os = np.zeros(K)
pm = vlda.phi_matrix[doc]
for word,probs in pm.items():
word_index = vlda.word_index[word]
os += probs*vlda.beta_matrix[:,word_index]
for motif,m_pos in vlda.topic_index.items():
overlap_scores[doc][motif] = os[m_pos]
return overlap_scores
def write_csv(vlda,overlap_scores,filename,metadata,p_thresh=0.01,o_thresh=0.3):
import csv
probs = vlda.get_expect_theta()
motif_dict = {}
with open(filename,'w') as f:
writer = csv.writer(f)
heads = ['Document','Motif','Probability','Overlap Score','Precursor Mass','Retention Time','Document Annotation']
writer.writerow(heads)
all_rows = []
for doc,doc_pos in vlda.doc_index.items():
for motif,motif_pos in vlda.topic_index.items():
if probs[doc_pos,motif_pos] >= p_thresh and overlap_scores[doc][motif] >= o_thresh:
new_row = []
new_row.append(doc)
new_row.append(motif)
new_row.append(probs[doc_pos,motif_pos])
new_row.append(overlap_scores[doc][motif])
new_row.append(metadata[doc]['parentmass'])
new_row.append("None")
new_row.append(metadata[doc]['featid'])
all_rows.append(new_row)
motif_dict[motif] = True
all_rows = sorted(all_rows,key = lambda x:x[0])
for new_row in all_rows:
writer.writerow(new_row)
return motif_dict
|
gpl-3.0
| 7,522,224,093,427,851,000
| 33.374083
| 132
| 0.636862
| false
| 2.75431
| false
| false
| false
|
our-city-app/oca-backend
|
src/rogerthat/models/auth/acm.py
|
1
|
2211
|
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.7@@
from rogerthat.models.common import NdbModel
from google.appengine.ext import ndb
# DOCS https://authenticatie.vlaanderen.be/docs/beveiligen-van-toepassingen/integratie-methoden/oidc/
# T&I https://authenticatie-ti.vlaanderen.be/op/.well-known/openid-configuration
# PROD https://authenticatie.vlaanderen.be/op/.well-known/openid-configuration
class ACMSettings(NdbModel):
client_id = ndb.TextProperty()
client_secret = ndb.TextProperty()
openid_config_uri = ndb.TextProperty()
auth_redirect_uri = ndb.TextProperty()
logout_redirect_uri = ndb.TextProperty()
@classmethod
def create_key(cls, app_id):
return ndb.Key(cls, app_id)
class ACMLoginState(NdbModel):
creation_time = ndb.DateTimeProperty(auto_now_add=True)
app_id = ndb.TextProperty()
scope = ndb.TextProperty()
code_challenge = ndb.TextProperty()
token = ndb.JsonProperty()
id_token = ndb.JsonProperty()
@property
def state(self):
return self.key.id()
@classmethod
def create_key(cls, state):
return ndb.Key(cls, state)
@classmethod
def list_before_date(cls, date):
return cls.query(cls.creation_time < date)
class ACMLogoutState(NdbModel):
creation_time = ndb.DateTimeProperty(auto_now_add=True)
app_id = ndb.TextProperty()
@property
def state(self):
return self.key.id()
@classmethod
def create_key(cls, state):
return ndb.Key(cls, state)
@classmethod
def list_before_date(cls, date):
return cls.query(cls.creation_time < date)
|
apache-2.0
| 6,988,458,327,065,646,000
| 28.891892
| 101
| 0.703754
| false
| 3.438569
| false
| false
| false
|
cartertech/odoo-hr-ng
|
hr_report_payroll_attendance_summary/report/attendance_summary.py
|
1
|
14914
|
#-*- coding:utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 One Click Software (http://oneclick.solutions)
# and Copyright (C) 2013 Michael Telahun Makonnen <mmakonnen@gmail.com>.
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR 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.org/licenses/>.
#
##############################################################################
from datetime import datetime
from dateutil.relativedelta import relativedelta
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT as OE_DATEFORMAT
from report import report_sxw
class Parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(Parser, self).__init__(cr, uid, name, context)
self.localcontext.update({
'get_employee_data': self.get_employee_data,
'get_worked_days': self.get_worked_days,
'get_daily_ot': self.get_daily_ot,
'get_nightly_ot': self.get_nightly_ot,
'get_restday_ot': self.get_restday_ot,
'get_holiday_ot': self.get_holiday_ot,
'get_bunch_no': self.get_bunch_no,
'get_awol': self.get_awol,
'get_sickleave': self.get_sickleave,
'get_no': self.get_no,
'get_start': self.get_start,
'get_end': self.get_end,
'lose_bonus': self.lose_bonus,
'get_paid_leave': self.get_paid_leave,
'get_employee_list': self.get_employee_list,
'get_lu': self.get_lu,
'get_wage': self.get_adjusted_wage,
})
self.start_date = False
self.end_date = False
self.ee_lines = {}
self.no = 0
self.department_id = False
self.regular_hours = 8.0
self.get_employee_data_ids = []
self.get_employee_list_ids = []
def set_context(self, objects, data, ids, report_type=None):
if data.get('form', False) and data['form'].get('start_date', False):
self.start_date = data['form']['start_date']
if data.get('form', False) and data['form'].get('end_date', False):
self.end_date = data['form']['end_date']
return super(Parser, self).set_context(objects, data, ids, report_type=report_type)
def calculate_wage_by_ppf(self, dFullStart, dFullEnd, contracts_list):
full_days = 0
d = dFullStart
while d <= dFullEnd:
full_days += 1
d += relativedelta(days= +1)
wage = 0.0
for line in contracts_list:
ppf = 0.0
dates = line[0]
contract_wage = line[1]
ppf = float(relativedelta(dates[1], dates[0]).days + 1) / float(full_days)
wage += (contract_wage * ppf)
return wage
def get_adjusted_wage(self, ee_id):
con_obj = self.pool.get('hr.contract')
dS = datetime.strptime(self.start_date, OE_DATEFORMAT).date()
dE = datetime.strptime(self.end_date, OE_DATEFORMAT).date()
wage = 0
# Get contract in effect on first day of period (or first contract date for new employees)
cons= []
d = dS
while d <= dE:
con_ids = con_obj.search(self.cr, self.uid,
[('employee_id', '=', ee_id),
('date_start', '<=', d.strftime(OE_DATEFORMAT)),
'|', ('date_end', '=', False),
('date_end', '>=', d.strftime(OE_DATEFORMAT))])
if len(con_ids) > 0:
con = con_obj.browse(self.cr, self.uid, con_ids[0])
_seen = False
for c in cons:
if con.id == c[2]:
_seen = True
break
if _seen:
d += relativedelta(days= +1)
continue
dTempStart = dS
dTempEnd = dE
dConStart = datetime.strptime(con.date_start, OE_DATEFORMAT).date()
if dConStart > dS:
dTempStart = dConStart
if con.date_end:
dConEnd = datetime.strptime(con.date_end, OE_DATEFORMAT).date()
if dConEnd < dE:
dTempEnd = dConEnd
cons.append([(dTempStart, dTempEnd), con.wage, con.id])
d += relativedelta(days= +1)
if len(cons) > 0:
wage = self.calculate_wage_by_ppf(dS, dE, cons)
return wage
def get_employee_ids(self, department_id, seen_ids):
c_obj = self.pool.get('hr.contract')
ee_obj = self.pool.get('hr.employee')
c_ids = c_obj.search(self.cr, self.uid, ['|', ('job_id.department_id', '=', department_id),
('end_job_id.department_id', '=', department_id),
('date_start', '<=', self.end_date),
'|', ('date_end', '=', False),
('date_end', '>=', self.start_date)])
ee_ids = []
cdata = c_obj.read(self.cr, self.uid, c_ids, ['employee_id'])
ee_ids = [data['employee_id'][0] for data in cdata if ((data['employee_id'][0] not in ee_ids) and (data['employee_id'][0] not in seen_ids))]
seen_ids += ee_ids
# re-order
return ee_obj.search(self.cr, self.uid, [('id', 'in', ee_ids),
'|', ('active', '=', True),
('active', '=', False)])
def get_employee_list(self, department_id):
ee_ids = self.get_employee_ids(department_id, self.get_employee_list_ids)
return self.pool.get('hr.employee').browse(self.cr, self.uid, ee_ids)
def get_employee_data(self, department_id):
payslip_obj = self.pool.get('hr.payslip')
ee_obj = self.pool.get('hr.employee')
dtStart = datetime.strptime(self.start_date, OE_DATEFORMAT).date()
dtEnd = datetime.strptime(self.end_date, OE_DATEFORMAT).date()
ee_ids = self.get_employee_ids(department_id, self.get_employee_data_ids)
for ee in ee_obj.browse(self.cr, self.uid, ee_ids):
datas = []
for c in ee.contract_ids:
dtCStart = False
dtCEnd = False
if c.date_start: dtCStart = datetime.strptime(c.date_start, OE_DATEFORMAT).date()
if c.date_end: dtCEnd = datetime.strptime(c.date_end, OE_DATEFORMAT).date()
if (dtCStart and dtCStart <= dtEnd) and ((dtCEnd and dtCEnd >= dtStart) or not dtCEnd):
datas.append({'contract_id': c.id,
'date_start': dtCStart > dtStart and dtCStart.strftime(OE_DATEFORMAT) or dtStart.strftime(OE_DATEFORMAT),
'date_end': (dtCEnd and dtCEnd < dtEnd) and dtCEnd.strftime(OE_DATEFORMAT) or dtEnd.strftime(OE_DATEFORMAT)})
wd_lines = []
for d in datas:
wd_lines += payslip_obj.get_worked_day_lines(self.cr, self.uid, [d['contract_id']],
d['date_start'], d['date_end'])
self.ee_lines.update({ee.id: wd_lines})
def get_start(self):
return datetime.strptime(self.start_date, OE_DATEFORMAT).strftime('%B %d, %Y')
def get_end(self):
return datetime.strptime(self.end_date, OE_DATEFORMAT).strftime('%B %d, %Y')
def get_no(self, department_id):
if not self.department_id or self.department_id != department_id:
self.department_id = department_id
self.no = 1
else:
self.no += 1
return self.no
def get_lu(self, employee_id):
data = self.pool.get('hr.employee').read(self.cr, self.uid, employee_id, ['is_labour_union'])
return data.get('is_labour_union', False) and 'Y' or 'N'
def get_employee_start_date(self, employee_id):
first_day = False
c_obj = self.pool.get('hr.contract')
c_ids = c_obj.search(self.cr, self.uid, [('employee_id', '=', employee_id)])
for contract in c_obj.browse(self.cr, self.uid, c_ids):
if not first_day or contract.date_start < first_day:
first_day = contract.date_start
return first_day
def get_worked_days(self, employee_id):
total = 0.0
hol = 0.0
maxw = 0.0
for line in self.ee_lines[employee_id]:
if line['code'] in ['WORK100']:
total += float(line['number_of_hours']) / self.regular_hours
elif line['code'] == ['WORKHOL']:
hol += float(line['number_of_hours']) / self.regular_hours
elif line['code'] == ['MAX']:
maxw += float(line['number_of_hours']) / self.regular_hours
total += hol + self.get_paid_leave(employee_id)
awol = self.get_awol(employee_id)
# Take care to identify and handle employee's who didn't work the
# full month: newly hired and terminated employees
#
hire_date = self.get_employee_start_date(employee_id)
term_ids = self.pool.get('hr.employee.termination').search(self.cr, self.uid,
[('name', '<=', self.end_date),
('name', '>=', self.start_date),
('employee_id', '=', employee_id),
('employee_id.status', 'in', ['pending_inactive', 'inactive']),
('state', 'not in', ['cancel'])])
if hire_date <= self.start_date and len(term_ids) == 0:
if total >= maxw:
total = 26
total = total - awol
return total
def get_paid_leave(self, employee_id):
total = 0
paid_leaves = ['LVANNUAL', 'LVBEREAVEMENT', 'LVCIVIC', 'LVMATERNITY',
'LVMMEDICAL', 'LVPTO', 'LVWEDDING', 'LVSICK']
for line in self.ee_lines[employee_id]:
if line['code'] in paid_leaves:
total += float(line['number_of_hours']) / self.regular_hours
return total
def get_daily_ot(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['WORKOTD']:
total += line['number_of_hours']
return total
def get_nightly_ot(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['WORKOTN']:
total += line['number_of_hours']
return total
def get_restday_ot(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['WORKOTR', 'WORKRST']:
total += line['number_of_hours']
return total
def get_holiday_ot(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['WORKOTH', 'WORKHOL']:
total += line['number_of_hours']
return total
def get_bunch_no(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['BUNCH']:
total += int(line['number_of_hours'])
return total
def get_awol(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['AWOL']:
total += float(line['number_of_hours']) / self.regular_hours
return total
def get_sickleave(self, employee_id):
total = 0
for line in self.ee_lines[employee_id]:
if line['code'] in ['LVSICK']:
total += float(line['number_of_hours']) / self.regular_hours
elif line['code'] in ['LVSICK50']:
total += float(line['number_of_hours']) * 0.5
return total
def lose_bonus(self, employee_id):
loseit = False
for line in self.ee_lines[employee_id]:
if line['code'] in ['AWOL', 'TARDY', 'NFRA', 'WARNW'] and line['number_of_hours'] > 0.01:
loseit = True
# Check if the employee's contract spans the full month
if not loseit:
dStart = False
dEnd = None
con_obj = self.pool.get('hr.contract')
con_ids = con_obj.search(self.cr, self.uid, [('employee_id', '=', employee_id),
('state', '!=', 'draft'),
('date_start', '<=', self.end_date),
'|', ('date_end', '=', False),
('date_end', '>=', self.start_date)])
for con in con_obj.browse(self.cr, self.uid, con_ids):
dTempStart = datetime.strptime(con.date_start, OE_DATEFORMAT).date()
dTempEnd = False
if con.date_end:
dTempEnd = datetime.strptime(con.date_end, OE_DATEFORMAT).date()
if not dStart or dTempStart < dStart:
dStart = dTempStart
if (dEnd == None) or (not dTempEnd or (dEnd and dTempEnd > dEnd)):
dEnd = dTempEnd
if dStart and dStart > datetime.strptime(self.start_date, OE_DATEFORMAT).date():
loseit = True
elif (dEnd != None) and dEnd and (dEnd < datetime.strptime(self.end_date, OE_DATEFORMAT).date()):
loseit = True
return loseit
|
agpl-3.0
| -5,935,333,586,226,009,000
| 42.48105
| 148
| 0.495575
| false
| 3.907257
| false
| false
| false
|
adlius/osf.io
|
api/providers/urls.py
|
1
|
5275
|
from django.conf.urls import include, url
from api.providers import views
app_name = 'osf'
urlpatterns = [
url(
r'^preprints/', include(
(
[
url(r'^$', views.PreprintProviderList.as_view(), name=views.PreprintProviderList.view_name),
url(r'^(?P<provider_id>\w+)/$', views.PreprintProviderDetail.as_view(), name=views.PreprintProviderDetail.view_name),
url(r'^(?P<provider_id>\w+)/licenses/$', views.PreprintProviderLicenseList.as_view(), name=views.PreprintProviderLicenseList.view_name),
url(r'^(?P<provider_id>\w+)/preprints/$', views.PreprintProviderPreprintList.as_view(), name=views.PreprintProviderPreprintList.view_name),
url(r'^(?P<provider_id>\w+)/subjects/$', views.PreprintProviderSubjects.as_view(), name=views.PreprintProviderSubjects.view_name),
url(r'^(?P<provider_id>\w+)/subjects/highlighted/$', views.PreprintProviderHighlightedSubjectList.as_view(), name=views.PreprintProviderHighlightedSubjectList.view_name),
url(r'^(?P<provider_id>\w+)/taxonomies/$', views.PreprintProviderTaxonomies.as_view(), name=views.PreprintProviderTaxonomies.view_name),
url(r'^(?P<provider_id>\w+)/taxonomies/highlighted/$', views.PreprintProviderHighlightedTaxonomyList.as_view(), name=views.PreprintProviderHighlightedTaxonomyList.view_name),
url(r'^(?P<provider_id>\w+)/withdraw_requests/$', views.PreprintProviderWithdrawRequestList.as_view(), name=views.PreprintProviderWithdrawRequestList.view_name),
url(r'^(?P<provider_id>\w+)/moderators/$', views.PreprintProviderModeratorsList.as_view(), name=views.PreprintProviderModeratorsList.view_name),
url(r'^(?P<provider_id>\w+)/moderators/(?P<moderator_id>\w+)/$', views.PreprintProviderModeratorsDetail.as_view(), name=views.PreprintProviderModeratorsDetail.view_name),
], 'preprints',
),
namespace='preprint-providers',
),
),
url(
r'^collections/', include(
(
[
url(r'^$', views.CollectionProviderList.as_view(), name=views.CollectionProviderList.view_name),
url(r'^(?P<provider_id>\w+)/$', views.CollectionProviderDetail.as_view(), name=views.CollectionProviderDetail.view_name),
url(r'^(?P<provider_id>\w+)/licenses/$', views.CollectionProviderLicenseList.as_view(), name=views.CollectionProviderLicenseList.view_name),
url(r'^(?P<provider_id>\w+)/submissions/$', views.CollectionProviderSubmissionList.as_view(), name=views.CollectionProviderSubmissionList.view_name),
url(r'^(?P<provider_id>\w+)/subjects/$', views.CollectionProviderSubjects.as_view(), name=views.CollectionProviderSubjects.view_name),
url(r'^(?P<provider_id>\w+)/subjects/highlighted/$', views.CollectionProviderHighlightedSubjectList.as_view(), name=views.CollectionProviderHighlightedSubjectList.view_name),
url(r'^(?P<provider_id>\w+)/taxonomies/$', views.CollectionProviderTaxonomies.as_view(), name=views.CollectionProviderTaxonomies.view_name),
url(r'^(?P<provider_id>\w+)/taxonomies/highlighted/$', views.CollectionProviderHighlightedTaxonomyList.as_view(), name=views.CollectionProviderHighlightedTaxonomyList.view_name),
], 'collections',
),
namespace='collection-providers',
),
),
url(
r'^registrations/', include(
(
[
url(r'^$', views.RegistrationProviderList.as_view(), name=views.RegistrationProviderList.view_name),
url(r'^(?P<provider_id>\w+)/$', views.RegistrationProviderDetail.as_view(), name=views.RegistrationProviderDetail.view_name),
url(r'^(?P<provider_id>\w+)/licenses/$', views.RegistrationProviderLicenseList.as_view(), name=views.RegistrationProviderLicenseList.view_name),
url(r'^(?P<provider_id>\w+)/schemas/$', views.RegistrationProviderSchemaList.as_view(), name=views.RegistrationProviderSchemaList.view_name),
url(r'^(?P<provider_id>\w+)/submissions/$', views.RegistrationProviderSubmissionList.as_view(), name=views.RegistrationProviderSubmissionList.view_name),
url(r'^(?P<provider_id>\w+)/subjects/$', views.RegistrationProviderSubjects.as_view(), name=views.RegistrationProviderSubjects.view_name),
url(r'^(?P<provider_id>\w+)/subjects/highlighted/$', views.RegistrationProviderHighlightedSubjectList.as_view(), name=views.RegistrationProviderHighlightedSubjectList.view_name),
url(r'^(?P<provider_id>\w+)/taxonomies/$', views.RegistrationProviderTaxonomies.as_view(), name=views.RegistrationProviderTaxonomies.view_name),
url(r'^(?P<provider_id>\w+)/taxonomies/highlighted/$', views.RegistrationProviderHighlightedTaxonomyList.as_view(), name=views.RegistrationProviderHighlightedTaxonomyList.view_name),
], 'registrations',
),
namespace='registration-providers',
),
),
]
|
apache-2.0
| 7,185,396,797,768,840,000
| 80.153846
| 202
| 0.653649
| false
| 4.03596
| false
| true
| false
|
akraft196/pyASC
|
examples/mplot1.py
|
1
|
7267
|
#! /usr/bin/env python
#
# quick and dirty processing of the MD All Sky images
from astropy.io import fits
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from scipy.misc import imsave
import numpy as np
import aplpy
import argparse as ap
import os.path
import logging
import time
def d(ff,box=[]):
#very specific for 16 bit data, since we want to keep the data in uint16
h = fits.open(ff, do_not_scale_image_data=True)
if len(box)==0:
return h[0].header, h[0].data
else:
# figure out 0 vs. 1 based offsets; box is 1 based
return h[0].header, h[0].data[box[1]:box[3], box[0]:box[2]]
def dsum(i0,i1,step = 1, box=[]):
""" for a range of fits files
compute the mean and dispersion from the mean
"""
for i in range(i0,i1+1,step):
ff = 'IMG%05d.FIT' % i
h1, d1 = d(ff,box)
#very specific for 16 bit data, since we want to keep the data in uint16
bzero = h1['BZERO']
bscale = h1['BSCALE']
if i == i0:
sum0 = 1.0
sum1 = d1*bscale+bzero
sum2 = sum1*sum1
#sum1 = d1
#sum2 = d1*d1
h = h1
nx = d1.shape[1]
ny = d1.shape[0]
nz = i1 + 1 - i0
c = np.zeros((nz, ny, nx))
c[0,:,:] = d1.reshape(ny,nx)
else:
sum0 = sum0 + 1.0
sum1 = sum1 + (d1 * bscale + bzero)
sum2 = sum2 + (d1 * bscale + bzero) * (d1 * bscale + bzero)
#sum2 = sum2+d1*d1
c[i - i0,:,:] = d1.reshape(ny,nx)
sum1 = sum1 / sum0
sum2 = sum2 / sum0 - sum1*sum1
print type(sum1), type(sum2)
return h,sum1,np.sqrt(sum2),c
def show(sum):
""" some native matplotlib display,
doesn't show pointsources well at all
"""
ip = plt.imshow(sum)
plt.show()
def show2(sum):
""" aplpy is the better viewer clearly
"""
fig = aplpy.FITSFigure(sum)
#fig.show_grayscale()
fig.show_colorscale()
def show3(sum1,sum2):
""" aplpy is the better viewer clearly
"""
fig = aplpy.FITSFigure(sum1,subplot=(2,2,1))
#fig = aplpy.FITSFigure(sum2,subplot=(2,2,2),figure=1)
fig.show_grayscale()
# For some variations on this theme, e.g. time.time vs. time.clock, see
# http://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python
#
class Dtime(object):
""" Class to help measuring the wall clock time between tagged events
Typical usage:
dt = Dtime()
...
dt.tag('a')
...
dt.tag('b')
"""
def __init__(self, label=".", report=True):
self.start = self.time()
self.init = self.start
self.label = label
self.report = report
self.dtimes = []
dt = self.init - self.init
if self.report:
logging.info("Dtime: %s ADMIT " % self.label + str(self.start))
logging.info("Dtime: %s BEGIN " % self.label + str(dt))
def reset(self, report=True):
self.start = self.time()
self.report = report
self.dtimes = []
def tag(self, mytag):
t0 = self.start
t1 = self.time()
dt = t1 - t0
self.dtimes.append((mytag, dt))
self.start = t1
if self.report:
logging.info("Dtime: %s " % self.label + mytag + " " + str(dt))
return dt
def show(self):
if self.report:
for r in self.dtimes:
logging.info("Dtime: %s " % self.label + str(r[0]) + " " + str(r[1]))
return self.dtimes
def end(self):
t0 = self.init
t1 = self.time()
dt = t1 - t0
if self.report:
logging.info("Dtime: %s END " % self.label + str(dt))
return dt
def time(self):
""" pick the actual OS routine that returns some kind of timer
time.time : wall clock time (include I/O and multitasking overhead)
time.clock : cpu clock time
"""
return np.array([time.clock(), time.time()])
if __name__ == '__main__':
logging.basicConfig(level = logging.INFO)
dt = Dtime("mplot1")
#--start, -s n
#--end, -e n
#--box x1 y1 x2 y2
parser = ap.ArgumentParser(description='Plotting .fits files.')
parser.add_argument('-f', '--frame', nargs = '*', type = int, help = 'Starting and ending parameters for the frames analyzed')
parser.add_argument('-b', '--box', nargs = 4, type = int, help = 'Coordinates for the bottom left corner and top right corner of a rectangle of pixels to be analyzed from the data. In the structure x1, y1, x2, y2 (1 based numbers)')
parser.add_argument('-g', '--graphics', nargs = 1, type = int, default = 0, help = 'Controls whether to display or save graphics. 0: no graphics, 1: display graphics, 2: save graphics as .png')
args = vars(parser.parse_args())
if args['frame'] == None:
count = 0
start = None
end = None
step = 1
#while we have yet to find an end
while end == None:
filename = 'IMG%05d.FIT' % count
#if start has not been found yet, and this file exists
if start == None and os.path.isfile(filename):
start = count
#if start has been found and we finally found a file that doesn't exist, set end to the last file that existed (count - 1.FIT)
elif start != None and not os.path.isfile(filename):
end = count - 1
count += 1
elif len(args['frame']) >= 2 and len(args['frame']) <= 3:
start = args['frame'][0] # starting frame (IMGnnnnn.FIT)
end = args['frame'][1] # ending frame
if len(args['frame']) == 3:
step = args['frame']
else:
step = 1
else:
raise Exception,"-f needs 0, 2, or 3 arguments."
box = args['box'] # BLC and TRC
if box == None:
box = []
dt.tag("start")
# compute the average and dispersion of the series
h1,sum1,sum2,cube = dsum(start,end,step,box=box) # end can be uninitialized here might throw an error?
dt.tag("dsum")
nz = cube.shape[0]
# delta X and Y images
dsumy = sum1 - np.roll(sum1, 1, axis = 0) # change in the y axis
dsumx = sum1 - np.roll(sum1, 1, axis = 1) # change in the x axis
# write them to FITS
fits.writeto('dsumx.fits', dsumx, h1, clobber=True)
fits.writeto('dsumy.fits', dsumy, h1, clobber=True)
fits.writeto('sum1.fits', sum1, h1, clobber=True)
fits.writeto('sum2.fits', sum2, h1, clobber=True)
dt.tag("write2d")
# 3D cube to
h1['NAXIS'] = 3
h1['NAXIS3'] = nz
fits.writeto('cube.fits', cube, h1, clobber=True)
dt.tag("write3d")
if args['graphics'][0] == 1:
# plot the sum1 and sum2 correllation (glueviz should do this)
s1 = sum1.flatten()
s2 = sum2.flatten()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(s1,s2)
plt.show()
show2(sum1)
show2(sum2)
if args['graphics'][0] == 2:
imsave('sum1.png', sum1)
imsave('sum2.png', sum2)
dt.tag("done")
dt.end()
|
mit
| 8,728,276,588,416,666,000
| 31.734234
| 236
| 0.551534
| false
| 3.260206
| false
| false
| false
|
wooga/airflow
|
airflow/providers/google/cloud/operators/natural_language.py
|
1
|
10959
|
#
# 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 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.
"""
This module contains Google Cloud Language operators.
"""
from typing import Optional, Sequence, Tuple, Union
from google.api_core.retry import Retry
from google.cloud.language_v1 import enums
from google.cloud.language_v1.types import Document
from google.protobuf.json_format import MessageToDict
from airflow.models import BaseOperator
from airflow.providers.google.cloud.hooks.natural_language import CloudNaturalLanguageHook
MetaData = Sequence[Tuple[str, str]]
class CloudNaturalLanguageAnalyzeEntitiesOperator(BaseOperator):
"""
Finds named entities in the text along with entity types,
salience, mentions for each entity, and other properties.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudNaturalLanguageAnalyzeEntitiesOperator`
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf message Document
:type document: dict or google.cloud.language_v1.types.Document
:param encoding_type: The encoding type used by the API to calculate offsets.
:type encoding_type: google.cloud.language_v1.enums.EncodingType
:param retry: A retry object used to retry requests. If None is specified, requests will not be
retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
retry is specified, the timeout applies to each individual attempt.
:type timeout: float
:param metadata: Additional metadata that is provided to the method.
:type metadata: Sequence[Tuple[str, str]]
:param gcp_conn_id: The connection ID to use connecting to Google Cloud Platform.
:type gcp_conn_id: str
"""
# [START natural_language_analyze_entities_template_fields]
template_fields = ("document", "gcp_conn_id")
# [END natural_language_analyze_entities_template_fields]
def __init__(
self,
document: Union[dict, Document],
encoding_type: Optional[enums.EncodingType] = None,
retry: Optional[Retry] = None,
timeout: Optional[float] = None,
metadata: Optional[MetaData] = None,
gcp_conn_id: str = "google_cloud_default",
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.document = document
self.encoding_type = encoding_type
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
def execute(self, context):
hook = CloudNaturalLanguageHook(gcp_conn_id=self.gcp_conn_id)
self.log.info("Start analyzing entities")
response = hook.analyze_entities(
document=self.document, retry=self.retry, timeout=self.timeout, metadata=self.metadata
)
self.log.info("Finished analyzing entities")
return MessageToDict(response)
class CloudNaturalLanguageAnalyzeEntitySentimentOperator(BaseOperator):
"""
Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with each
entity and its mentions.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudNaturalLanguageAnalyzeEntitySentimentOperator`
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf message Document
:type document: dict or google.cloud.language_v1.types.Document
:param encoding_type: The encoding type used by the API to calculate offsets.
:type encoding_type: google.cloud.language_v1.enums.EncodingType
:param retry: A retry object used to retry requests. If None is specified, requests will not be
retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
retry is specified, the timeout applies to each individual attempt.
:type timeout: float
:param metadata: Additional metadata that is provided to the method.
:type metadata: Sequence[Tuple[str, str]]]
:param gcp_conn_id: The connection ID to use connecting to Google Cloud Platform.
:type gcp_conn_id: str
:rtype: google.cloud.language_v1.types.AnalyzeEntitiesResponse
"""
# [START natural_language_analyze_entity_sentiment_template_fields]
template_fields = ("document", "gcp_conn_id")
# [END natural_language_analyze_entity_sentiment_template_fields]
def __init__(
self,
document: Union[dict, Document],
encoding_type: Optional[enums.EncodingType] = None,
retry: Optional[Retry] = None,
timeout: Optional[float] = None,
metadata: Optional[MetaData] = None,
gcp_conn_id: str = "google_cloud_default",
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.document = document
self.encoding_type = encoding_type
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
def execute(self, context):
hook = CloudNaturalLanguageHook(gcp_conn_id=self.gcp_conn_id)
self.log.info("Start entity sentiment analyze")
response = hook.analyze_entity_sentiment(
document=self.document,
encoding_type=self.encoding_type,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
self.log.info("Finished entity sentiment analyze")
return MessageToDict(response)
class CloudNaturalLanguageAnalyzeSentimentOperator(BaseOperator):
"""
Analyzes the sentiment of the provided text.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudNaturalLanguageAnalyzeSentimentOperator`
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf message Document
:type document: dict or google.cloud.language_v1.types.Document
:param encoding_type: The encoding type used by the API to calculate offsets.
:type encoding_type: google.cloud.language_v1.enums.EncodingType
:param retry: A retry object used to retry requests. If None is specified, requests will not be
retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
retry is specified, the timeout applies to each individual attempt.
:type timeout: float
:param metadata: Additional metadata that is provided to the method.
:type metadata: sequence[tuple[str, str]]]
:param gcp_conn_id: The connection ID to use connecting to Google Cloud Platform.
:type gcp_conn_id: str
:rtype: google.cloud.language_v1.types.AnalyzeEntitiesResponse
"""
# [START natural_language_analyze_sentiment_template_fields]
template_fields = ("document", "gcp_conn_id")
# [END natural_language_analyze_sentiment_template_fields]
def __init__(
self,
document: Union[dict, Document],
encoding_type: Optional[enums.EncodingType] = None,
retry: Optional[Retry] = None,
timeout: Optional[float] = None,
metadata: Optional[MetaData] = None,
gcp_conn_id: str = "google_cloud_default",
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.document = document
self.encoding_type = encoding_type
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
def execute(self, context):
hook = CloudNaturalLanguageHook(gcp_conn_id=self.gcp_conn_id)
self.log.info("Start sentiment analyze")
response = hook.analyze_sentiment(
document=self.document, retry=self.retry, timeout=self.timeout, metadata=self.metadata
)
self.log.info("Finished sentiment analyze")
return MessageToDict(response)
class CloudNaturalLanguageClassifyTextOperator(BaseOperator):
"""
Classifies a document into categories.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudNaturalLanguageClassifyTextOperator`
:param document: Input document.
If a dict is provided, it must be of the same form as the protobuf message Document
:type document: dict or google.cloud.language_v1.types.Document
:param retry: A retry object used to retry requests. If None is specified, requests will not be
retried.
:param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if
retry is specified, the timeout applies to each individual attempt.
:type timeout: float
:param metadata: Additional metadata that is provided to the method.
:type metadata: sequence[tuple[str, str]]]
:param gcp_conn_id: The connection ID to use connecting to Google Cloud Platform.
:type gcp_conn_id: str
"""
# [START natural_language_classify_text_template_fields]
template_fields = ("document", "gcp_conn_id")
# [END natural_language_classify_text_template_fields]
def __init__(
self,
document: Union[dict, Document],
retry: Optional[Retry] = None,
timeout: Optional[float] = None,
metadata: Optional[MetaData] = None,
gcp_conn_id: str = "google_cloud_default",
*args,
**kwargs
) -> None:
super().__init__(*args, **kwargs)
self.document = document
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
def execute(self, context):
hook = CloudNaturalLanguageHook(gcp_conn_id=self.gcp_conn_id)
self.log.info("Start text classify")
response = hook.classify_text(
document=self.document, retry=self.retry, timeout=self.timeout, metadata=self.metadata
)
self.log.info("Finished text classify")
return MessageToDict(response)
|
apache-2.0
| 3,930,899,505,662,823,400
| 40.044944
| 102
| 0.686559
| false
| 4.140159
| false
| false
| false
|
goinnn/django-multiselectfield
|
example/app/urls.py
|
1
|
1723
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013 by Pablo Martín <goinnn@gmail.com>
#
# This software 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 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
from django import VERSION
try:
from django.conf.urls import url
# Compatibility for Django > 1.8
def patterns(prefix, *args):
if VERSION < (1, 9):
from django.conf.urls import patterns as django_patterns
return django_patterns(prefix, *args)
elif prefix != '':
raise NotImplementedError("You need to update your URLConf for "
"Django 1.10, or tweak it to remove the "
"prefix parameter")
else:
return list(args)
except ImportError: # Django < 1.4
if VERSION < (4, 0):
from django.conf.urls.defaults import patterns, url
else:
from django.urls import re_path as url
from .views import app_index
if VERSION < (1, 11):
urlpatterns = patterns(
'',
url(r'^$', app_index, name='app_index'),
)
else:
urlpatterns = [
url(r'^$', app_index, name='app_index'),
]
|
lgpl-3.0
| 1,116,952,307,818,030,800
| 34.875
| 79
| 0.639373
| false
| 4.109785
| false
| false
| false
|
bunnylin/supersakura
|
translate.py
|
1
|
4235
|
#!/usr/bin/python
# CC0, 2017 :: Kirinn Bunnylin / Mooncore
# https://creativecommons.org/publicdomain/zero/1.0/
import sys, re, time, subprocess
#from subprocess import check_output
if len(sys.argv) < 2:
print("Usage: python translate.py inputfile.tsv >outputfile.tsv")
print("The input file should be a tsv. The leftmost column is preserved in")
print("the output as unique string IDs, and the rightmost column is taken")
print("as the text to be translated.")
print("The translated output is printed in stdout in tsv format. You should")
print('pipe it into a suitable file, for example "outputfile.tsv".')
sys.exit(1)
def GetTranslation(com):
# Handy retry loop with a timeout for easily invoking translate-shell.
tries = 8
while tries != 0:
tries -= 1
try:
transres = subprocess.check_output(com, timeout = 16)
transres = transres.decode(sys.stdout.encoding).split("\n")
except:
transres = [""]
if len(transres) != 0: tries = 0
else: time.sleep(16)
return transres
# Read the constant substitutions list into memory. The file trans-subs.txt
# should contain one substitution per line, in the form "source/new text".
# Lines starting with a # are treated as comments.
sublist = []
with open("trans-subs.txt") as subfile:
for line in subfile:
if line[0] != "#":
line = line.rstrip()
if line != "":
splitline = line.split("/")
sublist.append({"from": splitline[0], "to": splitline[-1]})
# Print the output header.
print("String IDs\tOriginal\tPhonetic\tGoogle\tBing\tYandex")
sys.stdout.flush()
with open(sys.argv[1]) as infile:
for line in infile:
delaytime = time.time() + 1.024
# If this line has no tabs, the line as a whole is used as translatable
# input. Otherwise everything before the first tab is saved as the
# string ID, and everything after the last tab is used as the
# translatable input.
stringid = ""
splitline = line.rstrip().split("\t")
if len(splitline) > 1:
stringid = splitline[0]
line = splitline[-1]
# Output the string ID and translatable input.
linepart = stringid + "\t" + line + "\t"
sys.stdout.buffer.write(linepart.encode("utf-8"))
# Apply pre-translation substitutions.
for subitem in sublist:
line = line.replace(subitem["from"], subitem["to"])
# Replace backslashes with a double backslash. At least Bing sometimes
# drops backslashes if not doubled.
line = line.replace("\\", "\\\\")
# Google translate, wrapped in a retry loop.
transgoo = GetTranslation(["translate-shell","ja:en","-e","google",
"-no-ansi","-no-autocorrect","-show-alternatives","n",
"-show-languages","n","-show-prompt-message","n","--",line])
# transgoo is now expected to have the original on line 1, the phonetic
# on line 2 in brackets, and the translation on line 4.
trans0 = transgoo[1][1:-1]
trans1 = transgoo[3]
# Get the other translations.
trans2 = GetTranslation(["translate-shell","-b","ja:en","-e","bing",
"-no-ansi","--",line])[0]
trans3 = GetTranslation(["translate-shell","-b","ja:en","-e","yandex",
"-no-ansi","--",line])[0]
# A brief wait between requests is polite to the translation servers.
delaylen = delaytime - time.time()
if delaylen > 0: time.sleep(delaylen)
# Pack the translated strings in a single variable for post-processing.
# Delimit with tab characters.
transall = trans0 + "\t" + trans1 + "\t" + trans2 + "\t" + trans3 + "\n"
# If the output contains ": ", but the input doesn't, then the space was
# added unnecessarily and should be removed.
if transall.find(": ") != -1 and line.find(": ") == -1:
transall = transall.replace(": ", ":")
# The translators tend to add spaces after some backslashes, remove.
transall = transall.replace("\\ ", "\\")
# Change double-backslashes back to normal.
transall = transall.replace("\\\\", "\\")
# Some translators also add spaces after dollars, remove them.
transall = transall.replace("\\$ ", "\\$")
# Output the translated, processed strings.
sys.stdout.buffer.write(transall.encode("utf-8"))
sys.stdout.flush()
# end.
|
gpl-3.0
| 9,078,087,450,414,523,000
| 35.508621
| 79
| 0.654782
| false
| 3.576858
| false
| false
| false
|
marcusmchale/breedcafs
|
app/cypher.py
|
1
|
76573
|
class Cypher:
def __init__(self):
pass
# user procedures
allowed_emails = (
' MATCH '
' (e: Emails) '
' RETURN '
' e.allowed '
)
user_allowed_emails = (
' MATCH '
' (u:User) '
' WITH '
' COLLECT (DISTINCT u.email) as registered_emails '
' MATCH '
' (user:User {'
' username_lower : toLower(trim($username)) '
' }) '
' -[: SUBMITTED]->(: Submissions) '
' -[: SUBMITTED]->(e: Emails) '
' RETURN '
' FILTER (n in e.allowed WHERE NOT n in registered_emails) as user_allowed '
)
email_find = (
' MATCH '
' (user: User { '
' email: toLower(trim($email)) '
' }) '
' RETURN '
' user '
)
confirm_email = (
' MATCH '
' (user: User { '
' email: toLower(trim($email)) '
' }) '
' SET '
' user.confirmed = true '
)
user_find = (
' MATCH '
' (user: User) '
' WHERE '
' user.username_lower = toLower($username) '
' OR '
' user.email = toLower(trim($email)) '
' RETURN '
' user '
)
username_find = (
' MATCH '
' (user: User { '
' username_lower: toLower($username)'
' }) '
' RETURN '
' user '
)
user_affiliations = (
' MATCH '
' (u: User { '
' username_lower: toLower($username) '
' }) '
' -[a: AFFILIATED]->(p: Partner) '
' OPTIONAL MATCH '
' (p)<-[: AFFILIATED {admin: true}]-(admin: User) '
' RETURN '
' p.name , '
' p.fullname , '
' a.confirmed as confirmed, '
' a.data_shared as data_shared , '
' admin.email as admin_email'
)
add_affiliations = (
' UNWIND '
' $partners as partner '
' MATCH '
' (u:User { '
' username_lower: toLower(trim($username)) '
' }), '
' (p:Partner { '
' name_lower: toLower(trim(partner)) '
' }) '
' MERGE '
' (u)-[a: AFFILIATED { '
' data_shared: false, '
' admin: false, '
' confirm_timestamp: [], '
' confirmed: false '
' }]->(p) '
' ON CREATE SET '
' a.add_timestamp = datetime.transaction().epochMillis '
' RETURN '
' p.name '
)
remove_affiliations = (
' UNWIND '
' $partners as partner '
' MATCH '
' (u:User { '
' username_lower: toLower(trim($username)) '
' }) '
' -[a:AFFILIATED { '
' data_shared: false '
' }]->(p: Partner {'
' name_lower: toLower(trim(partner)) '
' }) '
' WHERE '
' size(a.confirm_timestamp = 0 '
' DELETE '
' a '
' RETURN p.name '
)
password_reset = (
' MATCH '
' (user: User { '
' email : toLower(trim($email)) '
' }) '
' SET user.password = $password '
)
user_register = (
# This is a little cautious using merge to prevent overwriting a user profile if it is called in error
' MATCH '
' (partner:Partner {'
' name_lower: toLower(trim($partner)) '
' }) '
' MERGE '
' (user:User { '
' username_lower: toLower(trim($username)) '
' }) '
' ON CREATE SET '
' user.username = trim($username), '
' user.password = $password, '
' user.email = toLower(trim($email)), '
' user.name = $name, '
' user.time = datetime.transaction().epochMillis, '
' user.access = ["user"], '
' user.confirmed = false, '
' user.found = false '
' ON MATCH SET '
' user.found = TRUE '
' WITH '
' user, partner '
' WHERE '
' user.found = false '
' CREATE '
' (user)-[r: AFFILIATED { '
' data_shared: true, '
' confirmed: false, '
' confirm_timestamp: [], '
' admin: false '
' }]->(partner), '
' (user)-[: SUBMITTED]->(sub: Submissions), '
' (sub)-[: SUBMITTED]->(: Emails {allowed :[]}),'
' (sub)-[: SUBMITTED]->(locations: Locations), '
' (locations)-[: SUBMITTED]->(: Countries), '
' (locations)-[: SUBMITTED]->(: Regions), '
' (locations)-[: SUBMITTED]->(: Farms), '
' (sub)-[:SUBMITTED]->(items: Items), '
' (items)-[: SUBMITTED]->(: Fields), '
' (items)-[: SUBMITTED]->(: Blocks), '
' (items)-[: SUBMITTED]->(: Trees), '
' (items)-[: SUBMITTED]->(: Samples), '
' (sub)-[:SUBMITTED]->(: Records) '
)
add_allowed_email = (
' MATCH '
' (all: Emails) '
' WITH '
' all.allowed as allowed_emails '
' UNWIND '
' allowed_emails as email '
' WITH '
' COLLECT(DISTINCT email) as set '
' WHERE '
' NOT toLower(trim($email)) IN set '
' MATCH '
' (:User { '
' username_lower: toLower(trim($username)) '
' }) '
' -[:SUBMITTED]->(: Submissions) '
' -[:SUBMITTED]->(e: Emails) '
' SET e.allowed = e.allowed + [toLower(trim($email))] '
' RETURN toLower(trim($email)) '
)
remove_allowed_email = (
' MATCH '
' (:User { '
' username_lower: toLower(trim($username)) '
' }) '
' -[:SUBMITTED]->(: Submissions) '
' -[:SUBMITTED]->(e: Emails) '
' WITH e, extract(x in $email | toLower(trim(x))) as emails'
' SET e.allowed = FILTER (n in e.allowed WHERE NOT n IN emails) '
' RETURN emails '
)
user_del = (
' MATCH '
' (u:User { '
' email: toLower(trim($email)), '
' confirmed: false '
' }) '
' OPTIONAL MATCH '
' (u)-[:SUBMITTED*..3]->(n) '
' DETACH DELETE '
' u,n '
)
partner_admin_users = (
' MATCH '
' (:User { '
' username_lower: toLower(trim($username)) '
' }) '
' -[: AFFILIATED { '
' admin: true '
' }]->(p:Partner) '
' WITH p '
' MATCH '
' (p)<-[a:AFFILIATED]-(u:User) '
' RETURN { '
' Username: u.username, '
' Email: u.email, '
' Name: u.name, '
' Partner: p.name, '
' PartnerFullName: p.fullname, '
' Confirmed: a.confirmed '
' } '
)
global_admin_users = (
' MATCH '
' (u:User)-[a:AFFILIATED]->(p:Partner) '
' RETURN { '
' Username : u.username, '
' Email : u.email, '
' Name : u.name, '
' Partner : p.name, '
' PartnerFullName : p.fullname, '
' Confirmed : a.confirmed '
' } '
)
# these functions toggle the confirmed status so do both confirm/un-confirm operations
partner_confirm_users = (
' MATCH '
' (user:User { '
' username_lower: toLower(trim($username)) '
' }) '
' -[:AFFILIATED {admin : true}]->(p:Partner) '
' WHERE '
' "partner_admin" in user.access'
' MATCH '
' (p)<-[a:AFFILIATED]-(u:User) '
' UNWIND '
' $confirm_list as confirm '
' WITH '
' p,a,u '
' WHERE '
' p.name_lower = toLower(trim(confirm["partner"])) '
' AND '
' u.username_lower = toLower(trim(confirm["username"])) '
' SET '
' a.confirmed = NOT a.confirmed, '
' a.confirm_timestamp = a.confirm_timestamp + datetime.transaction().epochMillis '
' RETURN u.name '
)
global_confirm_users = (
' MATCH '
' (p:Partner)<-[a:AFFILIATED]-(u:User) '
' UNWIND '
' $confirm_list as confirm '
' WITH '
' p,a,u '
' WHERE '
' p.name_lower = toLower(trim(confirm["partner"])) '
' AND '
' u.username_lower = toLower(trim(confirm["username"])) '
' SET '
' a.confirmed = NOT a.confirmed, '
' a.confirm_timestamp = a.confirm_timestamp + datetime.transaction().epochMillis '
' RETURN u.name '
)
partner_admins = (
' MATCH '
' (u:User)-[a:AFFILIATED]->(p:Partner) '
' RETURN { '
' Username : u.username, '
' Email : u.email, '
' Name : u.name, '
' Partner : p.name, '
' PartnerFullName : p.fullname, '
' Confirmed : a.admin '
' } '
)
confirm_admins = (
' MATCH '
' (p:Partner)<-[a:AFFILIATED]-(u:User) '
' UNWIND $admins as admin '
' WITH '
' p,a,u '
' WHERE '
' p.name_lower = toLower(trim(admin["partner"])) '
' AND '
' u.username_lower = toLower(trim(admin["username"])) '
' SET '
' a.admin = NOT a.admin '
' WITH u '
' MATCH (u)-[a:AFFILIATED]->(:Partner) '
' WITH u, collect(a.admin) as admin_rights '
' set u.access = CASE '
' WHEN true IN admin_rights '
' THEN ["user","partner_admin"] '
' ELSE ["user"] '
' END '
' RETURN '
' u.name '
)
# Upload procedures
upload_check_value = (
# make sure that all the entries match accepted entries
# handles empty items and white space
# forces strings to lower case and float/integer types
# removes % symbols
# ! ensure to declare input (as node) and value (from file) before including
' CASE '
' WHEN input.format = "multicat" '
' THEN CASE '
' WHEN size(FILTER (n in split(value, ":") WHERE size(n) > 0)) '
' = size(FILTER (n in split(value, ":") WHERE toLower(trim(n)) in '
' EXTRACT(item in input.category_list | toLower(item)))) '
' THEN trim(value) '
' ELSE Null '
' END '
' WHEN input.format = "categorical" '
' THEN [category IN input.category_list WHERE toLower(category) = toLower(trim(value)) | category][0] '
' WHEN input.format = "text" '
' THEN CASE '
' WHEN input.name_lower IN [ '
' "assign field sample to sample(s) by id", '
' "assign field sample to tree(s) by id", '
' "assign field sample to block(s) by id" '
' ] THEN CASE '
' WHEN size(split(value, "," )) = size( '
' filter(x in split(value, ",") WHERE '
' toInteger(trim(x)) IS NOT NULL '
' OR ( '
' size(split(x, "-")) = 2'
' AND toInteger(split(x, "-")[0]) IS NOT NULL '
' AND toInteger(split(x, "-")[1]) IS NOT NULL'
' ) '
' ) '
' ) '
' THEN value '
' ELSE Null '
' END '
' WHEN input.name_lower IN [ '
' "assign field sample to block by name", '
' "assign tree to block by name" '
' ] '
' THEN trim(value) '
' WHEN input.name contains "time" '
' THEN CASE '
' WHEN size(split(value, ":")) = 2 '
' AND size(split(value, ":")[0]) <= 2 '
' AND toInteger(trim(split(value, ":")[0])) <=24 '
' AND toInteger(trim(split(value, ":")[0])) >= 0 '
' AND size(split(value, ":")[1]) <= 2 '
' AND toInteger(trim(split(value, ":")[1])) < 60 '
' AND toInteger(trim(split(value, ":")[1])) >= 0 '
' THEN trim(value) '
' ELSE Null '
' END '
' ELSE '
' toString(value) '
' END '
' WHEN input.format = "percent" '
' THEN CASE '
' WHEN toFloat(replace(value, "%", "")) IS NOT NULL '
' THEN toFloat(replace(value, "%", "")) '
' ELSE Null '
' END '
' WHEN input.format = "counter" '
' THEN CASE '
' WHEN toInteger(value) IS NOT NULL '
' THEN toInteger(value) '
' ELSE '
' Null '
' END '
' WHEN input.format = "numeric" '
' THEN CASE '
' WHEN toFloat(value) IS NOT NULL '
' THEN toFloat(value) '
' ELSE Null '
' END '
' WHEN input.format = "boolean" '
' THEN CASE '
' WHEN toLower(value) in ["yes","y"] '
' THEN True '
' WHEN toLower(value) in ["no","n"] '
' THEN False '
' WHEN toBoolean(value) IS NOT NULL '
' THEN toBoolean(value) '
' ELSE Null '
' END '
' WHEN input.format = "location" '
' THEN CASE '
' WHEN size(split(value, ";")) = 2 '
' AND toFloat(trim(split(value, ";")[0])) IS NOT NULL '
' AND toFloat(trim(split(value, ";")[1])) IS NOT NULL '
' THEN trim(value) '
' ELSE Null '
' END '
' WHEN input.format = "date" '
' THEN CASE '
' WHEN size(split(value, "-")) = 3 '
' AND size(trim(split(value, "-")[0])) = 4 '
' AND size(trim(split(value, "-")[1])) <= 2 '
' AND size(trim(split(value, "-")[1])) >= 1 '
' AND toInteger(trim(split(value, "-")[1])) >= 1 '
' AND toInteger(trim(split(value, "-")[1])) <= 12 '
' AND size(trim(split(value, "-")[2])) <= 2 '
' AND size(trim(split(value, "-")[2])) >= 1 '
' AND toInteger(trim(split(value, "-")[2])) >= 1 '
' AND toInteger(trim(split(value, "-")[2])) <= 31 '
' THEN '
' trim(value) '
' ELSE '
' Null '
' END '
' ELSE Null '
' END '
)
upload_fb_check = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' toInteger(csvLine.row_index) as row_index, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 1) as replicate, '
' toLower(trim(csvLine.trait)) as input_name, '
' trim(csvLine.value) as value, '
' apoc.date.parse(csvLine.timestamp, "ms", "yyyy-MM-dd HH:mm:sszzz") as time, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
' WHERE trim(csvLine.value) <> "" '
' OPTIONAL MATCH '
' (item: Item { '
' uid: uid '
' }) '
' OPTIONAL MATCH '
' (:RecordType { '
' name_lower: "trait" '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(:ItemLevel { '
' name_lower: level '
' }) '
' WITH '
' row_index, '
' input, '
' input_name, '
' item, replicate, '
' time, '
' value '
' OPTIONAL MATCH '
' (item)'
' <-[:FOR_ITEM]-(if: ItemInput)'
' -[:FOR_INPUT*..2]->(input), '
' (if)'
' <-[:RECORD_FOR]-(r: Record { '
' replicate: replicate, '
' time: time '
' }) '
' <-[s: SUBMITTED]-(: UserFieldInput) '
' <-[: SUBMITTED]-(: Records) '
' <-[: SUBMITTED]-(: Submissions) '
' <-[: SUBMITTED]-(u: User) '
' -[:AFFILIATED {data_shared: true}]->(p:Partner) '
' OPTIONAL MATCH '
' (p)<-[a: AFFILIATED]-(: User {username_lower: toLower($username)}) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' time, '
+ upload_check_value +
' AS value, '
' CASE '
' WHEN a.confirmed '
' THEN r.value '
' ELSE CASE '
' WHEN r IS NOT NULL '
' THEN "ACCESS DENIED" '
' ELSE null '
' END '
' END AS r_value, '
' s.time AS `submitted at`, '
' CASE WHEN a.confirmed THEN u.name ELSE p.name END AS user, '
' a.confirmed AS access '
' WHERE '
' ( '
' item IS NULL '
' OR '
' input IS NULL '
' OR '
' value IS NULL '
' OR '
' a.confirmed <> True '
' OR'
' r.value <> value '
' ) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' value, '
' COLLECT(DISTINCT({ '
' existing_value: toString(r_value), '
' `submitted at`: `submitted at`, '
' user: user, '
' access: access '
' })) as conflicts '
' RETURN { '
' row_index: row_index, '
' `Supplied input name`: input_name, '
' UID: item.uid, '
' Replicate: replicate, '
' `Input variable`: input.name, '
' Format: input.format, '
' `Category list`: input.category_list, '
' Value: value, '
' Conflicts: conflicts '
' } '
' ORDER BY row_index '
' LIMIT 50 '
)
upload_fb = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' trim(csvLine.timestamp) as text_time, '
' trim(csvLine.person) as person, '
' trim(csvLine.location) as location, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toInteger(split(csvLine.uid, "_")[0]) '
' END as field_uid, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 1) as replicate, '
' toLower(trim(csvLine.trait)) as input_name, '
' trim(csvLine.value) as value, '
' apoc.date.parse(csvLine.timestamp, "ms", "yyyy-MM-dd HH:mm:sszzz") as time, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
' WHERE trim(csvLine.value) <> "" '
# And identify the fields and inputs assessed
' MATCH '
' (field:Field { '
' uid: field_uid '
' }), '
' (item: Item { '
' uid: uid '
' }), '
' (:RecordType {'
' name_lower: "trait" '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(item_level: ItemLevel { '
' name_lower: level '
' }) '
' FOREACH (n in CASE '
' WHEN level = "field" '
' THEN [1] ELSE [] END | '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput :FieldInput)-[: FOR_INPUT]->(input) '
' ON CREATE '
' ) '
' FOREACH (n in CASE '
' WHEN level in ["block", "tree", "sample"] '
' THEN [1] ELSE [] END | '
' MERGE '
' (field)<-[: FROM_FIELD]-(field_input: FieldInput)-[: FOR_INPUT]->(input) '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput)-[: FOR_INPUT]->(field_input) '
' ) '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' location, '
' time, '
' replicate, '
' text_time, '
+ upload_check_value +
' AS value '
' WHERE value IS NOT NULL '
# get the user submission tracking nodes
' MATCH '
' (:User { '
' username_lower : toLower(trim($username))'
' }) '
' -[: SUBMITTED]->(: Submissions) '
' -[: SUBMITTED]->(data_sub: Records) '
# and the item/input node
' MATCH '
' (item) '
' <-[: FOR_ITEM]-(item_input: ItemInput)'
' -[ :FOR_INPUT*..2]->(input) '
# and the field/input node
# todo consider the model here, this is an undirected match with two labels, not super happy with this one,
# todo would it be better to have a redundant ItemInput node for fields?
' MATCH (item) '
' -[:FOR_ITEM | FOR_INPUT*..2]-(field_input: FieldInput) '
' -[:FOR_INPUT]->(input) '
' MERGE '
' (r: Record { '
' time : time, '
' replicate: replicate '
' }) '
' -[:RECORD_FOR]->(item_input) '
' ON MATCH SET '
' r.found = True '
' ON CREATE SET '
' r.found = False, '
' r.person = person, '
' r.location = location, '
' r.value = CASE '
' WHEN input.format <> "multicat" THEN value '
' ELSE extract(i in FILTER (n in split(value, ":") WHERE size(n) > 0 )| toLower(trim(i)))'
' END '
# additional statements to occur when new data point
' FOREACH (n IN CASE '
' WHEN r.found = False '
' THEN [1] ELSE [] END | '
# track user submissions through /User/FieldInput container
' MERGE '
' (data_sub)'
' -[:SUBMITTED]->(uff:UserFieldInput) '
' -[:CONTRIBUTED]->(field_input) '
# then finally the data with a timestamp
' MERGE '
' (uff)-[s1:SUBMITTED]->(r) '
' ON CREATE SET '
' s1.time = datetime.transaction().epochMillis '
' ) '
' WITH '
' field, '
' item, '
' input, '
' value, '
' r '
' MATCH '
' (partner:Partner) '
' <-[:AFFILIATED {data_shared: True}]-(user:User) '
' -[:SUBMITTED]->(:Submissions) '
' -[:SUBMITTED]->(:Records) '
' -[:SUBMITTED]->(:UserFieldInput) '
' -[submitted:SUBMITTED]->(r) '
# need to check for permissions for values that didn't merge to provide filtered feedback
# and optionally roll back if existing records overlap without access confirmed.
' OPTIONAL MATCH '
' (partner)<-[access: AFFILIATED {confirmed: True}]-(:User {username_lower:toLower(trim($username))}) '
# And give the user feedback on their submission
' RETURN { '
' Found: r.found, '
' `Submitted by`: CASE WHEN access IS NOT NULL THEN user.name ELSE partner.name END, '
' `Submitted at`: submitted.time, '
' Value: CASE '
' WHEN NOT r.found '
' THEN r.value '
' WHEN access IS NOT NULL '
' THEN r.value '
' ELSE "ACCESS DENIED" '
' END, '
' `Uploaded value`: value, '
' Access: CASE WHEN access IS NULL THEN False ELSE True END, '
' Replicate: r.replicate, '
' Time: r.time, '
' UID: item.uid, '
' `Input variable`: input.name, '
' Partner: partner.name '
' } '
' ORDER BY input.name_lower, field.uid, item.id, r.replicate '
)
upload_table_property_check = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' toInteger(csvLine.row_index) as row_index, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toUpper(csvLine.uid) '
' END as uid, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
' OPTIONAL MATCH '
' (item: Item { '
' uid: uid '
' }) '
' UNWIND $inputs as input_name '
' OPTIONAL MATCH '
' (:RecordType {'
' name_lower: "property" '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(:ItemLevel { '
' name_lower: level '
' }) '
' WITH '
' row_index, '
' input_name, '
' item, '
' input, '
' csvLine[input_name] as value '
' WHERE trim(csvLine[input_name]) <> ""'
' OPTIONAL MATCH '
' (item)'
' <-[:FOR_ITEM]-(if: ItemInput)'
' -[:FOR_INPUT*..2]->(input), '
' (if)'
' <-[:RECORD_FOR]-(r: Record) '
' <-[s: SUBMITTED]-(: UserFieldInput) '
' <-[: SUBMITTED]-(: Records) '
' <-[: SUBMITTED]-(: Submissions) '
' <-[: SUBMITTED]-(u: User) '
' -[:AFFILIATED {data_shared: true}]->(p:Partner) '
' OPTIONAL MATCH '
' (p)<-[a: AFFILIATED]-(: User {username_lower: toLower($username)}) '
' WITH '
' row_index, '
' input_name, '
' item, '
' input, '
+ upload_check_value +
' AS value, '
' CASE '
' WHEN a.confirmed '
' THEN r.value '
' ELSE CASE '
' WHEN r IS NOT NULL '
' THEN "ACCESS DENIED" '
' ELSE null '
' END '
' END AS r_value, '
' s.time AS `submitted at`, '
' CASE WHEN a.confirmed THEN u.name ELSE p.name END AS user, '
' a.confirmed AS access '
' WHERE '
' ( '
' item IS NULL '
' OR '
' input IS NULL '
' OR '
' value IS NULL '
' ) OR ( '
' a.confirmed <> True '
' OR'
' r.value <> value '
' ) '
' WITH '
' row_index, '
' item, '
' input, '
' input_name, '
' value, '
' COLLECT(DISTINCT({ '
' existing_value: toString(r_value), '
' `submitted at`: `submitted at`, '
' user: user, '
' access: access '
' })) as conflicts '
' RETURN { '
' row_index: row_index, '
' `Supplied input name`: input_name, '
' UID: item.uid, '
' `Input variable`: input.name, '
' Format: input.format, '
' `Category list`: input.category_list, '
' Value: value, '
' Conflicts: conflicts '
' } '
' ORDER BY row_index '
' LIMIT 50 '
)
upload_table_trait_check = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' toInteger(csvLine.row_index) as row_index, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 0) as replicate, '
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.date, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.date, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.time, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.time, " ", "") '
' ELSE '
' "12:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as time, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
' OPTIONAL MATCH '
' (item: Item { '
' uid: uid '
' }) '
' UNWIND $inputs as input_name '
' OPTIONAL MATCH '
' (:RecordType {'
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(:ItemLevel { '
' name_lower: level '
' }) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' time, '
' csvLine[input_name] as value '
' WHERE trim(csvLine[input_name]) <> "" '
' OPTIONAL MATCH '
' (item)'
' <-[:FOR_ITEM]-(if: ItemInput)'
' -[:FOR_INPUT*..2]->(input), '
' (if)'
' <-[:RECORD_FOR]-(r: Record { '
' replicate: replicate, '
' time: time '
' }) '
' <-[s: SUBMITTED]-(: UserFieldInput) '
' <-[: SUBMITTED]-(: Records) '
' <-[: SUBMITTED]-(: Submissions) '
' <-[: SUBMITTED]-(u: User) '
' -[:AFFILIATED {data_shared: true}]->(p:Partner) '
' OPTIONAL MATCH '
' (p)<-[a: AFFILIATED]-(: User {username_lower: toLower($username)}) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' time, '
+ upload_check_value +
' AS value, '
' CASE '
' WHEN a.confirmed '
' THEN r.value '
' ELSE CASE '
' WHEN r IS NOT NULL '
' THEN "ACCESS DENIED" '
' ELSE null '
' END '
' END AS r_value, '
' s.time AS `submitted at`, '
' CASE WHEN a.confirmed THEN u.name ELSE p.name END AS user, '
' a.confirmed AS access '
' WHERE '
' ( '
' item IS NULL '
' OR '
' input IS NULL '
' OR '
' value IS NULL '
' OR '
' a.confirmed <> True '
' OR'
' r.value <> value '
' ) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' value, '
' COLLECT(DISTINCT({ '
' existing_value: toString(r_value), '
' `submitted at`: `submitted at`, '
' user: user, '
' access: access '
' })) as conflicts '
' RETURN { '
' row_index: row_index, '
' `Supplied input name`: input_name, '
' UID: item.uid, '
' Replicate: replicate, '
' `Input variable`: input.name, '
' Format: input.format, '
' `Category list`: input.category_list, '
' Value: value, '
' Conflicts: conflicts '
' } '
' ORDER BY row_index '
' LIMIT 50 '
)
upload_table_condition_check = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' toInteger(csvLine.row_index) as row_index, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 0) as replicate, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level, '
# start time from start date and start time
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.`start date`, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.`start date`, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.`start time`, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.`start time`, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.`start time`, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.`start time`, " ", "") '
' ELSE '
' "00:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as start, '
# end time from end date and end time
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.`end date`, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.`end date`, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.`end time`, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.`end time`, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.`end time`, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.`end time`, " ", "") '
' ELSE '
' "24:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as end '
' OPTIONAL MATCH '
' (item: Item { '
' uid: uid '
' }) '
' UNWIND $inputs as input_name '
' OPTIONAL MATCH '
' (:RecordType { '
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(:ItemLevel { '
' name_lower: level '
' }) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' start, end, '
' csvLine[input_name] as value '
' WHERE trim(csvLine[input_name]) <> "" '
' OPTIONAL MATCH '
' (item) '
' <-[:FOR_ITEM]-(if: ItemInput) '
' -[:FOR_INPUT*..2]->(input), '
' (if) '
' <-[:RECORD_FOR]-(r: Record { '
' replicate: replicate '
' }) '
' <-[s: SUBMITTED]-(: UserFieldInput) '
' <-[: SUBMITTED]-(: Records) '
' <-[: SUBMITTED]-(: Submissions) '
' <-[: SUBMITTED]-(u: User) '
' -[:AFFILIATED { '
' data_shared: true'
' }]->(p:Partner) '
' OPTIONAL MATCH '
' (p)<-[a: AFFILIATED]-(: User {username_lower: toLower($username)}) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' start, end, '
+ upload_check_value +
' AS value, '
' CASE WHEN r.start <> False THEN r.start ELSE Null END AS r_start, '
' CASE WHEN r.end <> False THEN r.end ELSE Null END AS r_end, '
' CASE '
' WHEN a.confirmed '
' THEN r.value '
' ELSE CASE '
' WHEN r IS NOT NULL '
' THEN "ACCESS DENIED" '
' ELSE null '
' END '
' END AS r_value, '
' s.time AS `submitted at`, '
' CASE WHEN a.confirmed THEN u.name ELSE p.name END AS user, '
' a.confirmed AS access '
' WHERE '
' ( '
' item IS NULL '
' OR '
' input IS NULL '
' OR '
' value IS NULL '
' ) OR ( '
# condition conflicts
' ( '
' a.confirmed <> True '
' OR '
' r.value <> value '
' ) AND ( '
# handle fully bound records
# - any overlapping records
' ( '
' r_start < end '
' AND '
' r_end > start '
' ) OR ( '
# - a record that has a lower bound in the bound period
' r_start >= start '
' AND '
' r_start < end '
' ) OR ( '
# - a record that has an upper bound in the bound period
' r_end > start '
' AND '
' r_end <= end '
' ) OR ( '
# now handle lower bound only records
' end IS NULL '
' AND ( '
' ( '
# - existing bound period includes start
' r_end > start '
' AND '
' r_start <= start '
# - record with same lower bound
' ) OR ( '
' r_start = start '
# - record with upper bound only greater than this lower bound
' ) OR ( '
' r_start IS NULL '
' AND '
' r_end > start '
' )'
' ) '
' ) OR ( '
# now handle upper bound only records
' start IS NULL '
' AND ( '
' ( '
# - existing bound period includes end
' r_end >= end '
' AND '
' r_start < end '
# - record with same upper bound
' ) OR ( '
' r_end = end '
# - record with lower bound only less than this upper bound
' ) OR ( '
' r_end IS NULL '
' AND '
' r_start < end '
' ) '
' )'
' ) OR ( '
# always conflict with unbound records
' r_end IS NULL '
' AND '
' r_start IS NULL '
' ) '
' ) '
' ) '
' WITH '
' row_index, '
' input_name, '
' item, replicate, '
' input, '
' value, '
' COLLECT(DISTINCT({ '
' start: r_start, '
' end: r_end, '
' existing_value: toString(r_value), '
' `submitted at`: `submitted at`, '
' user: user, '
' access: access '
' })) as conflicts '
' RETURN { '
' row_index: row_index, '
' `Supplied input name`: input_name, '
' UID: item.uid, '
' Replicate: replicate, '
' `Input variable`: input.name, '
' Format: input.format, '
' `Category list`: input.category_list, '
' Value: value, '
' Conflicts: conflicts '
' } '
' ORDER BY row_index '
' LIMIT 50 '
)
upload_table_curve_check = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' ['
' key in keys(csvLine) WHERE toFloat(key) in $x_values AND toFloat(csvLine[key]) <> "" '
' | [toFloat(key), toFloat(csvLine[key])]'
' ] as x_y_list '
' UNWIND x_y_list as x_y '
' WITH '
' csvLine, '
' x_y '
' ORDER BY x_y '
' WITH '
' csvLine, '
' collect(x_y[0]) as x_values, '
' collect(x_y[1]) as y_values '
' WITH '
' csvLine, '
' x_values, '
' y_values, '
' toInteger(csvLine.row_index) as row_index, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 0) as replicate, '
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.date, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.date, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.time, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.time, " ", "") '
' ELSE '
' "12:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as time, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
' OPTIONAL MATCH '
' (item: Item { '
' uid: uid '
' }) '
' OPTIONAL MATCH '
' (:RecordType {'
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower($input_name) '
' })-[:AT_LEVEL]->(:ItemLevel { '
' name_lower: level '
' }) '
' WITH '
' row_index, '
' item, replicate, '
' input, '
' time, '
' x_values,'
' y_values '
' WHERE size(y_values) > 0 '
' OPTIONAL MATCH '
' (item)'
' <-[:FOR_ITEM]-(if: ItemInput)'
' -[:FOR_INPUT*..2]->(input), '
' (if)'
' <-[:RECORD_FOR]-(r: Record { '
' replicate: replicate, '
' time: time '
' }) '
' <-[s: SUBMITTED]-(: UserFieldInput) '
' <-[: SUBMITTED]-(: Records) '
' <-[: SUBMITTED]-(: Submissions) '
' <-[: SUBMITTED]-(u: User) '
' -[:AFFILIATED {data_shared: true}]->(p:Partner) '
' WHERE '
# compare r.y_values with y_values
# list relevant [x_value, y_value] pairs
' [i IN range(0, size(x_values) - 1) WHERE x_values[i] in r.x_values | [x_values[i], y_values[i]]] <> '
# list of relevant [r.x_value, r.y_value] pairs
' [i IN range(0, size(r.x_values) - 1) WHERE r.x_values[i] in x_values | [r.x_values[i], r.y_values[i]]] '
' OPTIONAL MATCH '
' (p)<-[a: AFFILIATED]-(: User {username_lower: toLower($username)}) '
' WITH '
' row_index, '
' item, replicate, '
' input, '
' time, '
' x_values, '
' y_values, '
' CASE '
' WHEN a.confirmed '
' THEN r.y_values '
' ELSE CASE '
' WHEN r IS NOT NULL '
' THEN "ACCESS DENIED" '
' ELSE null '
' END '
' END AS r_y_values, '
' r.x_values as r_x_values, '
' s.time AS `submitted at`, '
' CASE WHEN a.confirmed THEN u.name ELSE p.name END AS user, '
' a.confirmed AS access '
' WHERE '
' ( '
' item IS NULL '
' OR '
' input IS NULL '
' OR '
' a.confirmed <> True '
' OR '
' r.y_values <> y_values '
' ) '
' WITH '
' row_index, '
' item, replicate, '
' input, '
' x_values, '
' y_values, '
' COLLECT(DISTINCT({ '
' existing_value: [i in range(0, size(r_x_values) - 1) | [r_x_values[i], r_y_values[i]]], '
' `submitted at`: `submitted at`, '
' user: user, '
' access: access '
' })) as conflicts '
' RETURN { '
' row_index: row_index, '
' `Supplied input name`: $input_name, '
' UID: item.uid, '
' Replicate: replicate, '
' `Input variable`: input.name, '
' Format: input.format, '
' `Category list`: input.category_list, '
' Value: [i in range(0, size(x_values) - 1) | [x_values[i], y_values[i]]], '
' Conflicts: conflicts '
' } '
' ORDER BY row_index '
' LIMIT 50 '
)
upload_table_property = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' trim(csvLine.person) as person, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toInteger(split(csvLine.uid, "_")[0]) '
' END as field_uid, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toUpper(csvLine.uid) '
' END as uid, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
' MATCH '
' (field:Field { '
' uid: field_uid '
' }), '
' (item: Item { '
' uid: uid '
' }) '
' UNWIND $inputs as input_name '
' MATCH '
' (:RecordType {'
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(item_level: ItemLevel { '
' name_lower: level '
' }) '
# Check for data in table
' WHERE trim(csvLine[input_name]) <> "" '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' csvLine[input_name] as value '
' FOREACH (n in CASE '
' WHEN level = "field" '
' THEN [1] ELSE [] END | '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput :FieldInput)-[: FOR_INPUT]->(input) '
' ) '
' FOREACH (n in CASE '
' WHEN level in ["block", "tree", "sample"] '
' THEN [1] ELSE [] END | '
' MERGE '
' (field)<-[: FROM_FIELD]-(field_input: FieldInput)-[: FOR_INPUT]->(input) '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput)-[: FOR_INPUT]->(field_input) '
' ) '
' WITH '
' field, '
' item, '
' input, '
' person, '
+ upload_check_value +
' AS value '
' WHERE value IS NOT NULL '
# get the user submission tracking nodes
' MATCH '
' (:User { '
' username_lower : toLower(trim($username))'
' }) '
' -[: SUBMITTED]->(: Submissions) '
' -[: SUBMITTED]->(data_sub: Records) '
# and the item/input node
' MATCH '
' (item) '
' <-[: FOR_ITEM]-(item_input: ItemInput) '
' -[ :FOR_INPUT*..2]->(input) '
# and the field/input node
# todo consider the model here, this is an undirected match with two labels, not super happy with this one,
# todo would it be better to have a redundant ItemInput node for fields?
' MATCH (item) '
' -[:FOR_ITEM | FOR_INPUT*..2]-(field_input: FieldInput) '
' -[:FOR_INPUT]->(input) '
' MERGE '
' (r: Record) '
' -[: RECORD_FOR]->(item_input) '
' ON MATCH SET '
' r.found = True '
' ON CREATE SET '
' r.found = False, '
' r.person = person, '
' r.value = CASE '
' WHEN input.format <> "multicat" THEN value '
' ELSE extract(i in FILTER (n in split(value, ":") WHERE size(n) > 0 )| toLower(trim(i)))'
' END '
# additional statements to occur when new data point
' FOREACH (n IN CASE '
' WHEN r.found = False '
' THEN [1] ELSE [] END | '
# track user submissions through /User/FieldInput container
' MERGE '
' (data_sub)'
' -[:SUBMITTED]->(uff:UserFieldInput) '
' -[:CONTRIBUTED]->(field_input) '
# then finally the data with a timestamp
' MERGE '
' (uff)-[s1:SUBMITTED]->(r) '
' ON CREATE SET '
' s1.time = datetime.transaction().epochMillis '
' ) '
' WITH '
' field, '
' item, '
' input, '
' value, '
' r '
' MATCH '
' (partner:Partner) '
' <-[:AFFILIATED {data_shared: True}]-(user:User) '
' -[:SUBMITTED]->(:Submissions) '
' -[:SUBMITTED]->(:Records) '
' -[:SUBMITTED]->(:UserFieldInput) '
' -[submitted:SUBMITTED]->(r) '
# need to check for permissions for values that didn't merge to provide filtered feedback
# and optionally roll back if existing records overlap without access confirmed.
' OPTIONAL MATCH '
' (partner)<-[access: AFFILIATED {confirmed: True}]-(:User {username_lower:toLower(trim($username))}) '
# And give the user feedback on their submission
' RETURN { '
' Found: r.found, '
' `Submitted by`: CASE WHEN access IS NOT NULL THEN user.name ELSE partner.name END, '
' `Submitted at`: submitted.time, '
' Value: CASE '
' WHEN NOT r.found '
' THEN r.value '
' WHEN access IS NOT NULL '
' THEN r.value '
' ELSE "ACCESS DENIED" '
' END, '
' `Uploaded value`: value, '
' Access: CASE WHEN access IS NULL THEN False ELSE True END, '
' UID: item.uid, '
' `Input variable`: input.name, '
' Partner: partner.name '
' } '
' ORDER BY input.name_lower, field.uid, item.id '
)
upload_table_trait = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' trim(csvLine.person) as person, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toInteger(split(csvLine.uid, "_")[0]) '
' END as field_uid, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 0) as replicate, '
# time from date and time
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.date, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.date, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.time, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.time, " ", "") '
' ELSE '
' "12:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as time, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
# And identify the fields and input variables assessed
' MATCH '
' (field:Field { '
' uid: field_uid '
' }), '
' (item: Item { '
' uid: uid '
' }) '
' UNWIND $inputs as input_name '
' MATCH '
' (:RecordType {'
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(item_level: ItemLevel { '
' name_lower: level '
' }) '
# Check for data in table
' WHERE trim(csvLine[input_name]) <> "" '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' time, '
' replicate, '
' csvLine[input_name] as value, '
# to allow differentiation of defaulted time and set time
' csvLine.time as text_time '
# for trait data if no time is set then drop the row
' WHERE '
' time IS NOT NULL '
' FOREACH (n in CASE '
' WHEN level = "field" '
' THEN [1] ELSE [] END | '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput :FieldInput)-[: FOR_INPUT]->(input) '
' ) '
' FOREACH (n in CASE '
' WHEN level in ["block", "tree", "sample"] '
' THEN [1] ELSE [] END | '
' MERGE '
' (field)<-[: FROM_FIELD]-(field_input: FieldInput)-[: FOR_INPUT]->(input) '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput)-[: FOR_INPUT]->(field_input) '
' ) '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' time, '
' replicate, '
' text_time, '
+ upload_check_value +
' AS value '
' WHERE value IS NOT NULL '
# get the user submission tracking nodes
' MATCH '
' (:User { '
' username_lower : toLower(trim($username))'
' }) '
' -[: SUBMITTED]->(: Submissions) '
' -[: SUBMITTED]->(data_sub: Records) '
# and the item/input node
' MATCH '
' (item) '
' <-[: FOR_ITEM]-(item_input: ItemInput)'
' -[ :FOR_INPUT*..2]->(input) '
# and the field/input node
# todo consider the model here, this is an undirected match with two labels, not super happy with this one,
# todo would it be better to have a redundant ItemInput node for fields?
' MATCH (item) '
' -[:FOR_ITEM | FOR_INPUT*..2]-(field_input: FieldInput) '
' -[:FOR_INPUT]->(input) '
' MERGE '
' (r: Record { '
' time : time, '
' replicate: replicate '
' }) '
' -[:RECORD_FOR]->(item_input) '
' ON MATCH SET '
' r.found = True '
' ON CREATE SET '
' r.found = False, '
' r.person = person, '
' r.text_time = text_time, '
' r.value = CASE '
' WHEN input.format <> "multicat" THEN value '
' ELSE extract(i in FILTER (n in split(value, ":") WHERE size(n) > 0 )| toLower(trim(i)))'
' END '
# additional statements to occur when new data point
' FOREACH (n IN CASE '
' WHEN r.found = False '
' THEN [1] ELSE [] END | '
# track user submissions through /User/FieldInput container
' MERGE '
' (data_sub)'
' -[:SUBMITTED]->(uff:UserFieldInput) '
' -[:CONTRIBUTED]->(field_input) '
# then finally the data with a timestamp
' MERGE '
' (uff)-[s1:SUBMITTED]->(r) '
' ON CREATE SET '
' s1.time = datetime.transaction().epochMillis '
' ) '
' WITH '
' field, '
' item, '
' input, '
' value, '
' r '
' MATCH '
' (partner:Partner) '
' <-[:AFFILIATED {data_shared: True}]-(user:User) '
' -[:SUBMITTED]->(:Submissions) '
' -[:SUBMITTED]->(:Records) '
' -[:SUBMITTED]->(:UserFieldInput) '
' -[submitted:SUBMITTED]->(r) '
# need to check for permissions for values that didn't merge to provide filtered feedback
# and optionally roll back if existing records overlap without access confirmed.
' OPTIONAL MATCH '
' (partner)<-[access: AFFILIATED {confirmed: True}]-(:User {username_lower:toLower(trim($username))}) '
# And give the user feedback on their submission
' RETURN { '
' Found: r.found, '
' `Submitted by`: CASE WHEN access IS NOT NULL THEN user.name ELSE partner.name END, '
' `Submitted at`: submitted.time, '
' Value: CASE '
' WHEN NOT r.found '
' THEN r.value '
' WHEN access IS NOT NULL '
' THEN r.value '
' ELSE "ACCESS DENIED" '
' END, '
' `Uploaded value`: value, '
' Access: CASE WHEN access IS NULL THEN False ELSE True END, '
' Replicate: r.replicate, '
' Time: r.time, '
' UID: item.uid, '
' `Input variable`: input.name, '
' Partner: partner.name '
' } '
' ORDER BY input.name_lower, field.uid, item.id, r.replicate '
)
upload_table_curve = (
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' [ '
' key in keys(csvLine) WHERE toFloat(key) in $x_values AND toFloat(csvLine[key]) <> "" '
' | [toFloat(key), toFloat(csvLine[key])]'
' ] as x_y_list '
' UNWIND x_y_list as x_y '
' WITH '
' csvLine, '
' x_y '
' ORDER BY x_y '
' WITH '
' csvLine, '
' collect(x_y[0]) as x_values, '
' collect(x_y[1]) as y_values '
' WITH '
' csvLine, '
' x_values, '
' y_values, '
' trim(csvLine.person) as person, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toInteger(split(csvLine.uid, "_")[0]) '
' END as field_uid, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 0) as replicate, '
# time from date and time
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.date, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.date, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.date, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.date, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.time, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.time, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.time, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.time, " ", "") '
' ELSE '
' "12:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as time, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level '
# And identify the fields and input variable assessed
' MATCH '
' (field:Field { '
' uid: field_uid '
' }), '
' (item: Item { '
' uid: uid '
' }) '
' MATCH '
' (:RecordType {'
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower($input_name) '
' })-[:AT_LEVEL]->(item_level: ItemLevel { '
' name_lower: level '
' }) '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' time, '
' replicate, '
' x_values, '
' y_values, '
# to allow differentiation of defaulted time and set time
' csvLine.time as text_time '
# for trait data if no time is set then drop the row
' WHERE '
' time IS NOT NULL '
' FOREACH (n in CASE '
' WHEN level = "field" '
' THEN [1] ELSE [] END | '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput :FieldInput)-[: FOR_INPUT]->(input) '
' ) '
' FOREACH (n in CASE '
' WHEN level in ["block", "tree", "sample"] '
' THEN [1] ELSE [] END | '
' MERGE '
' (field)<-[: FROM_FIELD]-(field_input: FieldInput)-[: FOR_INPUT]->(input) '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput)-[: FOR_INPUT]->(field_input) '
' ) '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' time, '
' replicate, '
' text_time, '
' x_values, '
' y_values '
' WHERE size(y_values) > 0 '
# get the user submission tracking nodes
' MATCH '
' (:User { '
' username_lower : toLower(trim($username))'
' }) '
' -[: SUBMITTED]->(: Submissions) '
' -[: SUBMITTED]->(data_sub: Records) '
# and the item/input node
' MATCH '
' (item) '
' <-[: FOR_ITEM]-(item_input: ItemInput)'
' -[ :FOR_INPUT*..2]->(input) '
# and the field/input node
# todo consider the model here, this is an undirected match with two labels, not super happy with this one,
# todo would it be better to have a redundant ItemInput node for fields?
' MATCH (item) '
' -[:FOR_ITEM | FOR_INPUT*..2]-(field_input: FieldInput) '
' -[:FOR_INPUT]->(input) '
' MERGE '
' (r: Record { '
' time : time, '
' replicate: replicate, '
' x_values: x_values '
' }) '
' -[:RECORD_FOR]->(item_input) '
' ON MATCH SET '
' r.found = True '
' ON CREATE SET '
' r.found = False, '
' r.person = person, '
' r.text_time = text_time, '
' r.y_values = y_values '
# additional statements to occur when new data point
' FOREACH (n IN CASE '
' WHEN r.found = False '
' THEN [1] ELSE [] END | '
# track user submissions through /User/FieldInput container
' MERGE '
' (data_sub)'
' -[:SUBMITTED]->(uff:UserFieldInput) '
' -[:CONTRIBUTED]->(field_input) '
# then finally the data with a timestamp
' MERGE '
' (uff)-[s1:SUBMITTED]->(r) '
' ON CREATE SET '
' s1.time = datetime.transaction().epochMillis '
' ) '
' WITH '
' field, '
' item, '
' input, '
' x_values, '
' y_values, '
' r '
' MATCH '
' (partner:Partner) '
' <-[:AFFILIATED {data_shared: True}]-(user:User) '
' -[:SUBMITTED]->(:Submissions) '
' -[:SUBMITTED]->(:Records) '
' -[:SUBMITTED]->(:UserFieldInput) '
' -[submitted:SUBMITTED]->(r) '
# need to check for permissions for values that didn't merge to provide filtered feedback
# and optionally roll back if existing records overlap without access confirmed.
' OPTIONAL MATCH '
' (partner)<-[access: AFFILIATED {confirmed: True}]-(:User {username_lower:toLower(trim($username))}) '
# And give the user feedback on their submission
' RETURN { '
' Found: r.found, '
' `Submitted by`: CASE WHEN access IS NOT NULL THEN user.name ELSE partner.name END, '
' `Submitted at`: submitted.time, '
' Value: CASE '
' WHEN NOT r.found '
' THEN [i in range(0, size(r.x_values) - 1) | [r.x_values[i], r.y_values[i]]] '
' WHEN access IS NOT NULL '
' THEN [i in range(0, size(r.x_values) - 1) | [r.x_values[i], r.y_values[i]]] '
' ELSE "ACCESS DENIED" '
' END, '
' `Uploaded value`: [i in range(0, size(x_values) - 1) | [x_values[i], y_values[i]]], '
' Access: CASE WHEN access IS NULL THEN False ELSE True END, '
' Replicate: r.replicate, '
' Time: r.time, '
' UID: item.uid, '
' Input: input.name, '
' Partner: partner.name '
' } '
' ORDER BY input.name_lower, field.uid, item.id, r.replicate '
)
upload_table_condition = (
# load in the csv
' LOAD CSV WITH HEADERS FROM $filename as csvLine '
' WITH '
' csvLine, '
' trim(csvLine.person) as person, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN toInteger(csvLine.uid) '
' ELSE '
' toInteger(split(csvLine.uid, "_")[0]) '
' END as field_uid, '
' CASE '
' WHEN size(split(split(csvLine.uid, ".")[0], "_")) = 1 '
' THEN toInteger(split(csvLine.uid, ".")[0]) '
' ELSE '
' toUpper(split(csvLine.uid, ".")[0]) '
' END as uid, '
' coalesce(toInteger(split(trim(toUpper(csvLine.uid)), ".")[1]), 0) as replicate, '
' CASE '
' WHEN size(split(csvLine.uid, "_")) = 1 '
' THEN "field" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "B" '
' THEN "block" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "T" '
' THEN "tree" '
' WHEN toUpper(left(split(csvLine.uid, "_")[1],1)) = "S" '
' THEN "sample" '
' END as level, '
# start time from start date and start time
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.`start date`, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.`start date`, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.`start date`, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.`start date`, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.`start time`, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.`start time`, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.`start time`, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.`start time`, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.`start time`, " ", "") '
' ELSE '
' "00:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as start, '
# end time from end date and end time
' apoc.date.parse( '
' CASE '
' WHEN size(split(replace(csvLine.`end date`, " ", ""), "-")) = 3 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[0]) = 4 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[1]) <=2 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[1]) >=1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[1]) >= 1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[1]) <= 12 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[2]) <=2 '
' AND size(split(replace(csvLine.`end date`, " ", ""), "-")[2]) >=1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[2]) >= 1 '
' AND toInteger(split(replace(csvLine.`end date`, " ", ""), "-")[2]) <= 31 '
' THEN '
' replace(csvLine.`end date`, " ", "") '
' ELSE '
' Null '
' END '
' + " " + '
' CASE '
' WHEN size(split(replace(csvLine.`end time`, " ", ""), ":")) = 2 '
' AND size(split(replace(csvLine.`end time`, " ", ""), ":")[0]) <= 2 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[0]) <=24 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[0]) >= 0 '
' AND size(split(replace(csvLine.`end time`, " ", ""), ":")[1]) <= 2 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[1]) <=60 '
' AND toInteger(split(replace(csvLine.`end time`, " ", ""), ":")[1]) >=0 '
' THEN '
' replace(csvLine.`end time`, " ", "") '
' ELSE '
' "24:00" '
' END '
' , "ms", "yyyy-MM-dd HH:mm") as end '
# And identify the fields and inputs assessed
' MATCH '
' (field:Field { '
' uid: field_uid '
' }), '
' (item: Item { '
' uid: uid '
' }) '
' UNWIND $inputs as input_name '
' MATCH '
' (:RecordType {'
' name_lower: $record_type '
' }) '
' <-[:OF_TYPE]-(input: Input { '
' name_lower: toLower(input_name) '
' })-[:AT_LEVEL]->(item_level:ItemLevel { '
' name_lower: level '
' }) '
# Check for data in table
' WHERE trim(csvLine[input_name]) <> "" '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' start, end, '
' csvLine[input_name] as value, '
# to allow differentiation of defaulted time and set time
' csvLine.`start time` as text_start_time, '
' csvLine.`end time` as text_end_time '
' FOREACH (n in CASE '
' WHEN level = "field" '
' THEN [1] ELSE [] END | '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput :FieldInput)-[: FOR_INPUT]->(input) '
' ) '
' FOREACH (n in CASE '
' WHEN level in ["block", "tree", "sample"] '
' THEN [1] ELSE [] END | '
' MERGE '
' (field)<-[: FROM_FIELD]-(field_input: FieldInput)-[: FOR_INPUT]->(input) '
' MERGE '
' (item)<-[: FOR_ITEM]-(:ItemInput)-[: FOR_INPUT]->(field_input) '
' ) '
' WITH '
' field, '
' item, '
' input, '
' level, '
' person, '
' start, end, '
' text_start_time, text_end_time, '
+ upload_check_value +
' AS value '
' WHERE value IS NOT NULL '
# get the user submission tracking nodes
' MATCH '
' (:User { '
' username_lower : toLower(trim($username))'
' }) '
' -[: SUBMITTED]->(: Submissions) '
' -[: SUBMITTED]->(data_sub: Records) '
# and the item/input node
' MATCH '
' (item) '
' <-[: FOR_ITEM]-(item_input: ItemInput)'
' -[ :FOR_INPUT*..2]->(input) '
# and the field/input node
# todo consider the model here, this is an undirected match with two labels, not super happy with this one,
# todo would it be better to have a redundant ItemInput node for fields?
' MATCH (item) '
' -[:FOR_ITEM | FOR_INPUT*..2]-(field_input: FieldInput) '
' -[:FOR_INPUT]->(input) '
' MERGE '
' (r: Record { '
' start : CASE WHEN start IS NOT NULL THEN start ELSE False END, '
' end : CASE WHEN end IS NOT NULL THEN end ELSE False END '
' }) '
' -[:RECORD_FOR]->(item_input) '
' ON MATCH SET '
' r.found = True '
' ON CREATE SET '
' r.found = False, '
' r.person = person, '
' r.text_start_time = text_start_time, '
' r.text_end_time = text_end_time, '
' r.value = CASE '
' WHEN input.format <> "multicat" THEN value '
' ELSE extract(i in FILTER (n in split(value, ":") WHERE size(n) > 0 )| toLower(trim(i)))'
' END '
# additional statements to occur when new data point
' FOREACH (n IN CASE '
' WHEN r.found = False '
' THEN [1] ELSE [] END | '
# track user submissions through /User/FieldInput container
' MERGE '
' (data_sub)'
' -[:SUBMITTED]->(uff:UserFieldInput) '
' -[:CONTRIBUTED]->(field_input) '
# then finally the data with a timestamp
' MERGE '
' (uff)-[s1:SUBMITTED]->(r) '
' ON CREATE SET '
' s1.time = datetime.transaction().epochMillis '
' ) '
' WITH '
' field, '
' item, '
' input, '
' item_input, '
' value, '
' r, '
' start, end '
' MATCH '
' (partner:Partner) '
' <-[:AFFILIATED {data_shared: True}]-(user:User) '
' -[:SUBMITTED]->(:Submissions) '
' -[:SUBMITTED]->(:Records) '
' -[:SUBMITTED]->(:UserFieldInput) '
' -[submitted:SUBMITTED]->(r) '
# need to check for permissions for values that didn't merge to provide filtered feedback
# and optionally roll back if existing records overlap without access confirmed.
' OPTIONAL MATCH '
' (partner)<-[access: AFFILIATED {confirmed: True}]-(:User {username_lower:toLower(trim($username))}) '
# check again for conflicts - in case there have been concurrent submissions
# or there are conflicts within the uploaded table
' OPTIONAL MATCH '
' (r)'
' -[:RECORD_FOR]->(item_input) '
' <-[:RECORD_FOR]-(rr:Record) '
' <-[rr_sub:SUBMITTED]-(:UserFieldInput) '
' <-[:SUBMITTED]-(:Records) '
' <-[:SUBMITTED]-(:Submissions) '
' <-[:SUBMITTED]-(rr_user:User) '
' -[:AFFILIATED {data_shared: True}]->(rr_partner:Partner) '
' WHERE '
' ( '
# handle fully bound records
# - any overlapping records
' CASE WHEN rr.start <> False THEN rr.start ELSE Null END < end '
' AND '
' CASE WHEN rr.end <> False THEN rr.end ELSE Null END > start '
' ) OR ( '
# - a record that has a lower bound in the bound period
' CASE WHEN rr.start <> False THEN rr.start ELSE Null END >= start '
' AND '
' CASE WHEN rr.start <> False THEN rr.start ELSE Null END < end '
' ) OR ( '
# - a record that has an upper bound in the bound period
' CASE WHEN rr.end <> False THEN rr.end ELSE Null END > start '
' AND '
' CASE WHEN rr.end <> False THEN rr.end ELSE Null END <= end '
' ) OR ( '
# now handle lower bound only records
' end IS NULL '
' AND ( '
# - existing bound period includes start
' CASE WHEN rr.end <> False THEN rr.end ELSE Null END > start '
' AND '
' CASE WHEN rr.start <> False THEN rr.start ELSE Null END <= start '
# - record with same lower bound
' ) OR ( '
' rr.start = start '
# - record with upper bound only greater than this lower bound
' ) OR ( '
' rr.start = False '
' AND '
' CASE WHEN rr.end <> False THEN rr.end ELSE Null END > start '
' ) '
' ) OR ( '
# now handle upper bound only records
' start IS NULL '
' AND ( '
# - existing bound period includes end
' CASE WHEN rr.end <> False THEN rr.end ELSE Null END >= end '
' AND '
' CASE WHEN rr.start <> False THEN rr.start ELSE Null END < end '
# - record with same upper bound
' ) OR ( '
' rr.end = end '
# - record with lower bound only less than this upper bound
' ) OR ( '
' rr.end = False '
' AND '
' CASE WHEN rr.start <> False THEN rr.start ELSE Null END < end '
' ) '
' ) OR ( '
# always conflict with unbound records
' rr.end = False '
' AND '
' rr.start = False '
' )'
' OPTIONAL MATCH '
' (rr_partner) '
' <-[rr_access: AFFILIATED {confirmed: True}]-(:User {username_lower: toLower(trim($username))}) '
# If don't have access or if have access and values don't match then potential conflict
# time parsing to allow various degrees of specificity in the relevant time range is below
' WITH '
' r, '
' access, '
' user, '
' partner, '
' value, '
' submitted, '
' item, '
' field, '
' input, '
' case WHEN rr IS NOT NULL AND (rr.value <> r.value OR rr_access IS NULL) THEN '
' collect(DISTINCT { '
' start: rr.start, '
' end: rr.end, '
' existing_value: CASE WHEN rr_access IS NOT NULL THEN toString(rr.value) ELSE "ACCESS DENIED" END, '
' `submitted at`: rr_sub.time, '
' user: CASE WHEN rr_access IS NOT NULL THEN rr_user.name ELSE rr_partner.name END, '
' access: CASE WHEN rr_access IS NOT NULL THEN True ELSE False END '
' }) '
' ELSE Null END as conflicts '
# And give the user feedback on their submission
' RETURN { '
' Found: r.found, '
' `Submitted by`: CASE WHEN access IS NOT NULL THEN user.name ELSE partner.name END, '
' `Submitted at`: submitted.time, '
' Value: CASE '
' WHEN NOT r.found '
' THEN r.value '
' WHEN access IS NOT NULL '
' THEN r.value '
' ELSE "ACCESS DENIED" '
' END, '
' `Uploaded value`: value, '
' Access: CASE WHEN access IS NULL THEN False ELSE True END, '
' Period: [r.start, r.end], '
' UID: item.uid, '
' `Input variable`: input.name, '
' Partner: partner.name, '
' Conflicts: conflicts '
' } '
' ORDER BY input.name_lower, field.uid, item.id '
)
get_fields_treecount = (
' MATCH (country:Country)<-[:IS_IN]-(region: Region) '
' OPTIONAL MATCH (region)<-[:IS_IN]-(farm: Farm) '
' OPTIONAL MATCH (farm)<-[:IS_IN]-(field: Field) '
' OPTIONAL MATCH '
' (field)'
' <-[:IS_IN]-(:FieldTrees)'
' <-[:FOR]-(field_tree_counter:Counter {name:"tree"}) '
' OPTIONAL MATCH '
' (field)'
' <-[:IS_IN*2]-(block:Block)'
' <-[:IS_IN]-(:BlockTrees)'
' <-[:FOR]-(block_tree_counter:Counter {name:"tree"}) '
' WITH '
' country, '
' region, '
' farm, '
' field, '
' field_tree_counter.count as field_trees, '
' {'
' name: block.name, '
' label:"Block", '
' treecount: block_tree_counter.count '
' } as blocks, '
' block_tree_counter.count as block_trees '
' WITH '
' country, '
' region, '
' farm, '
' { '
' name: field.name, '
' label:"Field", '
' treecount: field_trees - sum(block_trees), '
' children: FILTER(block IN collect(blocks) WHERE block["name"] IS NOT NULL)'
' } as fields '
' WITH '
' country, '
' region, '
' {'
' name: farm.name, '
' label: "Farm", '
' children: FILTER(field IN collect(fields) WHERE field["name"] IS NOT NULL)'
' } as farms '
' WITH '
' country, '
' {'
' name: region.name, '
' label:"Region", '
' children: FILTER(farm IN collect(farms) WHERE farm["name"] IS NOT NULL)'
' } as regions '
' WITH '
' {'
' name: country.name, '
' label:"Country", '
' children: FILTER(region IN collect (regions) WHERE region["name"] IS NOT NULL)'
' } as countries '
' RETURN countries '
)
get_submissions_range = (
# first get all the data collections and link to a base node formed from field
' MATCH '
' (:User {username_lower: toLower($username)}) '
' -[:SUBMITTED*3]->(uff:UserFieldInput) '
' -[s:SUBMITTED]->(record: Record) '
' -[:RECORD_FOR]->(), '
' (uff)-[:CONTRIBUTED]->(ff:FieldInput) '
' -[:FROM_FIELD]->(field: Field), '
' (ff)-[:FOR_INPUT]->(input: Input) '
' WHERE s.time >= $starttime AND s.time <= $endtime '
' WITH '
' input, count(record) as record_count, field '
' RETURN '
' "Input" as d_label, '
' input.name + " (" + toString(record_count) + ")" as d_name, '
' id(field) + "_" + id(input) as d_id, '
' "Field" as n_label, '
' field.name as n_name,'
' id(field) as n_id, '
' "FROM" as r_type, '
' id(field) + "_" + id(input) + "_rel" as r_id, '
' id(field) + "_" + id(input) as r_start, '
' id(field) as r_end '
' UNION '
# get users farm context
' MATCH '
' (:User {username_lower: toLower($username)}) '
' -[:SUBMITTED*3]->(:UserFieldInput) '
' -[:CONTRIBUTED]->(: FieldInput) '
' -[:FOR_ITEM | FROM_FIELD]->(field:Field) '
' -[:IS_IN]->(farm:Farm) '
' RETURN '
' "Field" as d_label, '
' field.name as d_name, '
' id(field) as d_id, '
' "Farm" as n_label, '
' farm.name as n_name, '
' id(farm) as n_id, '
' "IS_IN" as r_type, '
' (id(field) + "_" + id(farm)) as r_id, '
' id(field) as r_start, '
' id(farm) as r_end'
' UNION '
# link the above into region context
' MATCH '
' (:User {username_lower: toLower($username)}) '
' -[:SUBMITTED*3]->(:UserFieldInput) '
' -[:CONTRIBUTED]->(: FieldInput) '
' -[:FOR_ITEM | FROM_FIELD]->(:Field) '
' -[:IS_IN]->(farm: Farm) '
' -[:IS_IN]->(region: Region) '
' RETURN '
' "Farm" as d_label, '
' farm.name as d_name, '
' id(farm) as d_id, '
' "Region" as n_label, '
' region.name as n_name, '
' id(region) as n_id, '
' "IS_IN" as r_type, '
' (id(farm) + "_" + id(region)) as r_id, '
' id(farm) as r_start, '
' id(region) as r_end'
' UNION '
# link the above into country context
' MATCH '
' (:User {username_lower: toLower($username)}) '
' -[:SUBMITTED*3]->(:UserFieldInput) '
' -[:CONTRIBUTED]->(: FieldInput) '
' -[:FOR_ITEM | FROM_FIELD]->(: Field) '
' -[:IS_IN]->(: Farm) '
' -[:IS_IN]->(region: Region) '
' -[:IS_IN]->(country: Country) '
' RETURN '
' "Region" as d_label, '
' region.name as d_name, '
' id(region) as d_id, '
' "Country" as n_label, '
' country.name as n_name, '
' id(country) as n_id, '
' "IS_IN" as r_type, '
' (id(region) + "_" + id(country)) as r_id, '
' id(region) as r_start, '
' id(country) as r_end'
)
|
gpl-3.0
| 6,791,217,323,624,032,000
| 29.951091
| 110
| 0.525838
| false
| 2.351317
| false
| false
| false
|
acgtun/acgtun.com
|
acgtun/leetcode/views.py
|
1
|
1338
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import sys
from collections import OrderedDict
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.conf import settings
from . import db_table
from database.database import Database
sys.path.append(os.path.join(settings.BASE_DIR, 'ommon'))
sys.path.append(os.path.join(settings.BASE_DIR, 'database'))
db_path = os.path.join(settings.BASE_DIR, 'database')
def get_solution(response):
db = Database(os.path.join(db_path, 'db.sqlite3'))
solutions = db.query("SELECT id,problem,cpptime,cppcode,javatime,javacode,pythontime,pythoncode FROM {}".format(
db_table.leetcode_solution_table))
problems = OrderedDict()
for r in solutions:
pn = r[1]
pn = pn.rstrip()
if pn not in problems.keys():
problems[pn] = OrderedDict()
problems[pn]['cpp'] = r[3]
problems[pn]['java'] = r[5]
problems[pn]['python'] = r[7]
problems = OrderedDict(sorted(problems.items(), key=lambda t: t[0]))
return response.write(render_to_string('leetcode/index.html', {'problems': problems}))
def index(request):
response = HttpResponse();
get_solution(response)
response.close()
return response
|
gpl-2.0
| -7,404,087,127,536,536,000
| 28.733333
| 116
| 0.683857
| false
| 3.558511
| false
| false
| false
|
jdilallo/jdilallo-test
|
examples/dfp/v201311/label_service/create_labels.py
|
1
|
1668
|
#!/usr/bin/python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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.
"""This code example creates new labels.
To determine which labels exist, run get_all_labels.py. This feature is only
available to DFP premium solution networks."""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
import uuid
# Import appropriate classes from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
label_service = client.GetService('LabelService', version='v201311')
# Create label objects.
labels = []
for _ in xrange(5):
label = {
'name': 'Label #%s' % uuid.uuid4(),
'isActive': 'true',
'types': ['COMPETITIVE_EXCLUSION']
}
labels.append(label)
# Add Labels.
labels = label_service.createLabels(labels)
# Display results.
for label in labels:
print ('Label with id \'%s\', name \'%s\', and types {%s} was found.'
% (label['id'], label['name'], ','.join(label['types'])))
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client)
|
apache-2.0
| -6,635,565,559,352,071,000
| 28.785714
| 77
| 0.681655
| false
| 3.723214
| false
| false
| false
|
cshinaver/cctools
|
umbrella/src/umbrella.py
|
1
|
188703
|
#!/usr/bin/env cctools_python
# CCTOOLS_PYTHON_VERSION 2.7 2.6
# All the vanilla python package dependencies of Umbrella can be satisfied by Python 2.6.
"""
Umbrella is a tool for specifying and materializing comprehensive execution environments, from the hardware all the way up to software and data. A user simply invokes Umbrella with the desired task, and Umbrella determines the minimum mechanism necessary to run the task, whether it be direct execution, a system container, a local virtual machine, or submission to a cloud or grid environment. We present the overall design of Umbrella and demonstrate its use to precisely execute a high energy physics application and a ray-tracing application across many platforms using a combination of Parrot, Chroot, Docker, VMware, Condor, and Amazon EC2.
Copyright (C) 2003-2004 Douglas Thain and the University of Wisconsin
Copyright (C) 2005- The University of Notre Dame
This software is distributed under the GNU General Public License.
See the file COPYING for details.
Implementation Logics of Different Execution Engines:
If the sandbox type is Parrot, create the mountlist file and set PARROT_MOUNT_FILE; set PATH; set PARROT_LDSO_PATH if a separate OS image is needed; parrotize the user's command into `parrot_run user_cmd`.
If the sandbox type is Docker, transfer the OS image into a Docker image; use volume to mount all the software and data dependencies into a container; set PATH; dockerize the user's command into `docker run user_cmd`. To use Docker, a separate OS image is needed.
If the sandbox type is chroot, create mountpoints for software and data dependencies inside the OS image directory and mount software and data into the OS image, set PATH, chrootize the user's command into `chroot user_cmd`.
Implementation Logic of Dependency Sources:
HTTP/HTTPS: Download the dependency into Umbrella local cache.
CVMFS: check whether the mountpoint already exists on the execution node, if yes, do not need to set mountpoint for this dependency and directly process the next dependency; if no, parrot will be used to deliver cvmfs for the application.
If Parrot is needed to access cvmfs, and the sandbox type is Parrot,
Do all the work mentioned above for Parrot execution engine + add SITEINFO into mountlist file.
If Parrot is needed to access cvmfs, and the sandbox type is Docker,
Do all the work mentioned above for Docker execution engine + add SITEINFO into mountlist file + parrotize the user's command. First parrotize the user's command, then dockerize the user's command.
If Parrot is needed to access cvmfs, and the sandbox type is chroot,
Do all the work mentioned above for chroot execution engine + add SITEINFO into mountlist file + parrotize the user's command. First parrotize the user's command, then chrootize the user's command.
ROOT: If the user expects the root file to be access at runtime without downloading. Umbrella does nothing if a ROOT file through ROOT protocol is needed, because ROOT supports data access during runtime without downloading first. Inside the umbrella specification file, the user only needs to specify the mount_env attribute.
If the user expects the root file to be downloaded first, then the user needs to specify both the mount_env and mountpoint attributes inside the umbrella specification.
Git: If the user's application needs git to do `git clone <repo_url>; git checkout <branch_name/commit_id>`, then the user does not need to specify mountpoint attribute inside the umbrella specification.
If the user's application does not explicitly require git, but umbrella tries to pull some dependencies from a remote git repository, then the user needs to specify both the mount_env and mountpoint attributes inside the umbrella specification.
mount_env and mountpoint:
If only mountpoint is set to A in a specification, the dependency will be downloaded into the umbrella local cache with the file path of D, and a new mountpoint will be added into mount_dict (mount_dict[A] = D).
If only mount_env is set to B in a specification, the dependency will not be downloaded, meta_search will be executed to get one remote storage location, C, of the dependency, a new environment variable will be set (env_para_dict[B] = C).
If mountpoint is set to A and mount_env is set to B in a specification, the dependency will be downloaded into the umbrella local cache with the file path of D, and a new mountpoint will be added into mount_dict (mount_dict[A] = D) and a new environment variable will also be set (env_para_dict[B] = A).
Local path inside the umbrella local cache:
Case 1: the dependency is delivered as a git repository through http/https/git protocol.
dest = os.path.dirname(sandbox_dir) + "/cache/" + git_commit + '/' + repo_name
Note: git_commit is optional in the metadata database. If git_commit is not specified in the metadata database, then:
dest = os.path.dirname(sandbox_dir) + "/cache/" + repo_name
Case 2: the dependency is delivered not as a git repository through http/https protocol.
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
Note: checksum is required to be specified in the metadata database. If it is not specified, umbrella will complain and exit.
Case 3: SITECONF info necessary for CVMFS cms repository access through Parrot. For this case, we use a hard-coded path.
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/SITECONF"
"""
import sys
from stat import *
from pprint import pprint
import subprocess
import platform
import re
import tarfile
import StringIO
from optparse import OptionParser
import os
import hashlib
import difflib
import sqlite3
import shutil
import datetime
import time
import getpass
import grp
import logging
import multiprocessing
import resource
import tempfile
import urllib
import gzip
import imp
found_requests = None
try:
imp.find_module('requests')
found_requests = True
import requests
import requests.packages.urllib3
except ImportError:
found_requests = False
found_boto3 = None
try:
imp.find_module('boto3')
found_boto3 = True
import boto3
except ImportError:
found_boto3 = False
found_botocore = None
try:
imp.find_module('botocore')
found_botocore = True
import botocore
except ImportError:
found_botocore = False
s3_url = 'https://s3.amazonaws.com'
if sys.version_info >= (3,):
import urllib.request as urllib2
import urllib.parse as urlparse
else:
import urllib2
import urlparse
if sys.version_info > (2,6,):
import json
else:
import simplejson as json #json module is introduce in python 2.4.3
#Replace the version of cctools inside umbrella is easy: set cctools_binary_version.
cctools_binary_version = "5.2.0"
cctools_dest = ""
#set cms_siteconf_url to be the url for the siteconf your application depends
#the url and format settings here should be consistent with the function set_cvmfs_cms_siteconf
cms_siteconf_url = "http://ccl.cse.nd.edu/research/data/hep-case-study/2efd5cbb3424fe6b4a74294c84d0fb43/SITECONF.tar.gz"
cms_siteconf_format = "tgz"
tempfile_list = [] #a list of temporary file created by umbrella and need to be removed before umbrella ends.
tempdir_list = [] #a list of temporary dir created by umbrella and need to be removed before umbrella ends.
pac_manager = {
"yum": ("-y install", "info")
}
"""
ec2 metadata
the instance types provided by ec2 are undergoing changes as time goes by.
"""
ec2_json = {
"redhat-6.5-x86_64": {
"ami-2cf8901c": {
"ami": "ami-2cf8901c",
"root_device_type": "ebs",
"virtualization_type": "paravirtual",
"user": "ec2-user"
},
"ami-0b5f073b": {
"ami": "ami-0b5f073b",
"root_device_type": "ebs",
"virtualization_type": "paravirtual",
"user": "ec2-user"
}
},
"centos-6.6-x86_64": {
"ami-0b06483b": {
"ami": "ami-0b06483b",
"root_device_type": "ebs",
"virtualization_type": "paravirtual",
"user": "root"
}
},
"redhat-5.10-x86_64": {
"ami-d76a29e7": {
"ami": "ami-d76a29e7",
"root_device_type": "ebs",
"virtualization_type": "hvm",
"user": "root"
}
}
}
upload_count = 0
def subprocess_error(cmd, rc, stdout, stderr):
"""Print the command, return code, stdout, and stderr; and then directly exit.
Args:
cmd: the executed command.
rc: the return code.
stdout: the standard output of the command.
stderr: standard error of the command.
Returns:
directly exit the program.
"""
cleanup(tempfile_list, tempdir_list)
sys.exit("`%s` fails with the return code of %d, \nstdout: %s, \nstderr: %s\n" % (cmd, rc, stdout, stderr))
def func_call(cmd):
""" Execute a command and return the return code, stdout, stderr.
Args:
cmd: the command needs to execute using the subprocess module.
Returns:
a tuple including the return code, stdout, stderr.
"""
logging.debug("Start to execute command: %s", cmd)
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = True)
(stdout, stderr) = p.communicate()
rc = p.returncode
logging.debug("returncode: %d\nstdout: %s\nstderr: %s", rc, stdout, stderr)
return (rc, stdout, stderr)
def func_call_withenv(cmd, env_dict):
""" Execute a command with a special setting of the environment variables and return the return code, stdout, stderr.
Args:
cmd: the command needs to execute using the subprocess module.
env_dict: the environment setting.
Returns:
a tuple including the return code, stdout, stderr.
"""
logging.debug("Start to execute command: %s", cmd)
logging.debug("The environment variables for executing the command is:")
logging.debug(env_dict)
p = subprocess.Popen(cmd, env = env_dict, stdout = subprocess.PIPE, shell = True)
(stdout, stderr) = p.communicate()
rc = p.returncode
logging.debug("returncode: %d\nstdout: %s\nstderr: %s", rc, stdout, stderr)
return (rc, stdout, stderr)
def which_exec(name):
"""The implementation of shell which command
Args:
name: the name of the executable to be found.
Returns:
If the executable is found, returns its fullpath.
If PATH is not set, directly exit.
Otherwise, returns None.
"""
if not os.environ.has_key("PATH"):
cleanup(tempfile_list, tempdir_list)
logging.critical("The environment variable PATH is not set!")
sys.exit("The environment variable PATH is not set!")
for path in os.environ["PATH"].split(":"):
fullpath = path + '/' + name
if os.path.exists(fullpath) and os.path.isfile(fullpath):
return fullpath
return None
def md5_cal(filename, block_size=2**20):
"""Calculate the md5sum of a file
Args:
filename: the name of the file
block_size: the size of each block
Returns:
If the calculation fails for any reason, directly exit.
Otherwise, return the md5 value of the content of the file
"""
try:
with open(filename, 'rb') as f:
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
except Exception as e:
cleanup(tempfile_list, tempdir_list)
logging.critical("Computing the checksum of %s fails: %s.", filename, e)
sys.exit("md5_cal(" + filename + ") failed.\n" + e)
def url_download(url, dest):
""" Download url into dest
Args:
url: the url needed to be downloaded.
dest: the path where the content from the url should be put.
Returns:
If the url is downloaded successfully, return None;
Otherwise, directly exit.
"""
logging.debug("Start to download %s to %s ...." % (url, dest))
urllib.urlretrieve(url, dest)
def dependency_download(name, url, checksum, checksum_tool, dest, format_remote_storage, action):
"""Download a dependency from the url and verify its integrity.
Args:
name: the file name of the dependency. If its format is plain text, then filename is the same with the archived name. If its format is tgz, the filename should be the archived name with the trailing .tgz/.tar.gz removed.
url: the storage location of the dependency.
checksum: the checksum of the dependency.
checksum_tool: the tool used to calculate the checksum, such as md5sum.
dest: the destination of the dependency where the downloaded dependency will be put.
format_remote_storage: the file format of the dependency, such as .tgz.
action: the action on the downloaded dependency. Options: none, unpack. "none" leaves the downloaded dependency at it is. "unpack" uncompresses the dependency.
Returns:
If the url is a broken link or the integrity of the downloaded data is bad, directly exit.
Otherwise, return None.
"""
print "Download software from %s into the umbrella local cache (%s)" % (url, dest)
logging.debug("Download software from %s into the umbrella local cache (%s)", url, dest)
dest_dir = os.path.dirname(dest)
dest_uncompress = dest #dest_uncompress is the path of the uncompressed-version dependency
if format_remote_storage == "plain":
filename = name
elif format_remote_storage == "tgz":
filename = "%s.tar.gz" % name
dest = os.path.join(dest_dir, filename) #dest is the path of the compressed-version dependency
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
if not os.path.exists(dest):
#download the dependency from the url
#this method currently will fail when the data size is larger than the memory size, use subprocess + wget can solve it
url_download(url, dest)
#if it exists, the uncompressed-version directory will be deleted first
if action == "unpack" and format_remote_storage != 'plain' and os.path.exists(dest_uncompress):
shutil.rmtree(dest_uncompress)
logging.debug("the uncompressed-version directory exists already, first delete it")
#calculate the checkusm of the compressed-version dependency
if checksum_tool == "md5sum":
local_checksum = md5_cal(dest)
logging.debug("The checksum of %s is: %s", dest, local_checksum)
if not local_checksum == checksum:
cleanup(tempfile_list, tempdir_list)
logging.critical("The version of %s is incorrect! Please first delete it and its unpacked directory!!", dest)
sys.exit("the version of " + dest + " is incorrect! Please first delete it and its unpacked directory!!\n")
elif not checksum_tool:
logging.debug("the checksum of %s is not provided!", url)
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s is not supported currently!", checksum_tool)
sys.exit(checksum_tool + "is not supported currently!")
#if the uncompressed-version dependency does not exist, uncompress the dependency
if action == "unpack" and (not os.path.exists(dest_uncompress)) and format_remote_storage == "tgz":
logging.debug("Uncompressing %s into %s ....", dest, dest_uncompress)
tfile = tarfile.open(dest, "r:gz")
tfile.extractall(dest_dir)
def extract_tar(src, dest, form):
"""Extract a tgz file from src to dest
Args:
src: the location of a tgz file
dest: the location where the uncompressed data will be put
form: the format the tarball. Such as: tar, tgz
Returns:
None
"""
if form == "tar":
tfile = tarfile.open(src, "r")
elif form == "tgz":
tfile = tarfile.open(src, "r:gz")
tfile.extractall(dest)
def meta_search(meta_json, name, id=None):
"""Search the metadata information of an dependency in the meta_json
First find all the items with the required name in meta_json.
Then find the right one whose id satisfied the requirement.
If no id parameter is problem, then the first matched one will be returned.
Args:
meta_json: the json object including all the metadata of dependencies.
name: the name of the dependency.
id: the id attribute of the dependency. Defaults to None.
Returns:
If one item is found in meta_json, return the item, which is a dictionary.
If no item satisfied the requirement on meta_json, directly exit.
"""
if meta_json.has_key(name):
if not id:
for item in meta_json[name]:
return meta_json[name][item]
else:
if meta_json[name].has_key(id):
return meta_json[name][id]
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("meta_json does not has <%s> with the id <%s>", name, id)
sys.exit("meta_json does not has <%s> with the id <%s>" % (name, id))
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("meta_json does not include %s", name)
sys.exit("meta_json does not include %s\n" % name)
def attr_check(name, item, attr, check_len = 0):
"""Check and obtain the attr of an item.
Args:
name: the name of the dependency.
item: an item from the metadata database
attr: an attribute
check_len: if set to 1, also check whether the length of the attr is > 0; if set to 0, ignore the length checking.
Returns:
If the attribute check is successful, directly return the attribute.
Otherwise, directly exit.
"""
logging.debug("check the %s attr of the following item:", attr)
logging.debug(item)
if item.has_key(attr):
if check_len == 1:
if len(item[attr]) <= 0:
cleanup(tempfile_list, tempdir_list)
logging.debug("The %s attr of the item is empty.", attr)
sys.exit("The %s attr of the item (%s) is empty." % (item, attr))
#when multiple options are available, currently the first one will be picked.
#we can add filter here to control the choice.
if attr == 'source':
return source_filter(item[attr], ['osf', 's3'], name)
else:
return item[attr][0]
else:
return item[attr]
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("This item doesn not have %s attr!", attr)
sys.exit("the item (%s) does not have %s attr!" % (item, attr))
def source_filter(sources, filters, name):
"""Filter the download urls of a dependency.
The reason why this filtering process is necessary is: some urls are not
accessible by the current umbrella runtime. For example, if some urls points to
OSF, but the execution node has no requests python package installed. In this
case, all the download urls pointing to OSF are ignored.
Args:
sources: a list of download urls
filters: a list of protocols which are not supported by the current umbrella runtime.
name: the name of the dependency.
Returns:
If all the download urls are not available, exit directly.
Otherwise, return the first available url.
"""
l = []
for s in sources:
filtered = 0
for item in filters:
if s[:len(item)] == item:
filtered = 1
break
if not filtered:
l.append(s)
if len(l) == 0:
return sources[0]
else:
return l[0]
def cctools_download(sandbox_dir, hardware_platform, linux_distro, action):
"""Download cctools
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
linux_distro: the linux distro. For Example: redhat6, centos6.
action: the action on the downloaded dependency. Options: none, unpack. "none" leaves the downloaded dependency at it is. "unpack" uncompresses the dependency.
Returns:
the path of the downloaded cctools in the umbrella local cache. For example: /tmp/umbrella_test/cache/d19376d92daa129ff736f75247b79ec8/cctools-4.9.0-redhat6-x86_64
"""
name = "cctools-%s-%s-%s" % (cctools_binary_version, hardware_platform, linux_distro)
source = "http://ccl.cse.nd.edu/software/files/%s.tar.gz" % name
global cctools_dest
cctools_dest = os.path.dirname(sandbox_dir) + "/cache/" + name
dependency_download(name, source, None, None, cctools_dest, "tgz", "unpack")
return cctools_dest
def set_cvmfs_cms_siteconf(sandbox_dir):
"""Download cvmfs SITEINFO and set its mountpoint.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
Returns:
cvmfs_cms_siteconf_mountpoint: a string in the format of '/cvmfs/cms.cern.ch/SITECONF/local <SITEINFO dir in the umbrella local cache>/local'
"""
dest = os.path.dirname(sandbox_dir) + "/cache/cms_siteconf/SITECONF"
dependency_download("SITECONF.tar.gz", cms_siteconf_url, "", "", dest, cms_siteconf_format, "unpack")
cvmfs_cms_siteconf_mountpoint = '/cvmfs/cms.cern.ch/SITECONF/local %s/local' % dest
return cvmfs_cms_siteconf_mountpoint
def is_dir(path):
"""Judge whether a path is directory or not.
If the path is a dir, directly return. Otherwise, exit directly.
Args:
path: a path
Returns:
None
"""
if os.path.isdir(path):
pass
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("%s is not a directory!", path)
sys.exit("%s is not a directory!" % path)
def git_dependency_download(repo_url, dest, git_branch, git_commit):
"""Prepare a dependency from a git repository.
First check whether dest exist or not: if dest exists, then checkout to git_branch and git_commit;
otherwise, git clone url, and then checkout to git_branch and git_commit.
Args:
repo_url: the url of the remote git repository
dest: the local directory where the git repository will be cloned into
git_branch: the branch name of the git repository
git_commit: the commit id of the repository
Returns:
dest: the local directory where the git repository is
"""
dest = remove_trailing_slashes(dest)
scheme, netloc, path, query, fragment = urlparse.urlsplit(repo_url)
repo_name = os.path.basename(path)
if repo_name[-4:] == '.git':
repo_name = repo_name[:-4]
dest = dest + '/' + repo_name
if os.path.exists(dest):
is_dir(dest)
else:
dir = os.path.dirname(dest)
if os.path.exists(dir):
is_dir(dir)
else:
os.makedirs(dir)
os.chdir(dir)
if dependency_check('git') == -1:
cleanup(tempfile_list, tempdir_list)
sys.exit("Git is not found!")
cmd = "git clone %s" % repo_url
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
os.chdir(dest)
if git_branch:
cmd = "git checkout %s" % git_branch
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
if git_commit:
cmd = "git checkout %s" % git_commit
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
return dest
def git_dependency_parser(item, repo_url, sandbox_dir):
"""Parse a git dependency
Args:
item: an item from the metadata database
repo_url: the url of the remote git repository
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
Returns:
dest: the path of the downloaded data dependency in the umbrella local cache.
"""
logging.debug("This dependency is stored as a git repository: ")
logging.debug(item)
git_branch = ''
if item.has_key("branch"):
git_branch = item["branch"]
git_commit = ''
if item.has_key("commit"):
git_commit = item["commit"]
dest = os.path.dirname(sandbox_dir) + "/cache/" + git_commit
dest = git_dependency_download(repo_url, dest, git_branch, git_commit)
return dest
def data_dependency_process(name, id, meta_json, sandbox_dir, action, osf_auth):
"""Download a data dependency
Args:
name: the item name in the data section
id: the id attribute of the processed dependency
meta_json: the json object including all the metadata of dependencies.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
action: the action on the downloaded dependency. Options: none, unpack. "none" leaves the downloaded dependency at it is. "unpack" uncompresses the dependency.
osf_auth: the osf authentication info including osf_username and osf_password.
Returns:
dest: the path of the downloaded data dependency in the umbrella local cache.
"""
item = meta_search(meta_json, name, id)
source = attr_check(name, item, "source", 1)
if source[:4] == 'git+':
dest = git_dependency_parser(item, source[4:], sandbox_dir)
elif source[:4] == 'osf+':
checksum = attr_check(name, item, "checksum")
form = attr_check(name, item, "format")
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
try:
logging.debug("Trying to download %s as a normal url ,,,", source)
dependency_download(name, source[4:], checksum, "md5sum", dest, form, action)
except:
logging.debug("Fails to download %s as a normal url ,,,", source)
if len(osf_auth) < 2:
cleanup(tempfile_list, tempdir_list)
logging.debug("Please use --osf_user and --osf_pass to specify your osf authentication info!")
sys.exit("Please use --osf_user and --osf_pass to specify your osf authentication info!")
if form == "tgz":
osf_download(osf_auth[0], osf_auth[1], source[4:], dest + ".tar.gz")
else:
osf_download(osf_auth[0], osf_auth[1], source[4:], dest)
dependency_download(name, dest, checksum, "md5sum", dest, form, action)
elif source[:3] == "s3+":
checksum = attr_check(name, item, "checksum")
form = attr_check(name, item, "format")
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
try:
logging.debug("Trying to download %s as a normal url ,,,", source)
dependency_download(name, source[3:], checksum, "md5sum", dest, form, action)
except:
logging.debug("Fails to download %s as a normal url ,,,", source)
if form == "tgz":
s3_download(source[3:], dest + ".tar.gz")
else:
s3_download(source[3:], dest)
dependency_download(name, dest, checksum, "md5sum", dest, form, action)
else:
checksum = attr_check(name, item, "checksum")
form = attr_check(name, item, "format")
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
dependency_download(name, source, checksum, "md5sum", dest, form, action)
return dest
def check_cvmfs_repo(repo_name):
""" Check whether a cvmfs repo is installed on the host or not
Args:
repo_name: a cvmfs repo name. For example: "/cvmfs/cms.cern.ch".
Returns:
If the cvmfs repo is installed, returns the string including the mountpoint of cvmfs cms repo. For example: "/cvmfs/cms.cern.ch".
Otherwise, return an empty string.
"""
logging.debug("Check whether a cvmfs repo is installed on the host or not")
cmd = "df -h|grep '^cvmfs'|grep "+ "'" + repo_name + "'" + "|rev| cut -d' ' -f1|rev"
rc, stdout, stderr = func_call(cmd)
if rc == 0:
return stdout
else:
return ''
def dependency_process(name, id, action, meta_json, sandbox_dir, osf_auth):
""" Process each explicit and implicit dependency.
Args:
name: the item name in the software section
id: the id attribute of the processed dependency
action: the action on the downloaded dependency. Options: none, unpack. "none" leaves the downloaded dependency at it is. "unpack" uncompresses the dependency.
meta_json: the json object including all the metadata of dependencies.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
osf_auth: the osf authentication info including osf_username and osf_password.
Returns:
mount_value: the actual storage path of one dependency.
"""
mount_value = ''
item = meta_search(meta_json, name, id)
source = attr_check(name, item, "source", 1)
logging.debug("%s is chosen to deliver %s", source, name)
if source[:4] == "git+":
dest = git_dependency_parser(item, source[4:], sandbox_dir)
mount_value = dest
cleanup(tempfile_list, tempdir_list)
sys.exit("this is git source, can not support")
elif source[:4] == "osf+":
checksum = attr_check(name, item, "checksum")
form = attr_check(name, item, "format")
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
#first download it as a normal url
try:
logging.debug("Trying to download %s as a normal url ,,,", source)
dependency_download(name, source[4:], checksum, "md5sum", dest, form, action)
except:
logging.debug("Fails to download %s as a normal url ,,,", source)
if len(osf_auth) < 2:
cleanup(tempfile_list, tempdir_list)
logging.debug("Please use --osf_user and --osf_pass to specify your osf authentication info!")
sys.exit("Please use --osf_user and --osf_pass to specify your osf authentication info!")
if form == "tgz":
osf_download(osf_auth[0], osf_auth[1], source[4:], dest + ".tar.gz")
else:
osf_download(osf_auth[0], osf_auth[1], source[4:], dest)
dependency_download(name, dest, checksum, "md5sum", dest, form, action)
mount_value = dest
elif source[:3] == "s3+":
checksum = attr_check(name, item, "checksum")
form = attr_check(name, item, "format")
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
try:
logging.debug("Trying to download %s as a normal url ,,,", source)
dependency_download(name, source[3:], checksum, "md5sum", dest, form, action)
except:
logging.debug("Fails to download %s as a normal url ,,,", source)
if form == "tgz":
s3_download(source[3:], dest + ".tar.gz")
else:
s3_download(source[3:], dest)
dependency_download(name, dest, checksum, "md5sum", dest, form, action)
mount_value = dest
elif source[:5] == "cvmfs":
pass
else:
checksum = attr_check(name, item, "checksum")
form = attr_check(name, item, "format")
dest = os.path.dirname(sandbox_dir) + "/cache/" + checksum + "/" + name
dependency_download(name, source, checksum, "md5sum", dest, form, action)
mount_value = dest
return mount_value
def env_parameter_init(hardware_spec, kernel_spec, os_spec):
""" Set the environment parameters according to the specification file.
Args:
hardware_spec: the hardware section in the specification for the user's task.
kernel_spec: the kernel section in the specification for the user's task.
os_spec: the os section in the specification for the user's task.
Returns:
a tuple including the requirements for hardware, kernel and os.
"""
hardware_platform = attr_check("hardware", hardware_spec, "arch").lower()
cpu_cores = 1
if hardware_spec.has_key("cores"):
cpu_cores = hardware_spec["cores"].lower()
memory_size = "1GB"
if hardware_spec.has_key("memory"):
memory_size = hardware_spec["memory"].lower()
disk_size = "1GB"
if hardware_spec.has_key("disk"):
disk_size = hardware_spec["disk"].lower()
kernel_name = attr_check("kernel", kernel_spec, "name").lower()
kernel_version = attr_check("kernel", kernel_spec, "version").lower()
kernel_version = re.sub('\s+', '', kernel_version).strip()
distro_name = attr_check("os", os_spec, "name").lower()
distro_version = attr_check("os", os_spec, "version").lower()
os_id = ''
if os_spec.has_key("id"):
os_id = os_spec["id"]
index = distro_version.find('.')
linux_distro = distro_name + distro_version[:index] #example of linux_distro: redhat6
return (hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version, linux_distro, distro_name, distro_version, os_id)
def compare_versions(v1, v2):
""" Compare two versions, the format of version is: X.X.X
Args:
v1: a version.
v2: a version.
Returns:
0 if v1 == v2; 1 if v1 is newer than v2; -1 if v1 is older than v2.
"""
list1 = v1.split('.')
list2 = v2.split('.')
for i in range(len(list1)):
list1[i] = int(list1[i])
for i in range(len(list2)):
list2[i] = int(list2[i])
if list1[0] == list2[0]:
if list1[1] == list2[1]:
if list1[2] == list2[2]:
return 0
elif list1[2] > list2[2]:
return 1
else:
return -1
elif list1[1] > list2[1]:
return 1
else:
return -1
elif list1[0] > list2[0]:
return 1
else:
return -1
def verify_kernel(host_kernel_name, host_kernel_version, kernel_name, kernel_version):
""" Check whether the kernel version of the host machine matches the requirement.
The kernel_version format supported for now includes: >=2.6.18; [2.6.18, 2.6.32].
Args:
host_kernel_name: the name of the OS kernel of the host machine.
host_kernel_version: the version of the kernel of the host machine.
kernel_name: the name of the required OS kernel (e.g., linux). Not case sensitive.
kernel_version: the version of the required kernel (e.g., 2.6.18).
Returns:
If the kernel version of the host machine matches the requirement, return None.
If the kernel version of the host machine does not match the requirement, directly exit.
"""
if host_kernel_name != kernel_name:
cleanup(tempfile_list, tempdir_list)
logging.critical("The required kernel name is %s, the kernel name of the host machine is %s!", kernel_name, host_kernel_name)
sys.exit("The required kernel name is %s, the kernel name of the host machine is %s!\n" % (kernel_name, host_kernel_name))
if kernel_version[0] == '[':
list1 = kernel_version[1:-1].split(',')
if compare_versions(host_kernel_version, list1[0]) >= 0 and compare_versions(host_kernel_version, list1[1]) <= 0:
logging.debug("The kernel version matches!")
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("The required kernel version is %s, the kernel version of the host machine is %s!", kernel_version, host_kernel_version)
sys.exit("The required kernel version is %s, the kernel version of the host machine is %s!\n" % (kernel_version, host_kernel_version))
elif kernel_version[0] == '>':
if compare_versions(host_kernel_version, kernel_version[2:]) >= 0:
logging.debug("The kernel version matches!")
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("The required kernel version is %s, the kernel version of the host machine is %s!", kernel_version, host_kernel_version)
sys.exit("The required kernel version is %s, the kernel version of the host machine is %s!\n" % (kernel_version, host_kernel_version))
elif kernel_version[0] == '<':
if compare_versions(host_kernel_version, kernel_version[2:]) <= 0:
logging.debug("The kernel version matches!")
else:
cleanup(tempfile_list, tempdir_list)
logging.debug("The required kernel version is %s, the kernel version of the host machine is %s!", kernel_version, host_kernel_version)
sys.exit("The required kernel version is %s, the kernel version of the host machine is %s!\n" % (kernel_version, host_kernel_version))
else: #the kernel version is a single value
if compare_versions(host_kernel_version, kernel_version[2:]) == 0:
logging.debug("The kernel version matches!")
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("The required kernel version is %s, the kernel version of the host machine is %s!", kernel_version, host_kernel_version)
sys.exit("The required kernel version is %s, the kernel version of the host machine is %s!\n" % (kernel_version, host_kernel_version))
def env_check(sandbox_dir, sandbox_mode, hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version):
""" Check the matching degree between the specification requirement and the host machine.
Currently check the following item: sandbox_mode, hardware platform, kernel, OS, disk, memory, cpu cores.
Other things needed to check: software, and data??
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
sandbox_mode: the execution engine.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
cpu_cores: the number of required cpus (e.g., 1).
memory_size: the memory size requirement (e.g., 2GB). Not case sensitive.
disk_size: the disk size requirement (e.g., 2GB). Not case sensitive.
kernel_name: the name of the required OS kernel (e.g., linux). Not case sensitive.
kernel_version: the version of the required kernel (e.g., 2.6.18).
Returns:
host_linux_distro: the linux distro of the host machine. For Example: redhat6, centos6.
"""
print "Execution environment checking ..."
if sandbox_mode not in ["docker", "destructive", "parrot"]:
cleanup(tempfile_list, tempdir_list)
logging.critical("Currently local execution engine only support three sandbox techniques: docker, chroot or parrot!")
sys.exit("Currently local execution engine only support three sandbox techniques: docker, chroot or parrot!\n")
uname_list = platform.uname() #format of uname_list: (system,node,release,version,machine,processor)
logging.debug("Hardware platform checking ...")
if hardware_platform != uname_list[4].lower():
cleanup(tempfile_list, tempdir_list)
logging.critical("The specification requires %s, but the local machine is %s", hardware_platform, uname_list[4].lower())
sys.exit("The specification requires " + hardware_platform + ", but the local machine is " + uname_list[4].lower() + "!\n")
logging.debug("CPU cores checking ...")
cpu_cores = int(cpu_cores)
host_cpu_cores = multiprocessing.cpu_count()
if cpu_cores > host_cpu_cores:
cleanup(tempfile_list, tempdir_list)
logging.critical("The specification requires %d cpu cores, but the local machine only has %d cores!", cpu_cores, host_cpu_cores)
sys.exit("The specification requires %d cpu cores, but the local machine only has %d cores!\n" % (cpu_cores, host_cpu_cores))
logging.debug("Memory size checking ...")
memory_size = re.sub('\s+', '', memory_size).strip()
memory_size = float(memory_size[:-2])
cmd = "free -tg|grep Total|sed 's/\s\+/ /g'|cut -d' ' -f2"
rc, stdout, stderr = func_call(cmd)
if rc != 0:
logging.critical("The return code is %d, memory check fail!", rc)
else:
host_memory_size = float(stdout)
if memory_size > host_memory_size:
cleanup(tempfile_list, tempdir_list)
logging.critical("The specification requires %.2f GB memory space, but the local machine only has %.2f GB free memory space!", memory_size, host_memory_size)
sys.exit("The specification requires %.2f GB memory space, but the local machine only has %.2f GB free memory space!" % (memory_size, host_memory_size))
logging.debug("Disk space checking ...")
disk_size = re.sub('\s+', '', disk_size).strip()
disk_size = float(disk_size[:-2])
st = os.statvfs(sandbox_dir)
free_disk = float(st.f_bavail * st.f_frsize) / (1024*1024*1024)
if disk_size > free_disk:
cleanup(tempfile_list, tempdir_list)
logging.critical("The specification requires %.2f GB disk space, but the local machine only has %.2f GB free disk space!", disk_size, free_disk)
sys.exit("The specification requires %.2f GB disk space, but the local machine only has %.2f GB free disk space!" % (disk_size, free_disk))
#check kernel
logging.debug("Kernel checking ...")
host_kernel_name = uname_list[0].lower()
index = uname_list[2].find('-')
host_kernel_version = uname_list[2][:index]
verify_kernel(host_kernel_name, host_kernel_version, kernel_name, kernel_version)
dist_list = platform.dist()
logging.debug("The hardware information of the local machine:")
logging.debug(dist_list)
#set host_linux_distro. Examples: redhat6, centos6.
#potential problem: maybe in the future, we need a finer control about the host_linux_distro, like redhat6.5, centos6.5.
arch_index = uname_list[2].find('ARCH')
host_linux_distro = None
if arch_index != -1:
host_linux_distro = 'arch'
else:
redhat_index = uname_list[2].find('el')
centos_index = uname_list[2].find('centos')
if redhat_index != -1:
dist_version = uname_list[2][redhat_index + 2]
if centos_index != -1 or dist_list[0].lower() == 'centos':
host_linux_distro = 'centos' + dist_version
else:
host_linux_distro = 'redhat' + dist_version
logging.debug("The OS distribution information of the local machine: %s", host_linux_distro)
return host_linux_distro
def parrotize_user_cmd(user_cmd, sandbox_dir, cwd_setting, linux_distro, hardware_platform, meta_json, cvmfs_http_proxy):
"""Modify the user's command into `parrot_run + the user's command`.
The cases when this function should be called: (1) sandbox_mode == parrot; (2) sandbox_mode != parrot and cvmfs is needed to deliver some dependencies not installed on the execution node.
Args:
user_cmd: the user's command.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
cwd_setting: the current working directory for the execution of the user's command.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
linux_distro: the linux distro. For Example: redhat6, centos6.
meta_json: the json object including all the metadata of dependencies.
cvmfs_http_proxy: HTTP_PROXY environmetn variable used to access CVMFS by Parrot
Returns:
None
"""
#Here we use the cctools meta from the local cache (which includes all the meta including cvmfs, globus, fuse and so on). Even if the user may install cctools by himself on the machine, the configuration of the local installation may be not what we want. For example, the user may just configure like this `./configure --prefix ~/cctools`.
#4.4 and 4.4 does not support --no-set-foreground feature.
#user_cmd[0] = dest + "/bin/parrot_run --no-set-foreground /bin/sh -c 'cd " + cwd_setting + "; " + user_cmd[0] + "'"
if cvmfs_http_proxy:
user_cmd[0] = "export HTTP_PROXY=" + cvmfs_http_proxy + "; " + cctools_dest + "/bin/parrot_run --no-set-foreground /bin/sh -c 'cd " + cwd_setting + "; " + user_cmd[0] + "'"
else:
user_cmd[0] = cctools_dest + "/bin/parrot_run --no-set-foreground /bin/sh -c 'cd " + cwd_setting + "; " + user_cmd[0] + "'"
logging.debug("The parrotized user_cmd: %s" % user_cmd[0])
def chrootize_user_cmd(user_cmd, cwd_setting):
"""Modify the user's command when the sandbox_mode is chroot. This check should be done after `parrotize_user_cmd`.
The cases when this function should be called: sandbox_mode == chroot
Args:
user_cmd: the user's command.
cwd_setting: the current working directory for the execution of the user's command.
Returns:
the modified version of the user's cmd.
"""
#By default, the directory of entering chroot is /. So before executing the user's command, first change the directory to the $PWD environment variable.
user_cmd[0] = 'chroot / /bin/sh -c "cd %s; %s"' %(cwd_setting, user_cmd[0])
return user_cmd
def software_install(mount_dict, env_para_dict, software_spec, meta_json, sandbox_dir, pac_install_destructive, osf_auth, name=None):
""" Installation each software dependency specified in the software section of the specification.
Args:
mount_dict: a dict including each mounting item in the specification, whose key is the access path used by the user's task; whose value is the actual storage path.
env_para_dict: the environment variables which need to be set for the execution of the user's command.
software_spec: the software section of the specification
meta_json: the json object including all the metadata of dependencies.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
pac_install_destructive: whether this is to install packages through package manager in destructive mode
osf_auth: the osf authentication info including osf_username and osf_password.
name: if name is specified, then only the specified item will be installed. All the other items in the software section will be ignored.
Returns:
None.
"""
print "Installing software dependencies ..."
for item in software_spec:
if name and name != item:
continue
# always first check whether the attribute is set or not inside the umbrella specificiation file.
id = ''
if software_spec[item].has_key('id'):
id = software_spec[item]['id']
mountpoint = ''
if software_spec[item].has_key('mountpoint'):
mountpoint = software_spec[item]['mountpoint']
mount_env = ''
if software_spec[item].has_key('mount_env'):
mount_env = software_spec[item]['mount_env']
action = 'unpack'
if software_spec[item].has_key('action'):
action = software_spec[item]['action'].lower()
if mount_env and not mountpoint:
result = meta_search(meta_json, item, id)
env_para_dict[mount_env] =attr_check(item, result, "source", 1)
else:
if mount_env and mountpoint:
env_para_dict[mount_env] = mountpoint
mount_value = dependency_process(item, id, action, meta_json, sandbox_dir, osf_auth)
if len(mount_value) > 0:
logging.debug("Add mountpoint (%s:%s) into mount_dict", mountpoint, mount_value)
if pac_install_destructive:
parent_dir = os.path.dirname(mountpoint)
if not os.path.exists(parent_dir):
os.makedirs(parent_dir)
elif not os.path.isdir(parent_dir):
cleanup(tempfile_list, tempdir_list)
logging.critical("%s is not a directory!\n", parent_dir)
sys.exit("%s is not a directory!\n" % parent_dir)
if not os.path.exists(mountpoint):
cmd = "mv -f %s %s/" % (mount_value, parent_dir)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
else:
mount_dict[mountpoint] = mount_value
def data_install(data_spec, meta_json, sandbox_dir, mount_dict, env_para_dict, osf_auth, name=None):
"""Process data section of the specification.
At the beginning of the function, mount_dict only includes items for software and os dependencies. After this function is done, all the items for data dependencies will be added into mount_dict.
Args:
data_spec: the data section of the specification.
meta_json: the json object including all the metadata of dependencies.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
mount_dict: a dict including each mounting item in the specification, whose key is the access path used by the user's task; whose value is the actual storage path.
env_para_dict: the environment variables which need to be set for the execution of the user's command.
osf_auth: the osf authentication info including osf_username and osf_password.
name: if name is specified, then only the specified item will be installed. All the other items in the software section will be ignored.
Returns:
None
"""
print "Installing data dependencies ..."
for item in data_spec:
if name and name != item:
continue
id = ''
if data_spec[item].has_key('id'):
id = data_spec[item]['id']
mountpoint = ''
if data_spec[item].has_key('mountpoint'):
mountpoint = data_spec[item]['mountpoint']
mount_env = ''
if data_spec[item].has_key('mount_env'):
mount_env = data_spec[item]['mount_env']
action = 'unpack'
if data_spec[item].has_key('action'):
action = data_spec[item]['action']
if mount_env and not mountpoint:
result = meta_search(meta_json, item, id)
env_para_dict[mount_env] = attr_check(item, result, "source", 1)
else:
mount_value = data_dependency_process(item, id, meta_json, sandbox_dir, action, osf_auth)
logging.debug("Add mountpoint (%s:%s) into mount_dict", mountpoint, mount_value)
mount_dict[mountpoint] = mount_value
if mount_env and mountpoint:
env_para_dict[mount_env] = mountpoint
def get_linker_path(hardware_platform, os_image_dir):
"""Return the path of ld-linux.so within the downloaded os image dependency
Args:
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
os_image_dir: the path of the OS image inside the umbrella local cache.
Returns:
If the dynamic linker is found within the OS image, return its fullpath.
Otherwise, returns None.
"""
#env_list is directly under the directory of the downloaded os image dependency
if hardware_platform == "x86_64":
p = os_image_dir + "/lib64/ld-linux-x86-64.so.2"
if os.path.exists(p):
return p
else:
return None
else:
return None
def construct_docker_volume(input_dict, mount_dict, output_f_dict, output_d_dict):
"""Construct the docker volume parameters based on mount_dict.
Args:
input_dict: the setting of input files specified by the --inputs option.
mount_dict: a dict including each mounting item in the specification, whose key is the access path used by the user's task; whose value is the actual storage path.
Returns:
volume_paras: all the `-v` options for the docker command.
"""
if "/" in mount_dict:
del mount_dict["/"] #remove "/" from the mount_dict to avoid messing the root directory of the host machine
volume_paras = ""
for key in mount_dict:
volume_paras = volume_paras + " -v " + mount_dict[key] + ":" + key + " "
for key in input_dict:
volume_paras = volume_paras + " -v " + input_dict[key] + ":" + key + " "
for key in output_f_dict:
volume_paras = volume_paras + " -v " + output_f_dict[key] + ":" + key + " "
for key in output_d_dict:
volume_paras = volume_paras + " -v " + output_d_dict[key] + ":" + key + " "
return volume_paras
def obtain_path(os_image_dir, sw_mount_dict):
"""Get the path environment variable from envfile and add the mountpoints of software dependencies into it
the envfile here is named env_list under the OS image.
Args:
os_image_dir: the path of the OS image inside the umbrella local cache.
sw_mount_dict: a dict only including all the software mounting items.
Returns:
path_env: the new value for PATH.
"""
path_env = ''
if os.path.exists(os_image_dir + "/env_list") and os.path.isfile(os_image_dir + "/env_list"):
with open(os_image_dir + "/env_list", "rb") as f:
for line in f:
if line[:5] == 'PATH=':
path_env = line[5:-1]
break
else:
path_env = '.:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin'
for key in sw_mount_dict:
path_env = key + "/bin:" + path_env
return path_env
def transfer_env_para_docker(env_para_dict):
"""Transfer the env_para_dict into the docker `-e` options.
Args:
env_para_dict: the environment variables which need to be set for the execution of the user's command.
Returns:
env_options: the docker `-e` options constructed from env_para_dict.
"""
env_options = ''
for key in env_para_dict:
if key:
env_options = env_options + ' -e "' + key + '=' + env_para_dict[key] + '" '
return env_options
def collect_software_bin(host_cctools_path, sw_mount_dict):
"""Construct the path environment from the mountpoints of software dependencies.
Each softare meta has a bin subdir containing all its executables.
Args:
host_cctools_path: the path of cctools under the umbrella local cache.
sw_mount_dict: a dict only including all the software mounting items.
Returns:
extra_path: the paths which are extracted from sw_mount_dict and host_cctools_path, and needed to be added into PATH.
"""
extra_path = ""
for key in sw_mount_dict:
if key != '/':
extra_path += '%s/bin:' % key
if host_cctools_path:
extra_path += '%s/bin:' % host_cctools_path
return extra_path
def in_local_passwd():
"""Judge whether the current user exists in /etc/passwd.
Returns:
If the current user is inside /etc/passwd, returns 'yes'.
Otherwise, returns 'no'.
"""
user_name = getpass.getuser()
with open('/etc/passwd') as f:
for line in f:
if line[:len(user_name)] == user_name:
logging.debug("%s is included in /etc/passwd!", user_name)
return 'yes'
logging.debug("%s is not included in /etc/passwd!", user_name)
return 'no'
def in_local_group():
"""Judge whether the current user's group exists in /etc/group.
Returns:
If the current user's group exists in /etc/group, returns 'yes'.
Otherwise, returns 'no'.
"""
group_name = grp.getgrgid(os.getgid())[0]
with open('/etc/group') as f:
for line in f:
if line[:len(group_name)] == group_name:
logging.debug("%s is included in /etc/group!", group_name)
return 'yes'
logging.debug("%s is not included in /etc/group!", group_name)
return 'no'
def create_fake_mount(os_image_dir, sandbox_dir, mount_list, path):
"""For each ancestor dir B of path (including path iteself), check whether it exists in the rootfs and whether it exists in the mount_list and
whether it exists in the fake_mount directory inside the sandbox.
If B is inside the rootfs or the fake_mount dir, do nothing. Otherwise, create a fake directory inside the fake_mount.
Reason: the reason why we need to guarantee any ancestor dir of a path exists somehow is that `cd` shell builtin does a syscall stat on each level of
the ancestor dir of a path. Without creating the mountpoint for any ancestor dir, `cd` would fail.
Args:
os_image_dir: the path of the OS image inside the umbrella local cache.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
mount_list: a list of mountpoints which already been inside the parrot mountlist file.
path: a dir path.
Returns:
mount_str: a string including the mount items which are needed to added into the parrot mount file.
"""
mount_str = ''
if not path: #if the path is NULL, directly return.
return
path_list = []
tmp_path = path
while tmp_path != '/':
path_list.insert(0, tmp_path)
tmp_path = remove_trailing_slashes(os.path.dirname(tmp_path))
for item in path_list:
logging.debug("Judge whether the following mountpoint exists: %s", item)
fake_mount_path = '%s/fake_mount%s' % (sandbox_dir, item)
#if item is under localdir, do nothing.
if item in remove_trailing_slashes(os.path.dirname(sandbox_dir)):
break
if not os.path.exists(os_image_dir + item) and item not in mount_list and not os.path.exists(fake_mount_path):
logging.debug("The mountpoint (%s) does not exist, create a fake mountpoint (%s) for it!", item, fake_mount_path)
os.makedirs(fake_mount_path)
mount_str += '%s %s\n' % (item, fake_mount_path)
else:
logging.debug("The mountpoint (%s) already exists, do nothing!", item)
return mount_str
def remove_trailing_slashes(path):
"""Remove the trailing slashes of a string
Args:
path: a path, which can be any string.
Returns:
path: the new path without any trailing slashes.
"""
while len(path) > 1 and path.endswith('/'):
path = path[:-1]
return path
def construct_mountfile_full(sandbox_dir, os_image_dir, mount_dict, input_dict, output_f_dict, output_d_dict, cvmfs_cms_siteconf_mountpoint):
"""Create the mountfile if parrot is used to create a sandbox for the application and a separate rootfs is needed.
The trick here is the adding sequence does matter. The latter-added items will be checked first during the execution.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
os_image_dir: the path of the OS image inside the umbrella local cache.
mount_dict: all the mount items extracted from the specification file and possible implicit dependencies like cctools.
input_dict: the setting of input files specified by the --inputs option
cvmfs_cms_siteconf_mountpoint: a string in the format of '/cvmfs/cms.cern.ch/SITECONF/local <SITEINFO dir in the umbrella local cache>/local'
Returns:
the path of the mountfile.
"""
mount_list = []
mountfile_path = sandbox_dir + "/.__mountlist"
with open(mountfile_path, "wb") as mountfile:
new_root = mount_dict["/"]
mountfile.write("/ " + new_root + "\n")
mount_list.append('/')
del mount_dict["/"]
mountfile.write(new_root + " " + new_root + "\n") #this one is needed to avoid recuisive path resolution.
mount_list.append(new_root)
mountfile.write("%s %s\n" % (os.path.dirname(sandbox_dir), os.path.dirname(sandbox_dir)))
mount_list.append(os.path.dirname(sandbox_dir))
logging.debug("Adding items from mount_dict into %s", mountfile_path)
for key in mount_dict:
#os.path.dirname('/a/b/') is '/a/b'. Therefore, before and after calling dirname, use remove_trailing_slashes to remove the trailing slashes.
key = remove_trailing_slashes(key)
mount_str = create_fake_mount(os_image_dir, sandbox_dir, mount_list, remove_trailing_slashes(os.path.dirname(key)))
if mount_str:
logging.debug("Adding fake mount items (%s) into %s", mount_str, mountfile_path)
mountfile.write(mount_str)
mount_list.append(key)
mount_list.append(mount_dict[key])
mountfile.write(key + " " + mount_dict[key] + "\n")
mountfile.write(mount_dict[key] + " " + mount_dict[key] + "\n")
for key in output_f_dict:
mountfile.write(key + " " + output_f_dict[key] + "\n")
for key in output_d_dict:
mountfile.write(key + " " + output_d_dict[key] + "\n")
#common-mountlist includes all the common mountpoint (/proc, /dev, /sys, /mnt, /disc, /selinux)
if os.path.exists(os_image_dir + "/common-mountlist") and os.path.isfile(os_image_dir + "/common-mountlist"):
logging.debug("Adding items from %s/common-mountlist into %s", os_image_dir, mountfile_path)
with open(os_image_dir + "/common-mountlist", "rb") as f:
for line in f:
tmplist = line.split(' ')
item = remove_trailing_slashes(tmplist[0])
mount_str = create_fake_mount(os_image_dir, sandbox_dir, mount_list, remove_trailing_slashes(os.path.dirname(item)))
if mount_str:
logging.debug("Adding fake mount items (%s) into %s", mount_str, mountfile_path)
mountfile.write(mount_str)
mount_list.append(tmplist[0])
mountfile.write(line)
logging.debug("Add sandbox_dir(%s) into %s", sandbox_dir, mountfile_path)
mountfile.write(sandbox_dir + ' ' + sandbox_dir + '\n')
mount_list.append(sandbox_dir)
logging.debug("Add /etc/hosts and /etc/resolv.conf into %s", mountfile_path)
mount_str = create_fake_mount(os_image_dir, sandbox_dir, mount_list, '/etc')
if mount_str:
logging.debug("Adding fake mount items (%s) into %s", mount_str, mountfile_path)
mountfile.write(mount_str)
mountfile.write('/etc/hosts /etc/hosts\n')
mount_list.append('/etc/hosts')
mountfile.write('/etc/resolv.conf /etc/resolv.conf\n')
mount_list.append('/etc/resolv.conf')
#nd workstation uses NSCD (Name Service Cache Daemon) to deal with passwd, group, hosts services. Here first check whether the current uid and gid is in the /etc/passwd and /etc/group, if yes, use them. Otherwise, construct separate passwd and group files.
#If the current user name and group can not be found in /etc/passwd and /etc/group, a fake passwd and group file will be constructed under sandbox_dir.
existed_user = in_local_passwd()
if existed_user == 'yes':
logging.debug("Add /etc/passwd into %s", mountfile_path)
mountfile.write('/etc/passwd /etc/passwd\n')
else:
logging.debug("Construct a fake passwd file: .passwd, add .passwd into %s", mountfile_path)
with open('.passwd', 'w+') as f:
f.write('%s:x:%d:%d:unknown:%s:%s\n' % (getpass.getuser(), os.getuid(), os.getgid(), sandbox_dir + '/' + getpass.getuser(), os.environ['SHELL']))
mountfile.write('/etc/passwd %s/.passwd\n' % (sandbox_dir))
logging.debug("Construct a fake acl file: .__acl, add .__acl into %s", mountfile_path)
with open('.__acl', 'w+') as acl_file:
acl_file.write('%s rwlax\n' % getpass.getuser())
mount_list.append('/etc/passwd')
#getpass.getuser() returns the login name of the user
#os.makedirs(getpass.getuser()) #it is not really necessary to create this dir.
existed_group = in_local_group()
if existed_group == 'yes':
logging.debug("Add /etc/group into %s", mountfile_path)
mountfile.write('/etc/group /etc/group\n')
else:
logging.debug("Construct a fake group file: .group, add .group into %s", mountfile_path)
with open('.group', 'w+') as f:
f.write('%s:x:%d:%d\n' % (grp.getgrgid(os.getgid())[0], os.getgid(), os.getuid()))
mountfile.write('/etc/group %s/.group\n' % (sandbox_dir))
mount_list.append('/etc/group')
#add /var/run/nscd/socket into mountlist
mount_str = create_fake_mount(os_image_dir, sandbox_dir, mount_list, '/var/run/nscd')
if mount_str:
logging.debug("Adding fake mount items (%s) into %s", mount_str, mountfile_path)
mountfile.write(mount_str)
mountfile.write('/var/run/nscd/socket ENOENT\n')
mount_list.append('/var/run/nscd/socket')
if os.path.exists(os_image_dir + "/special_files") and os.path.isfile(os_image_dir + "/special_files"):
logging.debug("Add %s/special_files into %s", os_image_dir, mountfile_path)
with open(os_image_dir + "/special_files", "rb") as f:
for line in f:
tmplist = line.split(' ')
item = remove_trailing_slashes(tmplist[0])
mount_str = create_fake_mount(os_image_dir, sandbox_dir, mount_list, remove_trailing_slashes(os.path.dirname(item)))
if mount_str:
logging.debug("Adding fake mount items (%s) into %s", mount_str, mountfile_path)
mountfile.write(mount_str)
mount_list.append(tmplist[0])
mountfile.write(line)
#add the input_dict into mountflie
logging.debug("Add items from input_dict into %s", mountfile_path)
for key in input_dict:
key = remove_trailing_slashes(key)
mount_str = create_fake_mount(os_image_dir, sandbox_dir, mount_list, remove_trailing_slashes(os.path.dirname(key)))
if mount_str:
logging.debug("Adding fake mount items (%s) into %s", mount_str, mountfile_path)
mountfile.write(mount_str)
mountfile.write(key + " " + input_dict[key] + "\n")
mount_list.append(key)
if cvmfs_cms_siteconf_mountpoint == '':
logging.debug('cvmfs_cms_siteconf_mountpoint is null')
else:
mountfile.write('/cvmfs /cvmfs\n')
mountfile.write(cvmfs_cms_siteconf_mountpoint + '\n')
logging.debug('cvmfs_cms_siteconf_mountpoint is not null: %s', cvmfs_cms_siteconf_mountpoint)
return mountfile_path
def construct_mountfile_cvmfs_cms_siteconf(sandbox_dir, cvmfs_cms_siteconf_mountpoint):
""" Create the mountfile if chroot and docker is used to execute a CMS application and the host machine does not have cvmfs installed.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
cvmfs_cms_siteconf_mountpoint: a string in the format of '/cvmfs/cms.cern.ch/SITECONF/local <SITEINFO dir in the umbrella local cache>/local'
Returns:
the path of the mountfile.
"""
mountfile_path = sandbox_dir + "/.__mountlist"
with open(mountfile_path, "wb") as f:
f.write(cvmfs_cms_siteconf_mountpoint + '\n')
logging.debug('cvmfs_cms_siteconf_mountpoint is not null: %s', cvmfs_cms_siteconf_mountpoint)
return mountfile_path
def construct_mountfile_easy(sandbox_dir, input_dict, output_f_dict, output_d_dict, mount_dict, cvmfs_cms_siteconf_mountpoint):
""" Create the mountfile if parrot is used to create a sandbox for the application and a separate rootfs is not needed.
The trick here is the adding sequence does matter. The latter-added items will be checked first during the execution.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
mount_dict: all the mount items extracted from the specification file and possible implicit dependencies like cctools.
input_dict: the setting of input files specified by the --inputs option
cvmfs_cms_siteconf_mountpoint: a string in the format of '/cvmfs/cms.cern.ch/SITECONF/local <SITEINFO dir in the umbrella local cache>/local'
Returns:
the path of the mountfile.
"""
mountfile_path = sandbox_dir + "/.__mountlist"
with open(mountfile_path, "wb") as f:
for key in input_dict:
f.write(key + " " + input_dict[key] + "\n")
for key in output_f_dict:
f.write(key + " " + output_f_dict[key] + "\n")
for key in output_d_dict:
f.write(key + " " + output_d_dict[key] + "\n")
for key in mount_dict:
f.write(key + " " + mount_dict[key] + "\n")
f.write(mount_dict[key] + " " + mount_dict[key] + "\n")
if cvmfs_cms_siteconf_mountpoint == '':
logging.debug('cvmfs_cms_siteconf_mountpoint is null')
else:
f.write(cvmfs_cms_siteconf_mountpoint + '\n')
logging.debug('cvmfs_cms_siteconf_mountpoint is not null: %s', cvmfs_cms_siteconf_mountpoint)
return mountfile_path
def construct_env(sandbox_dir, os_image_dir):
""" Read env_list inside an OS image and save all the environment variables into a dictionary.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
os_image_dir: the path of the OS image inside the umbrella local cache.
Returns:
env_dict: a dictionary which includes all the environment variables from env_list
"""
if os.path.exists(os_image_dir + "/env_list") and os.path.isfile(os_image_dir + "/env_list"):
with open(os_image_dir + "/env_list", "rb") as f:
env_dict = {}
for line in f:
index = line.find("=")
key = line[:index]
value = line[(index+1):-1]
env_dict[key] = value
return env_dict
return {}
def has_docker_image(hardware_platform, distro_name, distro_version, tag):
"""Check whether the required docker image exists on the local machine or not.
Args:
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
distro_name: the name of the required OS (e.g., redhat).
distro_version: the version of the required OS (e.g., 6.5).
tag: the tag of the expected docker image. tag is os_id
Returns:
If the required docker image exists on the local machine, returns 'yes'.
Otherwise, returns 'no'.
"""
name = "%s-%s-%s" %(distro_name, distro_version, hardware_platform)
cmd = "docker images %s | awk '{print $2}'" % (name)
logging.debug("Start to run the command: %s", cmd)
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = True)
(stdout, stderr) = p.communicate()
rc = p.returncode
logging.debug("returncode: %d\nstdout: %s\nstderr: %s", rc, stdout, stderr)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
#str = "\n%s\s+" % (name)
if stdout.find(tag) == -1:
return 'no'
else:
return 'yes'
def create_docker_image(sandbox_dir, hardware_platform, distro_name, distro_version, tag):
"""Create a docker image based on the cached os image directory.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
distro_name: the name of the required OS (e.g., redhat).
distro_version: the version of the required OS (e.g., 6.5).
tag: the tag of the expected docker image. tag is os_id
Returns:
If the docker image is imported from the tarball successfully, returns None.
Otherwise, directly exit.
"""
name = "%s-%s-%s" %(distro_name, distro_version, hardware_platform)
location = os.path.dirname(sandbox_dir) + '/cache/' + tag + '/' + name
#docker container runs as root user, so use the owner option of tar command to set the owner of the docker image
cmd = 'cd ' + location + '; tar --owner=root -c .|docker import - ' + name + ":" + tag + '; cd -'
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
def construct_chroot_mount_dict(sandbox_dir, output_dir, input_dict, need_separate_rootfs, os_image_dir, mount_dict, host_cctools_path):
"""Construct directory mount list and file mount list for chroot. chroot requires the target mountpoint must be created within the chroot jail.
Args:
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
output_f_dict: the mappings of output files (key is the file path used by the application; value is the file path the user specifies.)
output_d_dict: the mappings of output dirs (key is the dir path used by the application; value is the dir path the user specified.)
input_dict: the setting of input files specified by the --inputs option.
need_separate_rootfs: whether a separate rootfs is needed to execute the user's command.
os_image_dir: the path of the OS image inside the umbrella local cache.
mount_dict: a dict including each mounting item in the specification, whose key is the access path used by the user's task; whose value is the actual storage path.
host_cctools_path: the path of cctools under the umbrella local cache.
Returns:
a tuple includes the directory mount list and the file mount list
"""
dir_dict = {}
file_dict = {}
logging.debug("need_separate_rootfs: %d", need_separate_rootfs)
if need_separate_rootfs == 1:
logging.debug("Add %s into dir_dict of chroot", os_image_dir + "/common-mountlist")
with open(os_image_dir + "/common-mountlist") as f:
for line in f:
index = line.find(' ')
item = line[:index]
dir_dict[item] = item
#special_files includes all the paths of the files which includes all the file paths of special types (block, character, socket, pipe)
logging.debug("Add %s into dir_dict of chroot", os_image_dir + "/special_files")
with open(os_image_dir + "/special_files") as f:
for line in f:
index = line.find(' ')
item = line[:index]
if os.path.exists(item):
file_dict[item] = item
if host_cctools_path:
logging.debug("Add cctools binary (%s) into dir_dict of chroot", host_cctools_path)
dir_dict[host_cctools_path] = host_cctools_path
logging.debug("Add sandbox_dir and output_dir into dir_dict of chroot")
dir_dict[sandbox_dir] = sandbox_dir
dir_dict[output_dir] = output_dir
logging.debug("Add items from mount_dict into dir_dict of chroot")
for key in mount_dict:
if key != '/':
value = mount_dict[key]
mode = os.lstat(value).st_mode
if S_ISDIR(mode):
dir_dict[value] = key
else:
file_dict[value] = key
logging.debug("Add /etc/passwd /etc/group /etc/hosts /etc/resolv.conf into file_dict of chroot")
file_dict['/etc/passwd'] = '/etc/passwd'
file_dict['/etc/group'] = '/etc/group'
file_dict['/etc/hosts'] = '/etc/hosts'
file_dict['/etc/resolv.conf'] = '/etc/resolv.conf'
logging.debug("Add input_dict into file_dict of chroot")
for key in input_dict:
value = input_dict[key]
mode = os.lstat(value).st_mode
if S_ISDIR(mode):
dir_dict[value] = key
else:
file_dict[value] = key
logging.debug("dir_dict:")
logging.debug(dir_dict)
logging.debug("file_dict:")
logging.debug(file_dict)
return (dir_dict, file_dict)
def chroot_mount_bind(dir_dict, file_dict, sandbox_dir, need_separate_rootfs, hardware_platform, distro_name, distro_version):
"""Create each target mountpoint under the cached os image directory through `mount --bind`.
Args:
dir_dict: a dict including all the directory mountpoints needed to be created inside the OS image.
file_dict: a dict including all the file mountpoints needed to be created inside the OS image.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
need_separate_rootfs: whether a separate rootfs is needed to execute the user's command.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
distro_name: the name of the required OS (e.g., redhat).
distro_version: the version of the required OS (e.g., 6.5).
Returns:
If no error happens, returns None.
Otherwise, directly exit.
"""
logging.debug("Use mount --bind to redirect mountpoints")
if need_separate_rootfs == 1:
os_image_name = "%s-%s-%s" %(distro_name, distro_version, hardware_platform)
os_image_path = os.path.dirname(sandbox_dir) + '/cache/' + os_image_name
else:
os_image_path = '/'
#mount --bind -o ro hostdir sandboxdir
for key in dir_dict:
jaildir = '%s%s' % (os_image_path, dir_dict[key])
hostdir = key
#if jaildir and hostdir are the same, there is no necessary to do mount.
if jaildir != hostdir:
if not os.path.exists(jaildir):
os.makedirs(jaildir)
cmd = 'mount --bind -o ro %s %s' % (hostdir, jaildir)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
for key in file_dict:
jailfile = '%s%s' % (os_image_path, file_dict[key])
hostfile = key
if jailfile != hostfile:
if not os.path.exists(jailfile):
d = os.path.dirname(jailfile)
if not os.path.exists(d):
os.makedirs(d)
with open(jailfile, 'w+') as f:
pass
cmd = 'mount --bind -o ro %s %s' % (hostfile, jailfile)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
def chroot_post_process(dir_dict, file_dict, sandbox_dir, need_separate_rootfs, hardware_platform, distro_name, distro_version):
"""Remove all the created target mountpoints within the cached os image directory.
It is not necessary to change the mode of the output dir, because only the root user can use the chroot method.
Args:
dir_dict: a dict including all the directory mountpoints needed to be created inside the OS image.
file_dict: a dict including all the file mountpoints needed to be created inside the OS image.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
need_separate_rootfs: whether a separate rootfs is needed to execute the user's command.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
distro_name: the name of the required OS (e.g., redhat).
distro_version: the version of the required OS (e.g., 6.5).
Returns:
If no error happens, returns None.
Otherwise, directly exit.
"""
logging.debug("post process of chroot")
if need_separate_rootfs == 1:
os_image_name = "%s-%s-%s" %(distro_name, distro_version, hardware_platform)
os_image_path = os.path.dirname(sandbox_dir) + '/cache/' + os_image_name
else:
os_image_path = '/'
#file_dict must be processed ahead of dir_dict, because we can not umount a directory if there is another mountpoints created for files under it.
for key in file_dict:
jailfile = '%s%s' % (os_image_path, file_dict[key])
hostfile = key
if jailfile != hostfile:
if os.path.exists(jailfile):
cmd = 'umount -f %s' % (jailfile)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
for key in dir_dict:
jaildir = '%s%s' % (os_image_path, dir_dict[key])
hostdir = key
if jaildir != hostdir:
if os.path.exists(jaildir):
cmd = 'umount -f %s' % (jaildir)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
#remove all the empty ancestor directory
parent_dir = jaildir
mode = os.lstat(parent_dir).st_mode
if S_ISDIR(mode):
while len(os.listdir(parent_dir)) == 0:
os.rmdir(parent_dir)
parent_dir = os.path.dirname(parent_dir)
def workflow_repeat(cwd_setting, sandbox_dir, sandbox_mode, output_f_dict, output_d_dict, input_dict, env_para_dict, user_cmd, hardware_platform, host_linux_distro, distro_name, distro_version, need_separate_rootfs, os_image_dir, os_image_id, host_cctools_path, cvmfs_cms_siteconf_mountpoint, mount_dict, sw_mount_dict, meta_json, new_os_image_dir):
"""Run user's task with the help of the sandbox techniques, which currently inculde chroot, parrot, docker.
Args:
cwd_setting: the current working directory for the execution of the user's command.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
sandbox_mode: the execution engine.
output_f_dict: the mappings of output files (key is the file path used by the application; value is the file path the user specifies.)
output_d_dict: the mappings of output dirs (key is the dir path used by the application; value is the dir path the user specified.)
input_dict: the setting of input files specified by the --inputs option.
env_para_dict: the environment variables which need to be set for the execution of the user's command.
user_cmd: the user's command.
hardware_platform: the architecture of the required hardware platform (e.g., x86_64).
distro_name: the name of the required OS (e.g., redhat).
distro_version: the version of the required OS (e.g., 6.5).
need_separate_rootfs: whether a separate rootfs is needed to execute the user's command.
os_image_dir: the path of the OS image inside the umbrella local cache.
os_image_id: the id of the OS image.
host_cctools_path: the path of cctools under the umbrella local cache.
cvmfs_cms_siteconf_mountpoint: a string in the format of '/cvmfs/cms.cern.ch/SITECONF/local <SITEINFO dir in the umbrella local cache>/local'
mount_dict: a dict including each mounting item in the specification, whose key is the access path used by the user's task; whose value is the actual storage path.
sw_mount_dict: a dict only including all the software mounting items.
meta_json: the json object including all the metadata of dependencies.
new_os_image_dir: the path of the newly created OS image with all the packages installed by package manager.
Returns:
If no error happens, returns None.
Otherwise, directly exit.
"""
#sandbox_dir will be the home directory of the sandbox
print 'Executing the application ....'
if not os.path.exists(sandbox_dir):
os.makedirs(sandbox_dir)
logging.debug("chdir(%s)", sandbox_dir)
os.chdir(sandbox_dir) #here, we indeed want to chdir to sandbox_dir, not cwd_setting, to do preparation work like create mountlist file for Parrot.
#at this point, all the software should be under the cache dir, all the mountpoint of the software should be in mount_dict
print "Execution engine: %s" % sandbox_mode
logging.debug("execution engine: %s", sandbox_mode)
logging.debug("need_separate_rootfs: %d", need_separate_rootfs)
if sandbox_mode == "destructive":
env_dict = os.environ
if cvmfs_cms_siteconf_mountpoint:
logging.debug("Create a parrot mountfile for the siteconf meta ...")
env_dict['PARROT_MOUNT_FILE'] = construct_mountfile_cvmfs_cms_siteconf(sandbox_dir, cvmfs_cms_siteconf_mountpoint)
logging.debug("Add env_para_dict into environment variables")
for key in env_para_dict:
env_dict[key] = env_para_dict[key]
logging.debug("Add software binary into PATH")
extra_path = collect_software_bin(host_cctools_path, sw_mount_dict)
if "PATH" not in env_dict:
env_dict['PATH'] = ""
env_dict['PATH'] = '%s:%s' % (env_dict['PATH'], extra_path[:-1])
#move software and data into the location
for key in mount_dict:
parent_dir = os.path.dirname(key)
if not os.path.exists(parent_dir):
os.makedirs(parent_dir)
elif not os.path.isdir(parent_dir):
cleanup(tempfile_list, tempdir_list)
logging.critical("%s is not a directory!\n", parent_dir)
sys.exit("%s is not a directory!\n" % parent_dir)
if not os.path.exists(key):
cmd = "mv -f %s %s/" % (mount_dict[key], parent_dir)
rc, stdout, stderr = func_call_withenv(cmd, env_dict)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
print "Start executing the user's task: %s" % user_cmd[0]
cmd = "cd %s; %s" % (cwd_setting, user_cmd[0])
rc, stdout, stderr = func_call_withenv(cmd, env_dict)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
logging.debug("Moving the outputs to the expected locations ...")
print "Moving the outputs to the expected locations ..."
for key in output_f_dict:
cmd = "mv -f %s %s" % (key, output_f_dict[key])
rc, stdout, stderr = func_call_withenv(cmd, env_dict)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
for key in output_d_dict:
cmd = "mv -f %s %s" % (key, output_d_dict[key])
rc, stdout, stderr = func_call_withenv(cmd, env_dict)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
elif sandbox_mode == "docker":
if need_separate_rootfs == 1:
if has_docker_image(hardware_platform, distro_name, distro_version, os_image_id) == 'no':
logging.debug("Start to construct a docker image from the os image")
create_docker_image(sandbox_dir, hardware_platform, distro_name, distro_version, os_image_id)
logging.debug("Finish constructing a docker image from the os image")
if cvmfs_cms_siteconf_mountpoint:
item = cvmfs_cms_siteconf_mountpoint.split(' ')[1]
logging.debug("Adding the siteconf meta (%s) into mount_dict", item)
mount_dict[item] = item
logging.debug("Create a parrot mountfile for the siteconf meta (%s)", item)
env_para_dict['PARROT_MOUNT_FILE'] = construct_mountfile_cvmfs_cms_siteconf(sandbox_dir, cvmfs_cms_siteconf_mountpoint)
logging.debug("Add a volume item (%s:%s) for the sandbox_dir", sandbox_dir, sandbox_dir)
#-v /home/hmeng/umbrella_test/output:/home/hmeng/umbrella_test/output
volume_output = " -v %s:%s " % (sandbox_dir, sandbox_dir)
#-v /home/hmeng/umbrella_test/cache/git-x86_64-redhat5:/software/git-x86_64-redhat5/
logging.debug("Start to construct other volumes from input_dict")
volume_parameters = construct_docker_volume(input_dict, mount_dict, output_f_dict, output_d_dict)
#-e "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/software/git-x86_64-redhat5/bin"
logging.debug("Set the environment variables ....")
path_env = obtain_path(os_image_dir, sw_mount_dict)
other_envs = transfer_env_para_docker(env_para_dict)
docker_image_name = "%s-%s-%s" %(distro_name, distro_version, hardware_platform)
#by default, docker executes user_cmd as the root user, `chown` is used to change the owner of the output dir to be the user who calls `umbrella`
chown_cmd = 'chown -R %d:%d %s %s %s' % (os.getuid(), os.getgid(), sandbox_dir, ' '.join(output_f_dict), ' '.join(output_d_dict))
#to count the post processing time, this cmd is split into two commands
container_name = "umbrella_%s_%s_%s" % (docker_image_name, os_image_id, os.path.basename(sandbox_dir))
#do not enable `-i` and `-t` option of Docker, it will fail when condor execution engine is chosen.
#to allow the exit code of user_cmd to be transferred back, seperate the user_cmd and the chown command.
cmd = 'docker run --name %s %s %s -e "PATH=%s" %s %s:%s /bin/sh -c "cd %s; %s"' % (container_name, volume_output, volume_parameters, path_env, other_envs, docker_image_name, os_image_id, cwd_setting, user_cmd[0])
print "Start executing the user's task: %s" % cmd
rc, stdout, stderr = func_call(cmd)
print "\n********** STDOUT of the command **********"
print stdout
print "\n********** STDERR of the command **********"
print stderr
#docker export container_name > tarball
if len(new_os_image_dir) > 0:
if not os.path.exists(new_os_image_dir):
os.makedirs(new_os_image_dir)
os_tar = new_os_image_dir + ".tar"
cmd = "docker export %s > %s" % (container_name, os_tar)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
#uncompress the tarball
cmd = "tar xf %s -C %s" % (os_tar, new_os_image_dir)
extract_tar(os_tar, new_os_image_dir, "tar")
#docker rm container_name
cmd = "docker rm %s" % (container_name)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
cmd1 = 'docker run --rm %s %s -e "PATH=%s" %s %s:%s %s' % (volume_output, volume_parameters, path_env, other_envs, docker_image_name, os_image_id, chown_cmd)
rc, stdout, stderr = func_call(cmd1)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
else:
#if a separate rootfs is not needed to execute the user's cmd, should forcely use other execution engine to run the user cmd.
cleanup(tempfile_list, tempdir_list)
logging.debug("Docker execution engine can only be used when a separate rootfs is needed.")
sys.exit("Docker execution engine can only be used when a separate rootfs is needed.\n")
elif sandbox_mode == "parrot":
if need_separate_rootfs == 1:
logging.debug("Construct environment variables ....")
env_dict = construct_env(sandbox_dir, os_image_dir)
env_dict['PWD'] = cwd_setting
logging.debug("Construct mounfile ....")
env_dict['PARROT_MOUNT_FILE'] = construct_mountfile_full(sandbox_dir, os_image_dir, mount_dict, input_dict, output_f_dict, output_d_dict, cvmfs_cms_siteconf_mountpoint)
for key in env_para_dict:
env_dict[key] = env_para_dict[key]
#here, setting the linker will cause strange errors.
logging.debug("Construct dynamic linker path ....")
result = get_linker_path(hardware_platform, os_image_dir)
if not result:
cleanup(tempfile_list, tempdir_list)
logging.critical("Can not find the dynamic linker inside the os image (%s)!", os_image_dir)
sys.exit("Can not find the dynamic linker inside the os image (%s)!\n" % os_image_dir)
env_dict['PARROT_LDSO_PATH'] = result
env_dict['USER'] = getpass.getuser()
#env_dict['HOME'] = sandbox_dir + '/' + getpass.getuser()
logging.debug("Add software binary into PATH")
extra_path = collect_software_bin(host_cctools_path, sw_mount_dict)
if "PATH" not in env_dict:
env_dict['PATH'] = '.:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin'
env_dict['PATH'] = '%s%s' % (extra_path, env_dict['PATH'])
print "Start executing the user's task: %s" % user_cmd[0]
rc, stdout, stderr = func_call_withenv(user_cmd[0], env_dict)
print "\n********** STDOUT of the command **********"
print stdout
print "\n********** STDERR of the command **********"
print stderr
else:
env_dict = os.environ
env_dict['PARROT_MOUNT_FILE'] = construct_mountfile_easy(sandbox_dir, input_dict, output_f_dict, output_d_dict, mount_dict, cvmfs_cms_siteconf_mountpoint)
for key in env_para_dict:
env_dict[key] = env_para_dict[key]
if 'PATH' not in env_dict: #if we run umbrella on Condor, Condor will not set PATH by default.
env_dict['PATH'] = '.:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin'
logging.debug("PATH is empty, forcely set it to be %s", env_dict['PATH'])
else:
env_dict['PATH'] = '.' + env_dict['PATH']
logging.debug("Forcely add '.' into PATH")
logging.debug("Add software binary into PATH")
extra_path = collect_software_bin(host_cctools_path, sw_mount_dict)
env_dict['PATH'] = '%s%s' % (extra_path, env_dict['PATH'])
print "Start executing the user's task: %s" % user_cmd[0]
rc, stdout, stderr = func_call_withenv(user_cmd[0], env_dict)
print "\n********** STDOUT of the command **********"
print stdout
print "\n********** STDERR of the command **********"
print stderr
# logging.debug("Removing the parrot mountlist file and the parrot submit file from the sandbox")
# if os.path.exists(env_dict['PARROT_MOUNT_FILE']):
# os.remove(env_dict['PARROT_MOUNT_FILE'])
else:
pass
def condor_process(spec_path, spec_json, spec_path_basename, meta_path, sandbox_dir, output_dir, input_list_origin, user_cmd, cwd_setting, condorlog_path, cvmfs_http_proxy):
"""Process the specification when condor execution engine is chosen
Args:
spec_path: the absolute path of the specification.
spec_json: the json object including the specification.
spec_path_basename: the file name of the specification.
meta_path: the path of the json file including all the metadata information.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
output_dir: the output directory.
input_list_origin: the list of input file paths.
user_cmd: the user's command.
cwd_setting: the current working directory for the execution of the user's command.
condorlog_path: the path of the umbrella log executed on the remote condor execution node.
cvmfs_http_proxy: HTTP_PROXY environmetn variable used to access CVMFS by Parrot
Returns:
If no errors happen, return None;
Otherwise, directly exit.
"""
if not os.path.exists(sandbox_dir):
os.makedirs(sandbox_dir)
print "Checking the validity of the umbrella specification ..."
if spec_json.has_key("hardware") and spec_json["hardware"] and spec_json.has_key("kernel") and spec_json["kernel"] and spec_json.has_key("os") and spec_json["os"]:
logging.debug("Setting the environment parameters (hardware, kernel and os) according to the specification file ....")
(hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version, linux_distro, distro_name, distro_version, os_id) = env_parameter_init(spec_json["hardware"], spec_json["kernel"], spec_json["os"])
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("this specification is not complete! You must have a hardware section, a kernel section and a os section!")
sys.exit("this spec has no hardware section\n")
condor_submit_path = sandbox_dir + "/condor_task.submit"
print "Constructing Condor submission file according to the umbrella specification ..."
transfer_inputs = ''
new_input_options = ''
logging.debug("Transform input_list_origin into condor attributes ....")
for item in input_list_origin:
index_equal = item.find('=')
access_path = item[:index_equal]
actual_path = item[(index_equal+1):]
transfer_inputs += ',%s' % (actual_path)
new_input_options += '%s=%s,' % (access_path, os.path.basename(actual_path))
if new_input_options[-1] == ',':
new_input_options = new_input_options[:-1]
logging.debug("transfer_input_files: %s, %s", spec_path, transfer_inputs)
logging.debug("The new_input_options of Umbrella: %s", new_input_options)
condor_output_dir = tempfile.mkdtemp(dir=".")
condor_output_dir = os.path.abspath(condor_output_dir)
condor_log_path = sandbox_dir + '/condor_task.log'
umbrella_fullpath = which_exec("umbrella")
if umbrella_fullpath == None:
cleanup(tempfile_list, tempdir_list)
logging.critical("Failed to find the executable umbrella. Please modify your $PATH.")
sys.exit("Failed to find the executable umbrella. Please modify your $PATH.\n")
logging.debug("The full path of umbrella is: %s" % umbrella_fullpath)
#find cctools_python
cmd = 'which cctools_python'
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
cctools_python_path = stdout[:-1]
condor_submit_file = open(condor_submit_path, "w+")
condor_submit_file.write('universe = vanilla\n')
condor_submit_file.write('executable = %s\n' % cctools_python_path)
if cvmfs_http_proxy:
condor_submit_file.write('arguments = "./umbrella -s local --spec %s --cvmfs_http_proxy %s --meta %s -l condor_umbrella -i \'%s\' -o %s --log condor_umbrella.log run \'%s\'"\n' % (spec_path_basename, cvmfs_http_proxy, os.path.basename(meta_path), new_input_options, os.path.basename(condor_output_dir), user_cmd[0]))
else:
condor_submit_file.write('arguments = "./umbrella -s local --spec %s --meta %s -l condor_umbrella -i \'%s\' -o %s --log condor_umbrella.log run \'%s\'"\n' % (spec_path_basename, os.path.basename(meta_path), new_input_options, os.path.basename(condor_output_dir), user_cmd[0]))
# condor_submit_file.write('PostCmd = "echo"\n')
# condor_submit_file.write('PostArguments = "$?>%s/condor_rc"\n' % os.path.basename(condor_output_dir))
condor_submit_file.write('transfer_input_files = %s, %s, %s, %s%s\n' % (cctools_python_path, umbrella_fullpath, meta_path, spec_path, transfer_inputs))
condor_submit_file.write('transfer_output_files = %s, condor_umbrella.log\n' % os.path.basename(condor_output_dir))
condor_submit_file.write('transfer_output_remaps = "condor_umbrella.log=%s"\n' % condorlog_path)
#the python on the redhat5 machines in the ND condor pool is 2.4. However, umbrella requires python 2.6.* or 2.7*.
if linux_distro == "redhat5":
condor_submit_file.write('requirements = TARGET.Arch == "%s" && TARGET.OpSys == "%s" && TARGET.OpSysAndVer == "redhat6"\n' % (hardware_platform, kernel_name))
else:
#condor_submit_file.write('requirements = TARGET.Arch == "%s" && TARGET.OpSys == "%s" && TARGET.OpSysAndVer == "%s" && TARGET.has_docker == true\n' % (hardware_platform, kernel_name, linux_distro))
condor_submit_file.write('requirements = TARGET.Arch == "%s" && TARGET.OpSys == "%s" && TARGET.OpSysAndVer == "%s"\n' % (hardware_platform, kernel_name, linux_distro))
condor_submit_file.write('environment = PATH=.:/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n')
condor_submit_file.write('output = %s/condor_stdout\n' % sandbox_dir)
condor_submit_file.write('error = %s/condor_stderr\n' % sandbox_dir)
condor_submit_file.write('log = %s\n' % condor_log_path)
condor_submit_file.write('should_transfer_files = yes\n')
condor_submit_file.write('when_to_transfer_output = on_exit\n')
condor_submit_file.write('queue\n')
condor_submit_file.close()
#submit condor job
print "Submitting the Condor job ..."
cmd = 'condor_submit ' + condor_submit_path
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
#keep tracking whether condor job is done
print "Waiting for the job is done ..."
logging.debug("Waiting for the job is done ...")
cmd = 'condor_wait %s' % condor_log_path
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
#check the content of condor log file to figure out the exit code of the remote executed umbrella
remote_rc = 500
with open(condor_log_path, 'rb') as f:
content = f.read()
str = "Normal termination (return value "
index1 = content.rfind(str)
index2 = content.find(')', index1)
remote_rc = int(content[(index1 + len(str)):index2])
print "The exit code of the remote executed umbrella found in the condor log file (%s) is %d!" % (condor_log_path, remote_rc)
logging.debug("The exit code of the remote executed umbrella found in the condor log file (%s) is %d!", condor_log_path, remote_rc)
if remote_rc == 500:
cleanup(tempfile_list, tempdir_list)
logging.critical("Can not find the exit code of the remote executed umbrella inside the condor log file (%s)!", condor_log_path)
sys.exit("Can not find the exit code of the remote executed umbrella inside the condor log file (%s)!" % condor_log_path)
elif remote_rc != 0:
cleanup(tempfile_list, tempdir_list)
logging.critical("The remote umbrella fails and the exit code is %d.", remote_rc)
sys.exit("The remote umbrella fails and the exit code is %d." % remote_rc)
logging.debug("the condor jos is done, put the output back into the output directory!")
print "the condor jobs is done, put the output back into the output directory!"
#check until the condor job is done, post-processing (put the output back into the output directory)
#the semantics of condor_output_files only supports transferring a dir from the execution node back to the current working dir (here it is condor_output_dir).
os.rename(condor_output_dir, output_dir)
print "move condor_stdout, condor_stderr and condor_task.log from sandbox_dir to output_dir."
logging.debug("move condor_stdout, condor_stderr and condor_task.log from sandbox_dir to output_dir.")
os.rename(sandbox_dir + '/condor_stdout', output_dir + '/condor_stdout')
os.rename(sandbox_dir + '/condor_stderr', output_dir + '/condor_stderr')
os.rename(sandbox_dir + '/condor_task.log', output_dir + '/condor_task.log')
print "Remove the sandbox dir"
logging.debug("Remove the sandbox_dir.")
shutil.rmtree(sandbox_dir)
print "The output has been put into the output dir: %s" % output_dir
def decide_instance_type(cpu_cores, memory_size, disk_size, instances):
""" Compare the required hardware configurations with each instance type, and return the first matched instance type, return 'no' if no matched instance type exist.
We can rank each instance type in the future, so that in the case of multiple matches exit, the closest matched instance type is returned.
Args:
cpu_cores: the number of required cpus (e.g., 1).
memory_size: the memory size requirement (e.g., 2GB). Not case sensitive.
disk_size: the disk size requirement (e.g., 2GB). Not case sensitive.
instances: the instances section of the ec2 json file.
Returns:
If there is no matched instance type, return 'no'.
Otherwise, returns the first matched instance type.
"""
cpu_cores = int(cpu_cores)
memory_size = int(memory_size[:-2])
disk_size = int(disk_size[:-2])
for item in instances:
j = instances[item]
inst_mem = int(float((j["memory"][:-2])))
inst_disk = int(j["disk"][:-2])
if cpu_cores <= int(j["cores"]) and memory_size <= inst_mem and disk_size <= inst_disk:
return item
return 'no'
def ec2_process(spec_path, spec_json, meta_option, meta_path, ssh_key, ec2_key_pair, ec2_security_group, ec2_instance_type, sandbox_dir, output_option, output_f_dict, output_d_dict, sandbox_mode, input_list, input_list_origin, env_option, env_para_dict, user_cmd, cwd_setting, ec2log_path, cvmfs_http_proxy):
"""
Args:
spec_path: the path of the specification.
spec_json: the json object including the specification.
meta_option: the --meta option.
meta_path: the path of the json file including all the metadata information.
ssh_key: the name the private key file to use when connecting to an instance.
ec2_key_pair: the path of the key-pair to use when launching an instance.
ec2_security_group: the security group within which the EC2 instance should be run.
ec2_instance_type: the type of an Amazone ec2 instance
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
output_f_dict: the mappings of output files (key is the file path used by the application; value is the file path the user specifies.)
output_d_dict: the mappings of output dirs (key is the dir path used by the application; value is the dir path the user specified.)
sandbox_mode: the execution engine.
input_list: a list including all the absolute path of the input files on the local machine.
input_list_origin: the list of input file paths.
env_para_dict: the environment variables which need to be set for the execution of the user's command.
user_cmd: the user's command.
cwd_setting: the current working directory for the execution of the user's command.
ec2log_path: the path of the umbrella log executed on the remote EC2 execution node.
cvmfs_http_proxy: HTTP_PROXY environmetn variable used to access CVMFS by Parrot
Returns:
If no errors happen, return None;
Otherwise, directly exit.
"""
print "Checking the validity of the umbrella specification ..."
if spec_json.has_key("hardware") and spec_json["hardware"] and spec_json.has_key("kernel") and spec_json["kernel"] and spec_json.has_key("os") and spec_json["os"]:
(hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version, linux_distro, distro_name, distro_version, os_id) = env_parameter_init(spec_json["hardware"], spec_json["kernel"], spec_json["os"])
else:
cleanup(tempfile_list, tempdir_list)
sys.exit("this spec has no hardware section!\n")
#According to the given specification file, the AMI and the instance type can be identified. os and arch can be used to decide the AMI; cores, memory and disk can be used to decide the instance type.
#decide the AMI according to (distro_name, distro_version, hardware_platform)
print "Deciding the AMI according to the umbrella specification ..."
name = '%s-%s-%s' % (distro_name, distro_version, hardware_platform)
if ec2_json.has_key(name):
if os_id[:4] != "ec2:":
for item in ec2_json[name]:
logging.debug("The AMI information is: ")
logging.debug(ec2_json[name][item])
ami = ec2_json[name][item]['ami']
user_name = ec2_json[name][item]['user']
break
else:
if ec2_json[name].has_key(os_id):
logging.debug("The AMI information is: ")
logging.debug(ec2_json[name][os_id])
ami = ec2_json[name][os_id]['ami']
user_name = ec2_json[name][os_id]['user']
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s with the id <%s> is not in the ec2 json file (%s).", name, os_id, ec2_path)
sys.exit("%s with the id <%s> is not in the ec2 json file (%s)." % (name, os_id, ec2_path))
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s is not in the ec2 json file (%s).", name, ec2_path)
sys.exit("%s is not in the ec2 json file (%s).\n" % (name, ec2_path))
#start the instance and obtain the instance id
print "Starting an Amazon EC2 instance ..."
instance_id = get_instance_id(ami, ec2_instance_type, ec2_key_pair, ec2_security_group)
logging.debug("Start the instance and obtain the instance id: %s", instance_id)
#get the public DNS of the instance_id
print "Obtaining the public DNS of the Amazon EC2 instance ..."
public_dns = get_public_dns(instance_id)
logging.debug("Get the public DNS of the instance_id: %s", public_dns)
'''
#instance_id = "<instance_id>"
#public_dns = "<public_dns>"
instance_id = "i-e61ad13c"
public_dns = "ec2-52-26-177-97.us-west-2.compute.amazonaws.com"
'''
#install wget on the instance
print "Installing wget on the EC2 instance ..."
logging.debug("Install wget on the instance")
#here we should judge the os type, yum is used by Fedora, CentOS, and REHL.
if distro_name not in ["fedora", "centos", "redhat"]:
cleanup(tempfile_list, tempdir_list)
sys.exit("Currently the supported Linux distributions are redhat, centos and fedora.\n")
#ssh exit code 255: the remote node is down or unavailable
rc = 300
while rc != 0:
#without `-t` option of ssh, if the username is not root, `ssh + sudo` will get the following error: sudo: sorry, you must have a tty to run sudo.
cmd = 'ssh -t -o ConnectionAttempts=5 -o StrictHostKeyChecking=no -o ConnectTimeout=60 -i %s %s@%s \'sudo yum -y install wget\'' % (ssh_key, user_name, public_dns)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
logging.debug("`%s` fails with the return code of %d, \nstdout: %s, \nstderr: %s" % (cmd, rc, stdout, stderr))
time.sleep(5)
#python, the python is needed to execute umbrella itself
print "Installing python 2.6.9 on the instance ..."
logging.debug("Install python 2.6.9 on the instance.")
python_name = 'python-2.6.9-%s-%s' % (linux_distro, hardware_platform)
python_url = "http://ccl.cse.nd.edu/research/data/hep-case-study/python-2.6.9-%s-%s.tar.gz" % (linux_distro, hardware_platform)
scheme, netloc, path, query, fragment = urlparse.urlsplit(python_url)
python_url_filename = os.path.basename(path)
cmd = 'ssh -t -o ConnectionAttempts=5 -o StrictHostKeyChecking=no -o ConnectTimeout=60 -i %s %s@%s \'sudo wget %s && sudo tar zxvf %s\'' % (ssh_key, user_name, public_dns, python_url, python_url_filename)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
#scp umbrella, meta.json and input files to the instance
print "Sending the umbrella task to the EC2 instance ..."
logging.debug("scp relevant files into the HOME dir of the instance.")
input_file_string = ''
for input_file in input_list:
input_file_string += input_file + ' '
#here meta_path may start with http so need a special treatement
umbrella_fullpath = which_exec("umbrella")
if meta_option:
meta_option = " --meta ~%s/%s " % (user_name, os.path.basename(meta_path))
cmd = 'scp -i %s %s %s %s %s %s@%s:' % (ssh_key, umbrella_fullpath, spec_path, meta_path, input_file_string, user_name, public_dns)
else:
meta_option = ""
cmd = 'scp -i %s %s %s %s %s@%s:' % (ssh_key, umbrella_fullpath, spec_path, input_file_string, user_name, public_dns)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
#change the --inputs option to put all the inputs directory in the home dir of the instance
new_input_options = ''
if len(input_list_origin) > 0:
logging.debug("change the --inputs option to put all the inputs directory in the home dir of the instance")
logging.debug("Transform input_list_origin ....")
new_input_options = " -i '"
for item in input_list_origin:
index_equal = item.find('=')
access_path = item[:index_equal]
actual_path = item[(index_equal+1):]
new_input_options += '%s=%s,' % (access_path, os.path.basename(actual_path))
if new_input_options[-1] == ',':
new_input_options = new_input_options[:-1]
new_input_options += "'"
logging.debug("The new_input_options of Umbrella: %s", new_input_options) #--inputs option
#find cctools_python
cmd = 'which cctools_python'
rc, stdout, stderr = func_call(cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
cctools_python_path = stdout[:-1]
#cvmfs_http_proxy
cvmfs_http_proxy_option = ''
if cvmfs_http_proxy:
cvmfs_http_proxy_option = '--cvmfs_http_proxy %s' % cvmfs_http_proxy
#execute the command on the instance
print "Executing the user's task on the EC2 instance ..."
logging.debug("Execute the command on the instance ...")
ec2_output_option = ""
if output_option:
ec2_output_option = " -o '%s'" % output_option
cmd = 'ssh -t -o ConnectionAttempts=5 -o StrictHostKeyChecking=no -o ConnectTimeout=60 -i %s %s@%s "sudo %s/bin/python ~%s/umbrella %s -s destructive --spec ~%s/%s %s --log ~%s/ec2_umbrella.log -l ec2_umbrella %s %s %s run \'%s\'"' % (ssh_key, user_name, public_dns, python_name, user_name, cvmfs_http_proxy_option, user_name, os.path.basename(spec_path), meta_option, user_name, ec2_output_option, new_input_options, env_option, user_cmd[0])
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
#postprocessing
print "Transferring the output of the user's task from the EC2 instance back to the local machine ..."
logging.debug("Create a tarball for the output dir on the instance.")
output = '%s %s' % (' '.join(output_f_dict.values()), ' '.join(output_d_dict.values()))
cmd = 'ssh -t -o ConnectionAttempts=5 -o StrictHostKeyChecking=no -o ConnectTimeout=60 -i %s %s@%s \'sudo tar cvzf ~%s/output.tar.gz %s && sudo chown %s:%s ~%s/output.tar.gz ~%s/ec2_umbrella.log\'' % (ssh_key, user_name, public_dns, user_name, output, user_name, user_name, user_name, user_name)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
logging.debug("The instance returns the output.tar.gz to the local machine.")
cmd = 'scp -i %s %s@%s:output.tar.gz %s/' % (ssh_key, user_name, public_dns, sandbox_dir)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
logging.debug("The instance returns the remote umbrella log file to the local machine.")
cmd = 'scp -i %s %s@%s:ec2_umbrella.log %s' % (ssh_key, user_name, public_dns, ec2log_path)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
cmd = 'tar zxvf %s/output.tar.gz -C /' % (sandbox_dir)
rc, stdout, stderr = func_call(cmd)
if rc != 0:
terminate_instance(instance_id)
subprocess_error(cmd, rc, stdout, stderr)
print "Terminating the EC2 instance ..."
terminate_instance(instance_id)
def obtain_package(spec_json):
"""Check whether this spec includes a package_manager section, which in turn includes a list attr.
Args:
spec_json: the json object including the specification.
Returns:
if a package list is specified in the spec_json, return the package manager name and a list of the required package name.
Otherwise, return None
"""
if spec_json.has_key("package_manager") and spec_json["package_manager"]:
if spec_json["package_manager"].has_key("name") and spec_json["package_manager"].has_key("list"):
pac_name = spec_json["package_manager"]["name"]
pac_str = spec_json["package_manager"]["list"]
pac_list = pac_str.split()
pac_list.sort()
if len(pac_list) > 0:
if len(pac_name) == 0:
logging.critical("The spec does not specify which package manager to use\n")
sys.exit("The spec does not specify which package manager to use\n")
else:
return (pac_name, pac_list)
return (None, None)
def cal_new_os_id(sec, old_os_id, pac_list):
"""Calculate the id of the new OS based on the old_os_id and the package_manager section
Args:
sec: the json object including the package_manager section.
old_os_id: the id of the original os image without any info about package manager.
pac_list: a list of the required package name.
Returns:
md5_value: the md5 value of the string constructed from binding old_os_id and information from the package_manager section.
install_cmd: the package install cmd, such as: yum -y install python
"""
pm_name = attr_check("os", sec, "name")
cmd = pm_name + " " + pac_manager[pm_name][0] + " " + ' '.join(pac_list)
install_cmd = []
install_cmd.append(cmd)
pac_str = ''.join(pac_list)
config_str = ''
if sec.has_key("config") and sec["config"]:
l = []
for item in sec["config"]:
id_attr = sec["config"][item]["id"]
l.append(id_attr)
l.sort()
config_str = ''.join(l)
data = old_os_id + pm_name + pac_str + config_str
md5 = hashlib.md5()
md5.update(data)
md5_value = md5.hexdigest()
return (md5_value, install_cmd)
def specification_process(spec_json, sandbox_dir, behavior, meta_json, sandbox_mode, output_f_dict, output_d_dict, input_dict, env_para_dict, user_cmd, cwd_setting, cvmfs_http_proxy, osf_auth):
""" Create the execution environment specified in the specification file and run the task on it.
Args:
spec_json: the json object including the specification.
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
behavior: the umbrella behavior, such as `run`.
meta_json: the json object including all the metadata of dependencies.
sandbox_mode: the execution engine.
output_f_dict: the mappings of output files (key is the file path used by the application; value is the file path the user specifies.)
output_d_dict: the mappings of output dirs (key is the dir path used by the application; value is the dir path the user specified.)
input_dict: the setting of input files specified by the --inputs option.
env_para_dict: the environment variables which need to be set for the execution of the user's command.
user_cmd: the user's command.
cwd_setting: the current working directory for the execution of the user's command.
cvmfs_http_proxy: HTTP_PROXY environmetn variable used to access CVMFS by Parrot
osf_auth: the osf authentication info including osf_username and osf_password.
Returns:
None.
"""
print "Checking the validity of the umbrella specification ..."
if spec_json.has_key("hardware") and spec_json["hardware"] and spec_json.has_key("kernel") and spec_json["kernel"] and spec_json.has_key("os") and spec_json["os"]:
logging.debug("Setting the environment parameters (hardware, kernel and os) according to the specification file ....")
(hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version, linux_distro, distro_name, distro_version, os_id) = env_parameter_init(spec_json["hardware"], spec_json["kernel"], spec_json["os"])
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("this specification is not complete! You must have a hardware section, a kernel section and a os section!")
sys.exit("this specification is not complete! You must have a hardware section, a kernel section and a os section!\n")
host_linux_distro = env_check(sandbox_dir, sandbox_mode, hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version)
#check os
need_separate_rootfs = 0
os_image_dir = ''
if os_id == "":
if sandbox_mode in ["docker"]:
cleanup(tempfile_list, tempdir_list)
logging.critical("the specification does not provide a concrete OS image, but docker execution engine needs a specific OS image!")
sys.exit("the specification does not provide a concrete OS image, but docker execution engine needs a specific OS image!\n")
if linux_distro != host_linux_distro:
cleanup(tempfile_list, tempdir_list)
logging.critical("the specification does not provide a concrete OS image, and the OS image of the local machine does not matching the requirement!")
sys.exit("the specification does not provide a concrete OS image, and the OS image of the local machine does not matching the requirement!\n")
else:
logging.debug("the specification does not provide a concrete OS image, but the OS image of the local machine matches the requirement!")
print "the specification does not provide a concrete OS image, but the OS image of the local machine matches the requirement!\n"
else:
need_separate_rootfs = 1
#check for dependencies which need to be installed by package managers
(pac_name, pac_list) = obtain_package(spec_json)
if pac_list:
logging.debug("The spec needs to use %s install packages.", pac_name)
print "The spec needs to use %s install packages." % pac_name
if sandbox_mode in ["parrot"]:
cleanup(tempfile_list, tempdir_list)
logging.critical("Installing packages through package managers requires the root authority! Please choose a different sandbox mode (docker or destructive)!")
sys.exit("Installing packages through package managers requires the root authority! Please choose a different sandbox mode(docker or destructive)!")
mount_dict = {}
cvmfs_cms_siteconf_mountpoint = ''
host_cctools_path = '' #the path of the cctools binary which is compatible with the host machine under the umbrella cache
if sandbox_mode in ["parrot"]:
logging.debug("To use parrot sandbox mode, cctools binary is needed")
host_cctools_path = cctools_download(sandbox_dir, hardware_platform, host_linux_distro, 'unpack')
logging.debug("Add mountpoint (%s:%s) into mount_dict", host_cctools_path, host_cctools_path)
mount_dict[host_cctools_path] = host_cctools_path
parrotize_user_cmd(user_cmd, sandbox_dir, cwd_setting, host_linux_distro, hardware_platform, meta_json, cvmfs_http_proxy)
item = '%s-%s-%s' % (distro_name, distro_version, hardware_platform) #example of item here: redhat-6.5-x86_64
if need_separate_rootfs and sandbox_mode not in ["destructive"]:
#download the os dependency into the local
os_image_dir = "%s/cache/%s/%s" % (os.path.dirname(sandbox_dir), os_id, item)
logging.debug("A separate OS (%s) is needed!", os_image_dir)
mountpoint = '/'
action = 'unpack'
r3 = dependency_process(item, os_id, action, meta_json, sandbox_dir, osf_auth)
logging.debug("Add mountpoint (%s:%s) into mount_dict for /.", mountpoint, r3)
mount_dict[mountpoint] = r3
#check for cvmfs dependency
is_cms_cvmfs_app = 0
cvmfs_path = ""
cvmfs_mountpoint = ""
result = needCVMFS(spec_json, meta_json)
if result:
(cvmfs_path, cvmfs_mountpoint) = result
if cvmfs_path:
logging.debug("cvmfs is needed! (%s)", cvmfs_path)
print "cvmfs is needed! (%s)" % cvmfs_path
cvmfs_ready = False
if need_separate_rootfs:
os_cvmfs_path = "%s%s" % (os_image_dir, cvmfs_mountpoint)
if os.path.exists(os_cvmfs_path) and os.path.isdir(os_cvmfs_path):
cvmfs_ready = True
logging.debug("The os image has /cvmfs/cms.cern.ch!")
print "The os image has /cvmfs/cms.cern.ch!"
if not cvmfs_ready:
local_cvmfs = ""
local_cvmfs = check_cvmfs_repo(cvmfs_path[7:])
if len(local_cvmfs) > 0:
mount_dict[cvmfs_mountpoint] = local_cvmfs
logging.debug("The cvmfs is installed on the local host, and its mountpoint is: %s", local_cvmfs)
print "The cvmfs is installed on the local host, and its mountpoint is: %s" % local_cvmfs
else:
logging.debug("The cvmfs is not installed on the local host.")
print "The cvmfs is not installed on the local host."
if cvmfs_path.find("cms.cern.ch") != -1:
is_cms_cvmfs_app = 1 #cvmfs is needed to deliver cms.cern.ch repo, and the local host has no cvmfs installed.
if not cvmfs_http_proxy or len(cvmfs_http_proxy) == 0:
cleanup(tempfile_list, tempdir_list)
logging.debug("Access CVMFS through Parrot requires the --cvmfs_http_proxy of umbrella to be set.")
sys.exit("Access CVMFS through Parrot requires the --cvmfs_http_proxy of umbrella to be set.")
#currently, if the logic reaches here, only parrot execution engine is allowed.
cvmfs_cms_siteconf_mountpoint = set_cvmfs_cms_siteconf(sandbox_dir)
#add cvmfs SITEINFO into mount_dict
if sandbox_mode == "docker":
list1 = cvmfs_cms_siteconf_mountpoint.split(' ')
logging.debug("Add mountpoint (%s:%s) into mount_dict for cvmfs SITEINFO", list1[0], list1[1])
mount_dict[list1[0]] = list1[1]
if sandbox_mode != "parrot":
logging.debug("To use parrot to access cvmfs, cctools binary is needed")
host_cctools_path = cctools_download(sandbox_dir, hardware_platform, linux_distro, 'unpack')
logging.debug("Add mountpoint (%s:%s) into mount_dict", host_cctools_path, host_cctools_path)
mount_dict[host_cctools_path] = host_cctools_path
parrotize_user_cmd(user_cmd, sandbox_dir, cwd_setting, linux_distro, hardware_platform, meta_json, cvmfs_http_proxy)
if need_separate_rootfs:
new_os_image_dir = ""
#if some packages from package managers are needed, ceate a intermediate os image with all the packages ready.
if pac_list:
new_sw_sec = spec_json["package_manager"]["config"]
(new_os_id, pm_cmd) = cal_new_os_id(spec_json["package_manager"], os_id, pac_list)
new_os_image_dir = "%s/cache/%s/%s" % (os.path.dirname(sandbox_dir), new_os_id, item)
logging.debug("Installing the package into the image (%s), and create a new image: %s ...", os_image_dir, new_os_image_dir)
if os.path.exists(new_os_image_dir) and os.path.isdir(new_os_image_dir):
logging.debug("the new os image already exists!")
#use the intermidate os image which has all the dependencies from package manager ready as the os image
os_image_dir = new_os_image_dir
os_id = new_os_id
pass
else:
logging.debug("the new os image does not exist!")
new_env_para_dict = {}
#install dependency specified in the spec_json["package_manager"]["config"] section
logging.debug('Install dependency specified in the spec_json["package_manager"]["config"] section.')
if sandbox_mode == "destructive":
software_install(mount_dict, new_env_para_dict, new_sw_sec, meta_json, sandbox_dir, 1, osf_auth)
#install dependencies through package managers
rc, stdout, stderr = func_call(pm_cmd)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
else:
software_install(mount_dict, new_env_para_dict, new_sw_sec, meta_json, sandbox_dir, 0, osf_auth)
#install dependencies through package managers
logging.debug("Create an intermediate OS image with all the dependencies from package managers ready!")
workflow_repeat(cwd_setting, sandbox_dir, sandbox_mode, output_f_dict, output_d_dict, input_dict, env_para_dict, pm_cmd, hardware_platform, host_linux_distro, distro_name, distro_version, need_separate_rootfs, os_image_dir, os_id, host_cctools_path, cvmfs_cms_siteconf_mountpoint, mount_dict, mount_dict, meta_json, new_os_image_dir)
logging.debug("Finishing creating the intermediate OS image!")
#use the intermidate os image which has all the dependencies from package manager ready as the os image
os_image_dir = new_os_image_dir
os_id = new_os_id
if spec_json.has_key("software") and spec_json["software"]:
software_install(mount_dict, env_para_dict, spec_json["software"], meta_json, sandbox_dir, 0, osf_auth)
else:
logging.debug("this spec does not have software section!")
software_install(mount_dict, env_para_dict, "", meta_json, sandbox_dir, 0, osf_auth)
sw_mount_dict = dict(mount_dict) #sw_mount_dict will be used later to config the $PATH
if spec_json.has_key("data") and spec_json["data"]:
data_install(spec_json["data"], meta_json, sandbox_dir, mount_dict, env_para_dict, osf_auth)
else:
logging.debug("this spec does not have data section!")
workflow_repeat(cwd_setting, sandbox_dir, sandbox_mode, output_f_dict, output_d_dict, input_dict, env_para_dict, user_cmd, hardware_platform, host_linux_distro, distro_name, distro_version, need_separate_rootfs, os_image_dir, os_id, host_cctools_path, cvmfs_cms_siteconf_mountpoint, mount_dict, sw_mount_dict, meta_json, "")
def dependency_check(item):
"""Check whether an executable exists or not.
Args:
item: the name of the executable to be found.
Returns:
If the executable can be found through $PATH, return 0;
Otherwise, return -1.
"""
print "dependency check -- ", item, " "
result = which_exec(item)
if result == None:
logging.debug("Failed to find the executable `%s` through $PATH.", item)
print "Failed to find the executable `%s` through $PATH." % item
return -1
else:
logging.debug("Find the executable `%s` through $PATH.", item)
print "Find the executable `%s` through $PATH." % item
return 0
def get_instance_id(image_id, instance_type, ec2_key_pair, ec2_security_group):
""" Start one VM instance through Amazon EC2 command line interface and return the instance id.
Args:
image_id: the Amazon Image Identifier.
instance_type: the Amazon EC2 instance type used for the task.
ec2_key_pair: the path of the key-pair to use when launching an instance.
ec2_security_group: the security group within which the EC2 instance should be run.
Returns:
If no error happens, returns the id of the started instance.
Otherwise, directly exit.
"""
sg_option = ''
if ec2_security_group:
sg_option = ' -g ' + ec2_security_group
cmd = 'ec2-run-instances %s -t %s -k %s %s --associate-public-ip-address true' % (image_id, instance_type, ec2_key_pair, sg_option)
logging.debug("Starting an instance: %s", cmd)
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = True)
(stdout, stderr) = p.communicate()
rc = p.returncode
logging.debug("returncode: %d\nstdout: %s\nstderr: %s", rc, stdout, stderr)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
str = "\nINSTANCE"
index = stdout.find(str)
if index == -1:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fail to get the instance id!")
else:
instance_id = stdout[(index+9):(index+20)]
return instance_id
def terminate_instance(instance_id):
"""Terminate an instance.
Args:
instance_id: the id of the VM instance.
Returns:
None.
"""
logging.debug("Terminate the ec2 instance: %s", instance_id)
cmd = 'ec2-terminate-instances %s' % instance_id
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = True)
def get_public_dns(instance_id):
"""Get the public dns of one VM instance from Amazon EC2.
`ec2-run-instances` can not directly return the public dns of the instance, so this function is needed to check the result of `ec2-describe-instances` to obtain the public dns of the instance.
Args:
instance_id: the id of the VM instance.
Returns:
If no error happens, returns the public dns of the instance.
Otherwise, directly exit.
"""
public_dns = ''
while public_dns == None or public_dns == '' or public_dns == 'l':
cmd = 'ec2-describe-instances ' + instance_id
p = subprocess.Popen(cmd, stdout = subprocess.PIPE, shell = True)
(stdout, stderr) = p.communicate()
rc = p.returncode
logging.debug("returncode: %d\nstdout: %s\nstderr: %s", rc, stdout, stderr)
if rc != 0:
subprocess_error(cmd, rc, stdout, stderr)
str = "\nPRIVATEIPADDRESS"
index = stdout.find(str)
if index >= 0:
index1 = stdout.find("ec2", index + 1)
if index1 == -1:
time.sleep(5)
continue
public_dns = stdout[index1:-1]
break
return public_dns
def add2spec(item, source_dict, target_dict):
"""Abstract the metadata information (source format checksum size) from source_dict (metadata database) and add these information into target_dict (umbrella spec).
For any piece of metadata information, if it already exists in target_dict, do nothing; otherwise, add it into the umbrella spec.
Args:
item: the name of a dependency
source_dict: fragment of an Umbrella metadata database
target_dict: fragement of an Umbrella specficiation
Returns:
None
"""
#item must exist inside target_dict.
ident = None
if source_dict.has_key("checksum"):
checksum = source_dict["checksum"]
ident = checksum
if not target_dict.has_key("id"):
target_dict["id"] = ident
if not target_dict.has_key(checksum):
target_dict["checksum"] = source_dict["checksum"]
if source_dict.has_key("source"):
if len(source_dict["source"]) == 0:
cleanup(tempfile_list, tempdir_list)
logging.critical("the source attribute of %s can not be empty!" % item)
sys.exit("the source attribute of %s can not be empty!" % item)
else:
source = source_dict["source"][0]
#if checksum is not provided in source_dict, the first url in the source section will be set to the ident.
if not ident and not target_dict.has_key("id"):
target_dict["id"] = source
if not target_dict.has_key("source"):
target_dict["source"] = list(source_dict["source"])
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s does not have source attribute in the umbrella metadata database!", item)
sys.exit("%s does not have source attribute in the umbrella metadata database!" % item)
if source_dict.has_key("format") and not target_dict.has_key("format"):
target_dict["format"] = source_dict["format"]
if source_dict.has_key("size") and not target_dict.has_key("size"):
target_dict["size"] = source_dict["size"]
if source_dict.has_key("uncompressed_size") and not target_dict.has_key("uncompressed_size"):
target_dict["uncompressed_size"] = source_dict["uncompressed_size"]
def add2db(item, source_dict, target_dict):
"""Add the metadata information (source format checksum size) about item from source_dict (umbrella specification) to target_dict (metadata database).
The item can be identified through two mechanisms: checksum attribute or one source location, which is used when checksum is not applicable for this item.
If the item has been in the metadata database, do nothing; otherwise, add it, together with its metadata, into the metadata database.
Args:
item: the name of a dependency
source_dict: fragment of an Umbrella specification
target_dict: fragement of an Umbrella metadata database
Returns:
None
"""
if not item in target_dict:
target_dict[item] = {}
ident = None
if source_dict.has_key("checksum"):
checksum = source_dict["checksum"]
if target_dict[item].has_key(checksum):
logging.debug("%s has been inside the metadata database!", item)
return
ident = checksum
target_dict[item][ident] = {}
target_dict[item][ident]["checksum"] = source_dict["checksum"]
if source_dict.has_key("source"):
if len(source_dict["source"]) == 0:
cleanup(tempfile_list, tempdir_list)
logging.critical("the source attribute of %s can not be empty!" % item)
sys.exit("the source attribute of %s can not be empty!" % item)
else:
source = source_dict["source"][0]
if target_dict[item].has_key(source):
logging.debug("%s has been inside the metadata database!", item)
return
#if checksum is not provided in source_dict, the first url in the source section will be set to the ident.
if not ident:
ident = source
target_dict[item][ident] = {}
target_dict[item][ident]["source"] = list(source_dict["source"])
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s does not have source attribute in the umbrella specification!", item)
sys.exit("%s does not have source attribute in the umbrella specification!" % item)
if source_dict.has_key("format"):
target_dict[item][ident]["format"] = source_dict["format"]
if source_dict.has_key("size"):
target_dict[item][ident]["size"] = source_dict["size"]
if source_dict.has_key("uncompressed_size"):
target_dict[item][ident]["uncompressed_size"] = source_dict["uncompressed_size"]
def prune_attr(dict_item, attr_list):
"""Remove certain attributes from a dict.
If a specific ttribute does not exist, pass.
Args:
dict_item: a dict
attr_list: a list of attributes which will be removed from the dict.
Returns:
None
"""
for item in attr_list:
if dict_item.has_key(item):
del dict_item[item]
def prune_spec(json_object):
"""Remove the metadata information from a json file (which represents an umbrella specification).
Note: the original json file will not be changed by this function.
Args:
json_object: a json file representing an umbrella specification
Returns:
temp_json: a new json file without metadata information
"""
logging.debug("Remove the metadata information from %s.\n", json_object)
temp_json = dict(json_object)
attr_list = ["source", "checksum", "format", "size", "uncompressed_size"]
if temp_json.has_key("os"):
os_sec = temp_json["os"]
if os_sec:
prune_attr(os_sec, attr_list)
if temp_json.has_key("package_manager") and temp_json["package_manager"] \
and temp_json["package_manager"].has_key("config") and temp_json["package_manager"]["config"]:
pm_config_sec = temp_json["package_manager"]["config"]
if pm_config_sec:
for item in pm_config_sec:
prune_attr(pm_config_sec[item], attr_list)
if temp_json.has_key("software"):
software_sec = temp_json["software"]
if software_sec:
for item in software_sec:
prune_attr(software_sec[item], attr_list)
if temp_json.has_key("data"):
data_sec = temp_json["data"]
if data_sec:
for item in data_sec:
prune_attr(data_sec[item], attr_list)
return temp_json
def abstract_metadata(spec_json, meta_path):
"""Abstract metadata information from a self-contained umbrella spec into a metadata database.
Args:
spec_json: a dict including the contents from a json file
meta_path: the path of the metadata database.
Returns:
If the umbrella spec is not complete, exit directly.
Otherwise, return None.
"""
hardware_sec = attr_check("hardware", spec_json, "hardware")
hardware_arch = attr_check("hardware", hardware_sec, "arch")
metadata = {}
os_sec = attr_check("os", spec_json, "os")
os_name = attr_check("os", os_sec, "name")
os_version = attr_check("os", os_sec, "version")
os_item = "%s-%s-%s" % (os_name, os_version, hardware_arch)
os_item = os_item.lower()
add2db(os_item, os_sec, metadata)
if spec_json.has_key("package_manager") and spec_json["package_manager"] \
and spec_json["package_manager"].has_key("config") and spec_json["package_manager"]["config"]:
pm_config_sec = spec_json["package_manager"]["config"]
if pm_config_sec:
for item in pm_config_sec:
add2db(item, pm_config_sec[item], metadata)
if spec_json.has_key("software"):
software_sec = spec_json["software"]
if software_sec:
for item in software_sec:
add2db(item, software_sec[item], metadata)
if spec_json.has_key("data"):
data_sec = spec_json["data"]
if data_sec:
for item in data_sec:
add2db(item, data_sec[item], metadata)
with open(meta_path, 'w') as f:
json.dump(metadata, f, indent=4)
logging.debug("dump the metadata information from the umbrella spec to %s" % meta_path)
print "dump the metadata information from the umbrella spec to %s" % meta_path
def needCVMFS(spec_json, meta_json):
"""For each dependency in the spec_json, check whether cvmfs is needed to deliver it.
Args:
spec_json: the json object including the specification.
meta_json: the json object including all the metadata of dependencies.
Returns:
if cvmfs is needed, return the cvmfs url. Otherwise, return None
"""
for sec_name in ["software", "data", "package_manager"]:
if spec_json.has_key(sec_name) and spec_json[sec_name]:
sec = spec_json[sec_name]
if sec_name == "package_manager":
if sec.has_key("config") and sec["config"]:
sec = sec["config"]
else:
logging.debug("%s does not have config attribute!", sec_name)
break
for item in sec:
item_id = ""
if sec[item].has_key("id") and len(sec[item]["id"]) > 0:
item_id = sec[item]["id"]
mountpoint = sec[item]["mountpoint"]
result = meta_search(meta_json, item, item_id)
if result.has_key("source") and len(result["source"]) > 0:
url = result["source"][0]
if url[:5] == "cvmfs":
return (url, mountpoint)
return None
def cleanup(filelist, dirlist):
"""Cleanup the temporary files and dirs created by umbrella
Args:
filelist: a list including file paths
dirlist: a list including dir paths
Returns:
None
"""
#cleanup the temporary files
for item in filelist:
if os.path.exists(item):
logging.debug("cleanup temporary file: %s", item)
print "cleanup temporary file: ", item
os.remove(item)
#cleanup the temporary dirs
for item in dirlist:
if os.path.exists(item):
logging.debug("cleanup temporary dir: %s", item)
print "cleanup temporary dir: ", item
shutil.rmtree(item)
def separatize_spec(spec_json, meta_json, target_type):
"""Given an umbrella specification and an umbrella metadata database, generate a self-contained umbrella specification or a metadata database only including the informationnecessary for the umbrella spec.
If the target_type is spec, then generate a self-contained umbrella specification.
If the target_type is db, then generate a metadata database only including the information necessary for the umbrella spec.
Args:
spec_json: the json object including the specification.
meta_json: the json object including all the metadata of dependencies.
target_type: the type of the target json file, which can be an umbrella spec or an umbrella metadata db.
Returns:
metadata: a json object
"""
#pull the metadata information of the spec from the meatadata db to the spec
if target_type == "spec":
metadata = dict(spec_json)
#pull the metadata information of the spec from the metadata db into a separate db
if target_type == "meta":
metadata = {}
hardware_sec = attr_check("hardware", spec_json, "hardware")
hardware_arch = attr_check("hardware", hardware_sec, "arch")
os_sec = attr_check("os", spec_json, "os")
os_name = attr_check("os", os_sec, "name")
os_version = attr_check("os", os_sec, "version")
os_item = "%s-%s-%s" % (os_name, os_version, hardware_arch)
os_item = os_item.lower()
ident = None
if os_sec.has_key("id"):
ident = os_sec["id"]
source = meta_search(meta_json, os_item, ident)
if target_type == "spec":
add2spec(os_item, source, metadata["os"])
if target_type == "meta":
add2db(os_item, source, metadata)
if spec_json.has_key("package_manager") and spec_json["package_manager"] \
and spec_json["package_manager"].has_key("config") and spec_json["package_manager"]["config"]:
pm_config_sec = spec_json["package_manager"]["config"]
if pm_config_sec:
for item in pm_config_sec:
ident = None
if pm_config_sec[item].has_key("id"):
ident = pm_config_sec[item]["id"]
source = meta_search(meta_json, item, ident)
if target_type == "spec":
add2spec(os_item, source, metadata["package_manager"]["config"][item])
if target_type == "meta":
add2db(item, source, metadata)
if spec_json.has_key("software"):
software_sec = spec_json["software"]
if software_sec:
for item in software_sec:
ident = None
if software_sec[item].has_key("id"):
ident = software_sec[item]["id"]
source = meta_search(meta_json, item, ident)
if target_type == "spec":
add2spec(os_item, source, metadata["software"][item])
if target_type == "meta":
add2db(item, source, metadata)
if spec_json.has_key("data"):
data_sec = spec_json["data"]
if data_sec:
for item in data_sec:
ident = None
if data_sec[item].has_key("id"):
ident = data_sec[item]["id"]
source = meta_search(meta_json, item, ident)
if target_type == "spec":
add2spec(os_item, source, metadata["data"][item])
if target_type == "meta":
add2db(item, source, metadata)
return metadata
def json2file(filepath, json_item):
"""Write a json object into a file
Args:
filepath: a file path
json_item: a dict representing a json object
Returns:
None
"""
with open(filepath, 'w') as f:
json.dump(json_item, f, indent=4)
logging.debug("dump a json object from the umbrella spec to %s" % filepath)
print "dump a json object from the umbrella spec to %s" % filepath
def path_exists(filepath):
"""Check the validity and existence of a file path.
Args:
filepath: a file path
Returns:
Exit directly if any error happens.
Otherwise, returns None.
"""
logging.debug("Checking file path: %s", filepath)
if os.path.exists(filepath):
cleanup(tempfile_list, tempdir_list)
logging.debug("The file (%s) already exists, please specify a new path!", filepath)
sys.exit("The file (%s) already exists, please specify a new path!" % filepath)
def dir_create(filepath):
"""Create the directory for it if necessary. If the file already exists, exit directly.
Args:
filepath: a file path
Returns:
Exit directly if any error happens.
Otherwise, returns None.
"""
dirpath = os.path.dirname(filepath)
if not os.path.exists(dirpath):
os.makedirs(dirpath)
else:
if not os.path.isdir(dirpath):
cleanup(tempfile_list, tempdir_list)
logging.debug("The basename of the file (%s) is not a directory!\n", dirpath)
sys.exit("The basename of the file (%s) is not a directory!\n" % dirpath)
def validate_meta(meta_json):
"""Validate a metadata db.
The current standard for a valid metadata db is: for each item, the "source" attribute must exist and not be not empty.
Args:
meta_json: a dict object representing a metadata db.
Returns:
If error happens, return directly with the error info.
Otherwise, None.
"""
logging.debug("Starting validating the metadata db ....\n")
print "Starting validating the metadata db ...."
for name in meta_json:
for ident in meta_json[name]:
logging.debug("check for %s with the id of %s ...", name, ident)
print "check for %s with the id of %s ..." % (name, ident)
attr_check(name, meta_json[name][ident], "source", 1)
logging.debug("Finish validating the metadata db ....\n")
print "Finish validating the metadata db successfully!"
def validate_spec(spec_json, meta_json = None):
"""Validate a spec_json.
Args:
spec_json: a dict object representing a specification.
meta_json: a dict object representing a metadata db.
Returns:
If error happens, return directly with the error info.
Otherwise, None.
"""
logging.debug("Starting validating the spec file ....\n")
print "Starting validating the spec file ...."
#validate the following three sections: hardware, kernel and os.
env_parameter_init(spec_json["hardware"], spec_json["kernel"], spec_json["os"])
for sec_name in ["software", "data", "package_manager"]:
if spec_json.has_key(sec_name) and spec_json[sec_name]:
sec = spec_json[sec_name]
if sec_name == "package_manager":
if sec.has_key("config") and sec["config"]:
sec = sec["config"]
else:
logging.debug("%s does not have config attribute!", sec_name)
break
for item in sec:
if (sec[item].has_key("mountpoint") and sec[item]["mountpoint"]) \
or (sec[item].has_key("mount_env") and sec[item]["mount_env"]):
pass
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s in the %s section should have either <mountpoint> or <mount_env>!\n", item, sec_name)
sys.exit("%s in the %s section should have either <mountpoint> or <mount_env>!\n" % (item, sec_name))
if sec[item].has_key("source") and len(sec[item]["source"]) > 0:
pass
else:
if meta_json:
ident = None
if sec[item].has_key("id"):
ident = sec[item]["id"]
result = meta_search(meta_json, item, ident)
if result.has_key("source") and len(result["source"]) > 0:
pass
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s in the metadata db should have <source> attr!\n", item)
sys.exit("%s in the metadata db should have <source> attr!\n", item)
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s in the %s section should have <source> attr!\n", item, sec_name)
sys.exit("%s in the %s section should have <source> attr!\n" % (item, sec_name))
logging.debug("Finish validating the spec file ....\n")
print "Finish validating the spec file successfully!"
def osf_create(username, password, user_id, proj_name, is_public):
"""Create an OSF project, and return the project id.
Args:
username: an OSF username
password: an OSF password
user_id: the id of an OSF user
proj_name: the name of the OSF project
is_public: set to 1 if the project is public; set to 0 if the project is private.
Returns:
the id of the OSF project
"""
#first check whether the user already has an existing OSF project having the same name
url="https://api.osf.io:443/v2/users/%s/nodes/" % user_id
nodes=set()
#the response results are splitted into pages, and each page has 10 items.
while url:
r=requests.get(url)
if r.status_code != 200:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to check the projects contributed by the user (%d): %s!" % (r.status_code, r.reason))
for data in r.json()['data']:
nodes.add(data['attributes']['title'])
url=r.json()['links']['next']
if proj_name in nodes:
cleanup(tempfile_list, tempdir_list)
sys.exit("The project name (%s) already exists!" % proj_name)
#create the new project
auth = (username, password)
payload = {
"type": "nodes",
"title": proj_name,
"category": "project",
"public": is_public
}
url="https://api.osf.io:443/v2/nodes/"
r=requests.post(url, auth=auth, data=payload)
if r.status_code != 201:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to create the new project (%d): %s!" % (r.status_code, r.reason))
proj_id = r.json()['data']['id']
return proj_id
def osf_upload(username, password, proj_id, source):
"""upload a file from source into the OSF project identified by proj_id.
Args:
username: an OSF username
password: an OSF password
proj_id: the id of the OSF project
source: a file path
Returns:
the OSF download url of the uploaded file
"""
print "Upload %s to OSF ..." % source
logging.debug("Upload %s to OSF ...",source)
url="https://files.osf.io/v1/resources/%s/providers/osfstorage/" % proj_id
payload = {"kind":"file", "name":os.path.basename(source)}
auth = (username, password)
f=open(source, 'rb')
r=requests.put(url, params=payload, auth = auth, data=f)
if r.status_code != 201 and r.status_code != 200:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to upload the file %s to OSF(%d): %s!" % (source, r.status_code, r.reason))
return r.json()['data']['links']['download']
def osf_download(username, password, osf_url, dest):
"""download a file pointed by an OSF url to dest.
Args:
username: an OSF username
password: an OSF password
osf_url: the OSF download url
dest: the destination of the OSF file
Returns:
If the osf_url is downloaded successfully, return None;
Otherwise, directly exit.
"""
if not found_requests:
cleanup(tempfile_list, tempdir_list)
logging.critical("\nDownloading private stuff from OSF requires a python package - requests. Please check the installation page of requests:\n\n\thttp://docs.python-requests.org/en/latest/user/install/\n")
sys.exit("\nDownloading private stuff from OSF requires a python package - requests. Please check the installation page of requests:\n\n\thttp://docs.python-requests.org/en/latest/user/install/\n")
print "Download %s from OSF to %s" % (osf_url, dest)
logging.debug("Download %s from OSF to %s", osf_url, dest)
word = 'resources'
proj_id = osf_url[(osf_url.index(word) + len(word) + 1):(osf_url.index(word) + len(word) + 6)]
url="https://api.osf.io:443/v2/nodes/%s/" % proj_id
r=requests.get(url)
r2 = None
if r.status_code == 401:
if username == None or password == None:
cleanup(tempfile_list, tempdir_list)
sys.exit("The OSF resource (%s) is private (%d): %s! To use the OSF resource, you need to provide a legal OSF username and password." % (url, r.status_code, r.reason))
auth = (username, password)
r1=requests.get(url, auth=auth)
if r1.status_code != 200:
cleanup(tempfile_list, tempdir_list)
sys.exit("The OSF resource (%s) is private (%d): %s! The username or password is incorrect!" % (url, r1.status_code, r1.reason))
else:
r2=requests.get(osf_url, auth=auth, stream=True)
else:
r2=requests.get(osf_url, stream=True)
if r2.status_code != 200:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to download the osf resource: %s (%d): %s!" % (r2.status_code, r2.reason))
chunk_size=10240
if not os.path.exists(os.path.dirname(dest)):
os.makedirs(os.path.dirname(dest))
with open(dest, 'wb') as fd:
for chunk in r2.iter_content(chunk_size):
fd.write(chunk)
def s3_create(bucket_name, acl):
"""Create a s3 bucket
Args:
bucket_name: the bucket name
acl: the access control, which can be: private, public-read
Returns:
bucket: an S3.Bucket instance
"""
#create the connection with s3
s3 = boto3.resource('s3')
#list all the bucket names
buckets = set()
try:
for bucket in s3.buckets.all():
buckets.add(bucket.name)
except botocore.exceptions.ClientError as e:
cleanup(tempfile_list, tempdir_list)
sys.exit(e.message)
except Exception as e:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to list all the current buckets: %s!" % e)
#check whether the bucket name already exists
if bucket_name in buckets:
cleanup(tempfile_list, tempdir_list)
sys.exit("The bucket name (%s) already exists!" % bucket_name)
#create a new bucket
try:
s3.create_bucket(Bucket=bucket_name)
except Exception as e:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to create the new bucket (%s): %s!" % (bucket_name, e))
#obtain the created bucket
bucket = s3.Bucket(bucket_name)
#set access control
#ACL totally can be one of these options: 'private'|'public-read'|'public-read-write'|'authenticated-read'
#for now, when an user uses Umbrella to upload to s3, the acl can only be private, public-read.
try:
bucket.Acl().put(ACL=acl)
except botocore.exceptions.ClientError as e:
cleanup(tempfile_list, tempdir_list)
sys.exit(e.message)
except Exception as e:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to list all the current buckets: %s!" % e)
return bucket
def s3_upload(bucket, source, acl):
"""Upload a local file to s3
Args:
bucket: an S3.Bucket instance
source: the local file path
acl: the access control, which can be: private, public-read
Returns:
link: the link of a s3 object
"""
print "Upload %s to S3 ..." % source
logging.debug("Upload %s to S3 ...", source)
key = os.path.basename(source)
data = open(source, 'rb')
try:
#acl on the bucket does not automatically apply to all the objects in it. Acl must be set on each object.
bucket.put_object(ACL=acl, Key=key, Body=data) #https://s3.amazonaws.com/testhmeng/s3
except botocore.exceptions.ClientError as e:
cleanup(tempfile_list, tempdir_list)
sys.exit(e.message)
except Exception as e:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to upload the file (%s) to S3: %s!" % (source, e))
return "%s/%s/%s" % (s3_url, bucket.name, key)
def s3_download(link, dest):
"""Download a s3 file to dest
Args:
link: the link of a s3 object. e.g., https://s3.amazonaws.com/testhmeng/s3
dest: a local file path
Returns:
None
"""
if not found_boto3 or not found_botocore:
cleanup(tempfile_list, tempdir_list)
logging.critical("\nUploading umbrella spec dependencies to s3 requires a python package - boto3. Please check the installation page of boto3:\n\n\thttps://boto3.readthedocs.org/en/latest/guide/quickstart.html#installation\n")
sys.exit("\nUploading umbrella spec dependencies to s3 requires a python package - boto3. Please check the installation page of boto3:\n\n\thttps://boto3.readthedocs.org/en/latest/guide/quickstart.html#installation\n")
print "Download %s from S3 to %s" % (link, dest)
logging.debug("Download %s from S3 to %s", link, dest)
s3 = boto3.resource('s3')
if (len(s3_url)+1) >= len(link):
cleanup(tempfile_list, tempdir_list)
sys.exit("The s3 object link (%s) is invalid! The correct format shoulde be <%s>/<bucket_name>/<key>!" % (link, s3_url))
m = link[(len(s3_url)+1):] #m format: <bucket_name>/<key>
i = m.find('/')
if i == -1:
cleanup(tempfile_list, tempdir_list)
sys.exit("The s3 object link (%s) is invalid! The correct format shoulde be <%s>/<bucket_name>/<key>!" % (link, s3_url))
bucket_name = m[:i]
if (i+1) >= len(m):
cleanup(tempfile_list, tempdir_list)
sys.exit("The s3 object link (%s) is invalid! The correct format shoulde be <%s>/<bucket_name>/<key>!" % (link, s3_url))
key = m[(i+1):]
if not os.path.exists(os.path.dirname(dest)):
os.makedirs(os.path.dirname(dest))
#the download url can be automatically combined through bucket name and key
try:
s3.Object(bucket_name, key).download_file(dest)
except botocore.exceptions.ClientError as e:
cleanup(tempfile_list, tempdir_list)
sys.exit(e.message)
except Exception as e:
cleanup(tempfile_list, tempdir_list)
sys.exit("Fails to download the object (%s) from the bucket(%s):! Please ensure you have the right permission to download these s3 objects: %s!" % (key, bucket_name, e))
def has_source(sources, target):
"""Check whether the sources includes a url from the specific target.
Args:
sources: a list of url
target: the specific resource url. For example, s3, osf.
Returns:
If a url from the specific target exists, return True.
Otherwise, return False.
"""
if not sources or len(sources) == 0:
return False
n = len(target)
for source in sources:
if len(source) > n and source[:n] == target:
return True
return False
def spec_upload(spec_json, meta_json, target_info, sandbox_dir, osf_auth=None, s3_bucket=None):
"""Upload each dependency in an umbrella spec to the target (OSF or s3), and add the new target download url into the umbrella spec.
The source of the dependencies can be anywhere supported by umbrella: http
https git local s3 osf. Umbrella always first downloads each dependency into
its local cache, then upload the dep from its local cache to the target.
Args:
spec_json: the json object including the specification.
meta_json: the json object including all the metadata of dependencies.
target_info: the info necessary to communicate with the remote target (i.e., OSF, s3)
sandbox_dir: the sandbox dir for temporary files like Parrot mountlist file.
osf_auth: the osf authentication info including osf_username and osf_password.
s3_bucket: an S3.Bucket instance
Returns:
None
"""
mount_dict = {}
env_para_dict = {}
global upload_count
print "Upload the dependencies from the umbrella spec to %s ..." % target_info[0]
logging.debug("Upload the dependencies from the umbrella spec to %s ...", target_info[0])
if spec_json.has_key("os") and spec_json["os"] and spec_json["os"].has_key("id") and spec_json["os"]["id"]:
os_id = spec_json["os"]["id"]
if spec_json.has_key("hardware") and spec_json["hardware"] and spec_json.has_key("kernel") and spec_json["kernel"] and spec_json.has_key("os") and spec_json["os"]:
logging.debug("Setting the environment parameters (hardware, kernel and os) according to the specification file ....")
(hardware_platform, cpu_cores, memory_size, disk_size, kernel_name, kernel_version, linux_distro, distro_name, distro_version, os_id) = env_parameter_init(spec_json["hardware"], spec_json["kernel"], spec_json["os"])
item = '%s-%s-%s' % (distro_name, distro_version, hardware_platform) #example of item here: redhat-6.5-x86_64
os_image_dir = "%s/cache/%s/%s" % (os.path.dirname(sandbox_dir), os_id, item)
logging.debug("A separate OS (%s) is needed!", os_image_dir)
mountpoint = '/'
action = 'unpack'
if spec_json["os"].has_key("source") or attr_check(item, meta_search(meta_json, item, os_id), "source", 1):
if spec_json["os"].has_key("source"):
sources = spec_json["os"]["source"]
else:
sources = meta_search(meta_json, item, os_id)["source"]
if has_source(sources, target_info[0]):
logging.debug("The os section already has a url from %s!", target_info[0])
print "The os section already has a url from %s!" % target_info[0]
else:
upload_count += 1
r3 = dependency_process(item, os_id, action, meta_json, sandbox_dir, osf_auth)
logging.debug("Add mountpoint (%s:%s) into mount_dict for /.", mountpoint, r3)
mount_dict[mountpoint] = r3
if target_info[0] == "osf":
osf_url = osf_upload(target_info[1], target_info[2], target_info[3], os_image_dir + ".tar.gz")
spec_json["os"]["source"].append("osf+" + osf_url)
elif target_info[0] == "s3":
s3_url = s3_upload(s3_bucket, os_image_dir + ".tar.gz", target_info[1])
spec_json["os"]["source"].append("s3+" + s3_url)
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("the os section does not has source attr!")
sys.exit("the os section does not has source attr!")
for sec_name in ["data"]:
if spec_json.has_key(sec_name) and spec_json[sec_name]:
sec = spec_json[sec_name]
for item in sec:
if sec[item].has_key("source") or attr_check(item, meta_search(meta_json, item, id), "source", 1):
if sec[item].has_key("source"):
sources = sec[item]["source"]
else:
sources = meta_search(meta_json, item, id)["source"]
if has_source(sources, target_info[0]):
logging.debug("%s already has a url from %s!", item, target_info[0])
print "%s already has a url from %s!" % (item, target_info[0])
continue
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s does not has the source attr!", item)
sys.exit("%s does not has the source attr!" % item)
upload_count += 1
data_install(sec, meta_json, sandbox_dir, mount_dict, env_para_dict, osf_auth, item)
if sec[item]["format"] == "tgz":
source_url = mount_dict[sec[item]["mountpoint"]] + ".tar.gz"
else:
source_url = mount_dict[sec[item]["mountpoint"]]
if target_info[0] == "osf":
osf_url = osf_upload(target_info[1], target_info[2], target_info[3], source_url)
sec[item]["source"].append("osf+" + osf_url)
elif target_info[0] == "s3":
s3_url = s3_upload(s3_bucket, source_url, target_info[1])
sec[item]["source"].append("s3+" + s3_url)
for sec_name in ["software", "package_manager"]:
if spec_json.has_key(sec_name) and spec_json[sec_name]:
sec = spec_json[sec_name]
if sec_name == "package_manager":
if sec.has_key("config") and sec["config"]:
sec = sec["config"]
else:
logging.debug("%s does not have config attribute!", sec_name)
break
for item in sec:
if sec[item].has_key("source") or attr_check(item, meta_search(meta_json, item, id), "source", 1):
if sec[item].has_key("source"):
sources = sec[item]["source"]
else:
sources = meta_search(meta_json, item, id)["source"]
if has_source(sources, target_info[0]):
logging.debug("%s already has a url from %s!", item, target_info[0])
print "%s already has a url from %s!" % (item, target_info[0])
continue
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("%s does not has the source attr!", item)
sys.exit("%s does not has the source attr!" % item)
upload_count += 1
software_install(mount_dict, env_para_dict, sec, meta_json, sandbox_dir, 0, osf_auth, item)
#ignore upload resouces from cvmfs
if (not sec[item].has_key("mountpoint")) or (not mount_dict.has_key(sec[item]["mountpoint"])) or mount_dict[sec[item]["mountpoint"]] == "":
continue
if sec[item]["format"] == "tgz":
source_url = mount_dict[sec[item]["mountpoint"]] + ".tar.gz"
else:
source_url = mount_dict[sec[item]["mountpoint"]]
if target_info[0] == "osf":
osf_url = osf_upload(target_info[1], target_info[2], target_info[3], source_url)
sec[item]["source"].append("osf+" + osf_url)
elif target_info[0] == "s3":
s3_url = s3_upload(s3_bucket, source_url, target_info[1])
sec[item]["source"].append("s3+" + s3_url)
def dep_build(d, name):
"""Build the metadata info of a dependency.
Args:
d: a dependency object
name: the name of the dependency
Returns:
None
"""
#check the validity of the 'format' attr
formats = ['plain', 'tgz']
form = attr_check(name, d, "format")
if not form in formats:
cleanup(tempfile_list, tempdir_list)
sys.exit("The format attr can only be: %s!\n", ' or '.join(formats))
#check the validity of the 'source' attr
source = attr_check(name, d, "source", 1)
if source == '':
cleanup(tempfile_list, tempdir_list)
sys.exit("The source of %s is empty!" % name)
if source[0] != '/':
cleanup(tempfile_list, tempdir_list)
sys.exit("The source of %s should be a local path!" % name)
#set the file size
size = os.stat(source).st_size
d["size"] = str(size)
#set the uncompressed size of tgz file
if form == "tgz":
full_size = get_tgz_size(source)
d["uncompressed_size"] = str(full_size)
#set the 'checksum' and 'id' attrs
checksum = md5_cal(source)
d["id"] = checksum
d["checksum"] = checksum
def get_tgz_size(path):
"""Get the uncompressed size of a tgz file
Args:
path: a tgz file path
Returns:
size: the uncompressed size of a tgz file
"""
size = 0
f = gzip.open(path, 'rb')
try:
while True:
c = f.read(1024*1024)
if not c:
break
else:
size += len(c)
finally:
f.close()
return size
def spec_build(spec_json):
"""Build the metadata information of an umbrella spec
Args:
spec_json: the json object including the specification.
Returns:
None
"""
if spec_json.has_key("os") and spec_json["os"]:
dep_build(spec_json["os"], "os")
for sec_name in ["data", "software", "package_manager"]:
if spec_json.has_key(sec_name) and spec_json[sec_name]:
sec = spec_json[sec_name]
if sec_name == "package_manager":
if sec.has_key("config") and sec["config"]:
sec = sec["config"]
else:
logging.debug("%s does not have config attribute!", sec_name)
break
for item in sec:
dep_build(sec[item], item)
help_info = {
"build": '''Build up the metadata info of dependencies inside an umbrella spec, and write the built-up version into a new file.
A good use case of build is when you have some dependencies from the local filesystem. In this case, umbrella will calculate the metadata info
about these dependencies.
The source spec should specify the following info of each local dependency: source, action, mountpoint, format.
When the local dependency is a .tar.gz file, the following metadata info will be put into the target spec: id, checksum, size, uncompressed size.
When the local dependency is a plain file, the following metadata info will be put into the target spec: id, checksum, size.
When the local dependencies is a dir D, a corresponding D.tar.gz file will be created under the same directory with D, then the following metadata info will be put into the target spec: id, checksum, size, uncompressed size.
For more info about how to compose an umbrella spec, please check the following link:
http://ccl.cse.nd.edu/software/manuals/umbrella.html#create_spec
usage: umbrella [options] build source target
source the path of an existing umbrella spec file from your local filesystem whose metadata info is needed to be built up
target an non-existing file path on your local filesystem where the built-up version of the umbrella spec will be wrotten into
''',
"expand": '''Expand an umbrella spec file into a self-contained umbrella spec
The source umbrella spec should be specified through the --spec option; the metadata db should be specified through the --meta option.
For each dependency in the source umbrella spec, the following info will be extracted from the metadata db: source, size, format, checksum.
Finally, the expanded umbrella sepc will be wrotten into a new file.
usage: umbrella [options] expand target
target an non-existing file path on your local filesystem where the expanded version of the umbrella spec will be wrotten into
''',
"filter": '''Filter the metadata info for an umbrella spec file from a huge metadata db
The source umbrella spec should be specified through the --spec option; the metadata db should be specified through the --meta option.
The source umbrella spec should NOT be self-contained.
For each dependency specified in the source umbrella spec, its metadata info will be extracted from the huge metadata db, and written into the target path.
usage: umbrella [options] filter target
target an non-existing file path on your local filesystem where the metadata info of all the dependencies in the umbrella spec will be wrotten into
''',
"run": '''Run your application through umbrella
usage: umbrella [options] run [command]
command command to run, the command can also be set inside the umbrella spec. By default: /bin/sh
''',
"split": '''Split a self-contained umbrella spec file into an umbrella spec and a metadata db
The source umbrella spec should be specified through the --spec option; The --meta option will be ignored.
The source umbrella spec should be self-contained.
usage: umbrella [options] split newspec newdb
newspec an non-existing file path on your local filesystem where the new umbrella spec will be wrotten into
newdb an non-existing file path on your local filesystem where the metadata info corresponding to newspec will be wrotten into
''',
"upload": '''Upload the dependencies in an umbrella spec into remote archives (OSF, Amazon S3)
Umbrella will upload all the dependencies to the target archive, and add the new resource location into the source section of each dependency.
Finally, the new umbrella spec will be written into a new file.
When the source of a dependency has already include one url from the target archive, the dependency will be ignored.
Currently, the supported target includes: OSF, the Amazon S3.
Uploading to OSF requires the following umbrella options: --osf_user, --osf_pass, --osf_userid
usage of upload osf: umbrella [options] upload osf proj acl target
proj the osf project name
acl the access permission of the uploaded data. Options: public, private
target an non-existing file path on your local filesystem where the new umbrella spec will be wrotten into
usage of upload s3: umbrella [options] upload s3 bucket acl target
bucket the s3 bucket name
acl the access permission of the uploaded data. Options: public-read, private
target an non-existing file path on your local filesystem where the new umbrella spec will be wrotten into
''',
"validate": '''Validate an umbrella spec file
The source umbrella spec should be specified through the --spec option; the metadata db should be specified through the --meta option.
usage: umbrella [options] validate
'''
}
def main():
parser = OptionParser(description="Umbrella is a portable environment creator for reproducible computing on clusters, clouds, and grids.",
usage="""usage: %prog [options] run|expand|filter|split|validate|upload|build ...
Currently, umbrella supports the following behaviors:
build\t\tbuild up the metadata info of dependencies inside an umbrella spec
expand\t\texpand an umbrella spec file into a self-contained umbrella spec
filter\t\tfilter the metadata info for an umbrella spec file from a huge metadata db
run\t\trun your application through umbrella
split\t\tsplit a self-contained umbrella spec file into an umbrella spec and a metadata db
upload\t\tupload the dependencies in an umbrella spec into remote archives (OSF, Amazon S3)
validate\tvalidate an umbrella spec file
To check the help doc for a specific behavoir, use: %prog <behavior> help""",
version="%prog CCTOOLS_VERSION")
parser.add_option("--spec",
action="store",
help="The specification json file.",)
parser.add_option("--meta",
action="store",
help="The source of meta information, which can be a local file path (e.g., file:///tmp/meta.json) or url (e.g., http://...).\nIf this option is not provided, the specification will be treated a self-contained specification.",)
parser.add_option("-l", "--localdir",
action="store",
help="The path of directory used for all the cached data and all the sandboxes, the directory can be an existing dir.",)
parser.add_option("-o", "--output",
action="store",
help="The mappings of outputs in the format of <container_path>=<local_path>. Multiple mappings should be separated by comma.\ncontainer_path is a path inside the sandbox and should be exposed in the output section of an umbrella spec.\nlocal_path should be a non-existing path on your local filessytem where you want the output from container_path to be put into.",)
parser.add_option("-s", "--sandbox_mode",
action="store",
choices=['parrot', 'destructive', 'docker', 'ec2',],
help="sandbox mode, which can be parrot, destructive, docker, ec2.",)
parser.add_option("-i", "--inputs",
action="store",
help="The path of input files in the format of <container_path>=<local_path>. Multiple mappings should be separated by comma. Please refer to the --output option for the settings of local_path and container_path.",)
parser.add_option("-e", "--env",
action="store",
help="The environment variables in the format of <variable_name>=<variable_value>. Multiple settings should be separated by comma. I.e., -e 'PWD=/tmp'.")
parser.add_option("--log",
action="store",
default="./umbrella.log",
help="The path of umbrella log file. (By default: ./umbrella.log)",)
parser.add_option("--cvmfs_http_proxy",
action="store",
help="HTTP_PROXY to access cvmfs (Used by Parrot)",)
parser.add_option("--ec2",
action="store",
help="The source of ec2 information.",)
parser.add_option("--condor_log",
action="store",
help="The path of the condor umbrella log file. Required for condor execution engines.",)
parser.add_option("--ec2_log",
action="store",
help="The path of the ec2 umbrella log file. Required for ec2 execution engines.",)
parser.add_option("-g", "--ec2_group",
action="store",
help="the security group within which an Amazon EC2 instance should be run. (only for ec2)",)
parser.add_option("-k", "--ec2_key",
action="store",
help="the name of the key pair to use when launching an Amazon EC2 instance. (only for ec2)",)
parser.add_option("--ec2_sshkey",
action="store",
help="the name of the private key file to use when connecting to an Amazon EC2 instance. (only for ec2)",)
parser.add_option("--ec2_instance_type",
action="store",
help="the type of an Amazon EC2 instance. (only for ec2)",)
parser.add_option("--osf_user",
action="store",
help="the OSF username (required in two cases: uploading to osf; downloading private osf resources.)",)
parser.add_option("--osf_pass",
action="store",
help="the OSF password (required in two cases: uploading to osf; downloading private osf resources.)",)
parser.add_option("--osf_userid",
action="store",
help="the OSF user id (required in two cases: uploading to osf; downloading private osf resources.)",)
(options, args) = parser.parse_args()
logfilename = options.log
if os.path.exists(logfilename) and not os.path.isfile(logfilename):
sys.exit("The --log option <%s> is not a file!" % logfilename)
global tempfile_list
global tempdir_list
global upload_count
"""
disable_warnings function is used here to disable the SNIMissingWarning and InsecurePlatformWarning from /afs/crc.nd.edu/user/h/hmeng/.local/lib/python2.6/site-packages/requests-2.9.1-py2.6.egg/requests/packages/urllib3/util/ssl_.py.
"Requests 2.6 introduced this warning for users of Python prior to Python 2.7.9 with only stock SSL modules available."
"""
if found_requests:
requests.packages.urllib3.disable_warnings()
logging.basicConfig(filename=logfilename, level=logging.DEBUG,
format='%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
logging.debug("*******Welcome to Umbrella*******")
logging.debug("Arguments: ")
logging.debug(sys.argv)
start = datetime.datetime.now()
logging.debug("Start time: %s", start)
logging.debug("Check the validity of the command ....")
if not args:
logging.critical("You must provide the behavior and the command!")
print "You must provide the behavior and the command!\n"
parser.print_help()
sys.exit(1)
user_cmd = []
behavior = args[0]
logging.debug("Check the validity of the behavior: %s", behavior)
behavior_list = ["run", "expand", "filter", "split", "validate", "upload", "build"]
if behavior not in behavior_list:
logging.critical("%s is not supported by umbrella!", behavior)
print behavior + " is not supported by umbrella!\n"
parser.print_help()
sys.exit(1)
if len(args) > 1 and args[1] in ['help']:
print help_info[behavior]
sys.exit(0)
if behavior in ["build"]:
if len(args) != 3:
cleanup(tempfile_list, tempdir_list)
logging.critical("The syntax for umbrella build is: umbrella ... build <source.umbrella> <dest.umbrella>\n")
sys.exit("The syntax for umbrella build is: umbrella ... build <source.umbrella> <dest.umbrella>\n")
args[1] = os.path.abspath(args[1])
if (not os.path.exists(args[1])) or (not os.path.isfile(args[1])):
cleanup(tempfile_list, tempdir_list)
logging.critical("<source.umbrella> (%s) should be an existing file!\n", args[1])
sys.exit("<source.umbrella> (%s) should be an existing file!\n" % args[1])
if os.path.exists(args[2]):
cleanup(tempfile_list, tempdir_list)
logging.critical("<dest.umbrella> (%s) should be a non-existing file!\n", args[2])
sys.exit("<dest.umbrella> (%s) should be a non-existing file!\n" % args[2])
args[2] = os.path.abspath(args[2])
if not os.path.exists(os.path.dirname(args[2])):
print os.path.dirname(args[2])
try:
os.makedirs(os.path.dirname(args[2]))
except Exception as e:
cleanup(tempfile_list, tempdir_list)
logging.critical("Fails to create the directory for the <dest.umbrella> (%s): %s!", args[2], e)
sys.exit("Fails to create the directory for the <dest.umbrella> (%s)!" % (args[2], e))
with open(args[1]) as f:
spec_json = json.load(f)
spec_build(spec_json)
json2file(args[2], spec_json)
sys.exit(0)
if behavior in ["run", "upload"]:
#get the absolute path of the localdir directory, which will cache all the data, and store all the sandboxes.
#to allow the reuse the local cache, the localdir can be a dir which already exists.
localdir = options.localdir
localdir = os.path.abspath(localdir)
logging.debug("Check the localdir option: %s", localdir)
if not os.path.exists(localdir):
logging.debug("create the localdir: %s", localdir)
os.makedirs(localdir)
sandbox_dir = tempfile.mkdtemp(dir=localdir)
logging.debug("Create the sandbox_dir: %s", sandbox_dir)
#add sandbox_dir into tempdir_list
tempdir_list.append(sandbox_dir)
osf_auth = []
#osf_auth info
osf_user = options.osf_user
osf_pass = options.osf_pass
if osf_user or osf_pass:
osf_auth.append(osf_user)
osf_auth.append(osf_pass)
if behavior in ["run"]:
sandbox_mode = options.sandbox_mode
logging.debug("Check the sandbox_mode option: %s", sandbox_mode)
if sandbox_mode in ["destructive"]:
if getpass.getuser() != 'root':
cleanup(tempfile_list, tempdir_list)
logging.critical("You must be root to use the %s sandbox mode.", sandbox_mode)
print 'You must be root to use the %s sandbox mode.\n' % (sandbox_mode)
parser.print_help()
sys.exit(1)
#transfer options.env into a dictionary, env_para_dict
env_para = options.env
env_para_dict = {}
if (not env_para) or env_para == '':
logging.debug("The env option is null")
env_para_list = ''
env_para_dict = {}
else:
logging.debug("Process the env option: %s", env_para)
env_para = re.sub('\s+', '', env_para).strip()
env_para_list = env_para.split(',')
for item in env_para_list:
index = item.find('=')
name = item[:index]
value = item[(index+1):]
env_para_dict[name] = value
logging.debug("the dictionary format of the env options (env_para_dict):")
logging.debug(env_para_dict)
#get the cvmfs HTTP_PROXY
cvmfs_http_proxy = options.cvmfs_http_proxy
if behavior in ["run", "expand", "filter", "split", "validate", "upload"]:
spec_path = options.spec
if behavior == "validate" and spec_path == None:
spec_json = None
else:
spec_path_basename = os.path.basename(spec_path)
logging.debug("Start to read the specification file: %s", spec_path)
if not os.path.isfile(spec_path):
cleanup(tempfile_list, tempdir_list)
logging.critical("The specification json file (%s) does not exist! Please refer the -c option.", spec_path)
print "The specification json file does not exist! Please refer the -c option.\n"
parser.print_help()
sys.exit(1)
with open(spec_path) as f: #python 2.4 does not support this syntax: with open () as
spec_json = json.load(f)
if behavior in ["run"]:
user_cmd = args[1:]
if len(user_cmd) == 0:
if spec_json.has_key("cmd") and len(spec_json["cmd"]) > 0:
user_cmd.append(spec_json["cmd"])
else:
user_cmd.append("/bin/sh") #set the user_cmd to be default: /bin/sh
logging.debug("The user's command is: %s", user_cmd)
#if the spec file has environ seciton, merge the variables defined in it into env_para_dict
if spec_json.has_key("environ") and spec_json["environ"]:
logging.debug("The specification file has environ section, update env_para_dict ....")
spec_env = spec_json["environ"]
for key in spec_env:
env_para_dict[key] = spec_env[key]
logging.debug("env_para_dict:")
logging.debug(env_para_dict)
if behavior in ["run"]:
if 'PWD' in env_para_dict:
cwd_setting = env_para_dict['PWD']
logging.debug("PWD environment variable is set explicitly: %s", cwd_setting)
else:
cwd_setting = sandbox_dir
env_para_dict['PWD'] = cwd_setting
logging.debug("PWD is not set explicitly, use sandbox_dir (%s) as PWD", cwd_setting)
#get the absolute path of each input file
input_files = options.inputs
input_list = []
input_dict = {}
if (not input_files) or input_files == '':
input_list_origin = ''
input_list = []
input_dict = {}
logging.debug("the inputs options is null")
else:
input_files = re.sub( '\s+', '', input_files).strip() #remove all the whitespaces within the inputs option
logging.debug("The inputs option: %s", input_files)
input_list_origin = input_files.split(',')
for item in input_list_origin:
index = item.find('=')
access_path = item[:index]
actual_path = item[(index+1):]
if access_path[0] != '/':
access_path = os.path.join(cwd_setting, access_path)
actual_path = os.path.abspath(actual_path)
input_dict[access_path] = actual_path
input_list.append(actual_path) #get the absolute path of each input file and add it into input_list
logging.debug("The list version of the inputs option: ")
logging.debug(input_list)
logging.debug("The dict version of the inputs option: ")
logging.debug(input_dict)
#get the absolute path of each output file
output_dir = options.output
output_dict = {}
output_f_dict = {}
output_d_dict = {}
if output_dir and len(output_dir) > 0:
output_dir = re.sub( '\s+', '', output_dir).strip() #remove all the whitespaces within the inputs option
if output_dir == "":
logging.debug("the output option is null!")
else:
logging.debug("the output option: %s", output_dir)
outputs = output_dir.split(',')
for item in outputs:
index = item.find('=')
access_path = item[:index]
actual_path = item[(index+1):]
if access_path[0] != '/':
cleanup(tempfile_list, tempdir_list)
logging.critical("the path of an output should be absolute!")
sys.exit("the path of an output should be absolute!")
actual_path = os.path.abspath(actual_path)
output_dict[access_path] = actual_path
if len(output_dict) > 0:
if spec_json.has_key("output"):
files = []
dirs = []
if spec_json["output"].has_key("files"):
files = spec_json["output"]["files"]
if spec_json["output"].has_key("dirs"):
dirs = spec_json["output"]["dirs"]
for key in output_dict.keys():
if key in files:
output_f_dict[key] = output_dict[key]
elif key in dirs:
output_d_dict[key] = output_dict[key]
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("the output file (%s) is not specified in the spec file!", key)
sys.exit("the output file (%s) is not specified in the spec file!" % key)
else:
cleanup(tempfile_list, tempdir_list)
logging.critical("the specification does not have a output section!")
sys.exit("the specification does not have a output section!")
del output_dict
for f in output_f_dict.values():
if not os.path.exists(f):
logging.debug("create the output file: %s", f)
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
elif not os.path.isdir(d):
cleanup(tempfile_list, tempdir_list)
logging.critical("the parent path of the output file (%s) is not a directory!", f)
sys.exit("the parent path of the output file (%s) is not a directory!" % f)
else:
pass
new_file = open(f, 'a')
new_file.close()
elif len(f) != 0:
cleanup(tempfile_list, tempdir_list)
logging.critical("the output file (%s) already exists!", f)
sys.exit("the output file (%s) already exists!\n" % f)
else:
pass
for d in output_d_dict.values():
if not os.path.exists(d):
logging.debug("create the output dir: %s", d)
os.makedirs(d)
elif len(d) != 0:
cleanup(tempfile_list, tempdir_list)
logging.critical("the output dir (%s) already exists!", d)
sys.exit("the output dir(%s) already exists!" % d)
else:
pass
meta_json = None
if behavior in ["run", "expand", "filter", "validate"]:
"""
meta_path is optional. If set, it provides the metadata information for the dependencies.
If not set, the umbrella specification is treated as a self-contained specification.
meta_path can be in either file:///filepath format or a http/https url like http:/ccl.cse.nd.edu/.... Otherwise, it is treated as a local path.
"""
meta_path = options.meta
if meta_path:
if meta_path[:7] == "file://":
meta_path = meta_path[7:]
logging.debug("Check the metatdata database file: %s", meta_path)
if not os.path.exists(meta_path):
cleanup(tempfile_list, tempdir_list)
logging.critical("the metatdata database file (%s) does not exist!", meta_path)
sys.exit("the metatdata database file (%s) does not exist!" % meta_path)
elif meta_path[:7] == "http://" or meta_path[:8] == "https://":
url = meta_path
if behavior in ["run"]:
meta_path = '%s/meta.json' % (sandbox_dir)
if behavior in ["expand", "filter", "validate"]:
#create a tempfile under /tmp
(fd, meta_path) = tempfile.mkstemp()
tempfile_list.append(meta_path)
os.close(fd)
logging.debug("Creating a temporary file (%s) to hold the metadata file specified by the --meta options!", meta_path)
logging.debug("Download metadata database from %s into %s", url, meta_path)
print "Download metadata database from %s into %s" % (url, meta_path)
url_download(url, meta_path)
else:
logging.debug("Check the metatdata database file: %s", meta_path)
if not os.path.exists(meta_path):
cleanup(tempfile_list, tempdir_list)
logging.critical("the metatdata database file (%s) does not exist!", meta_path)
sys.exit("the metatdata database file (%s) does not exist!" % meta_path)
else:
if behavior in ["run"]:
#the provided specification should be self-contained.
# One solution is to change all the current implementation of Umbrella to check whether the metadata information is included in the specification.
# Another solution is to extract all the metadata information into a separate metadata database file. (This solution is currently used).
meta_path = '%s/meta.json' % (sandbox_dir)
abstract_metadata(spec_json, meta_path)
elif behavior in ["expand", "filter"]:
cleanup(tempfile_list, tempdir_list)
logging.critical("The --meta option should be provided for the umbrella %s behavior!\n", behavior)
sys.exit("The --meta option should be provided for the umbrella %s behavior!\n" % behavior)
if meta_path:
with open(meta_path) as f: #python 2.4 does not support this syntax: with open () as
meta_json = json.load(f)
if behavior in ["upload"]:
#the provided specification should be self-contained.
# One solution is to change all the current implementation of Umbrella to check whether the metadata information is included in the specification.
# Another solution is to extract all the metadata information into a separate metadata database file. (This solution is currently used).
meta_path = '%s/meta.json' % (sandbox_dir)
abstract_metadata(spec_json, meta_path)
with open(meta_path) as f: #python 2.4 does not support this syntax: with open () as
meta_json = json.load(f)
if behavior in ["run", "validate", "split", "filter", "expand", "upload"]:
#for validate, if only --spec is provided, then check whether this spec is self-contained.
#for validate, if only --meta is provided, then check whether each item in the metadata db is well archived (for now, well-archived means the source attr is not null).
#for validate, if both --spec and --meta are provided, then check whether the dependencies of the spec file is well archived.
if spec_json == None:
if meta_json == None:
pass
else:
validate_meta(meta_json)
else:
if meta_json == None:
validate_spec(spec_json)
else:
validate_spec(spec_json, meta_json)
if behavior in ["run"]:
# user_name = 'root' #username who can access the VM instances from Amazon EC2
# ssh_key = 'hmeng_key_1018.pem' #the pem key file used to access the VM instances from Amazon EC2
if sandbox_mode == "ec2":
ec2log_path = options.ec2_log
ec2log_path = os.path.abspath(ec2log_path)
if os.path.exists(ec2log_path):
cleanup(tempfile_list, tempdir_list)
sys.exit("The ec2_log option <%s> already exists!" % ec2log_path)
ssh_key = os.path.abspath(options.ec2_sshkey)
if not os.path.exists(ssh_key):
cleanup(tempfile_list, tempdir_list)
logging.critical("The ssh key file (%s) does not exists!", ssh_key)
sys.exit("The ssh key file (%s) does not exists!\n" % ssh_key)
ec2_security_group = options.ec2_group
ec2_key_pair = options.ec2_key
ec2_instance_type = options.ec2_instance_type
ec2_process(spec_path, spec_json, options.meta, meta_path, ssh_key, ec2_key_pair, ec2_security_group, ec2_instance_type, sandbox_dir, output_dir, output_f_dict, output_d_dict, sandbox_mode, input_list, input_list_origin, env_para, env_para_dict, user_cmd, cwd_setting, ec2log_path, cvmfs_http_proxy)
elif sandbox_mode == "condor":
condorlog_path = options.condor_log
condorlog_path = os.path.abspath(condorlog_path)
if os.path.exists(condorlog_path):
cleanup(tempfile_list, tempdir_list)
sys.exit("The condor_log option <%s> already exists!" % condorlog_path)
condor_process(spec_path, spec_json, spec_path_basename, meta_path, sandbox_dir, output_dir, input_list_origin, user_cmd, cwd_setting, condorlog_path, cvmfs_http_proxy)
elif sandbox_mode == "local":
#first check whether Docker exists, if yes, use docker execution engine; if not, use parrot execution engine.
if dependency_check('docker') == 0:
logging.debug('docker exists, use docker execution engine')
specification_process(spec_json, sandbox_dir, behavior, meta_json, 'docker', output_f_dict, output_d_dict, input_dict, env_para_dict, user_cmd, cwd_setting, cvmfs_http_proxy, osf_auth)
else:
logging.debug('docker does not exist, use parrot execution engine')
specification_process(spec_json, sandbox_dir, behavior, meta_json, 'parrot', output_f_dict, output_d_dict, input_dict, env_para_dict, user_cmd, cwd_setting, cvmfs_http_proxy, osf_auth)
else:
if sandbox_mode == 'docker' and dependency_check('docker') != 0:
cleanup(tempfile_list, tempdir_list)
logging.critical('Docker is not installed on the host machine, please try other execution engines!')
sys.exit('Docker is not installed on the host machine, please try other execution engines!')
specification_process(spec_json, sandbox_dir, behavior, meta_json, sandbox_mode, output_f_dict, output_d_dict, input_dict, env_para_dict, user_cmd, cwd_setting, cvmfs_http_proxy, osf_auth)
if behavior in ["expand", "filter"]:
if len(args) != 2:
cleanup(tempfile_list, tempdir_list)
logging.critical("The syntax for umbrella %s is: umbrella ... %s <filepath>.\n", behavior, behavior)
sys.exit("The syntax for umbrella %s is: umbrella ... %s <filepath>.\n" % (behavior, behavior))
target_specpath = os.path.abspath(args[1])
path_exists(target_specpath)
dir_create(target_specpath)
if behavior == "expand":
new_json = separatize_spec(spec_json, meta_json, "spec")
else:
new_json = separatize_spec(spec_json, meta_json, "meta")
#write new_json into the file specified by the user.
json2file(target_specpath, new_json)
if behavior in ["split"]:
if len(args) != 3:
cleanup(tempfile_list, tempdir_list)
logging.critical("The syntax for umbrella split is: umbrella ... split <spec_filepath> <meta_filepath>.\n")
sys.exit("The syntax for umbrella split is: umbrella ... split <spec_filepath> <meata_filepath>.\n")
new_spec_path = os.path.abspath(args[1])
db_path = os.path.abspath(args[2])
path_exists(new_spec_path)
dir_create(new_spec_path)
path_exists(db_path)
dir_create(db_path)
abstract_metadata(spec_json, db_path)
new_json = prune_spec(spec_json)
json2file(new_spec_path, new_json)
if behavior in ["upload"]:
target = ["osf", "s3"]
if len(args) < 2 or args[1] not in target:
cleanup(tempfile_list, tempdir_list)
logging.critical("The syntax for umbrella upload is: umbrella ... upload <target> ... (target can be: %s)\n", " or ".join(target))
sys.exit("The syntax for umbrella upload is: umbrella ... upload <target> ... (target can be: %s)\n" % " or ".join(target))
if args[1] == "osf":
if not found_requests:
cleanup(tempfile_list, tempdir_list)
logging.critical("\nUploading umbrella spec dependencies to OSF requires a python package - requests. Please check the installation page of requests:\n\n\thttp://docs.python-requests.org/en/latest/user/install/\n")
sys.exit("\nUploading umbrella spec dependencies to OSF requires a python package - requests. Please check the installation page of requests:\n\n\thttp://docs.python-requests.org/en/latest/user/install/\n")
if len(args) != 5:
cleanup(tempfile_list, tempdir_list)
logging.critical("The syntax for umbrella upload osf is: umbrella ... upload osf <osf_project_name> <public_or_private> <target_specpath>\n")
sys.exit("The syntax for umbrella upload osf is: umbrella ... upload osf <osf_project_name> <public_or_private> <target_specpath>\n")
acl = ["private", "public"]
if args[3] not in acl:
cleanup(tempfile_list, tempdir_list)
sys.exit("The access control for s3 bucket and object can only be: %s" % " or ".join(acl))
target_specpath = os.path.abspath(args[4])
path_exists(target_specpath)
dir_create(target_specpath)
osf_info = []
osf_info.append("osf")
osf_info += [options.osf_user, options.osf_pass]
osf_proj_id = osf_create(options.osf_user, options.osf_pass, options.osf_userid, args[2], args[3] == "public")
osf_info.append(osf_proj_id)
spec_upload(spec_json, meta_json, osf_info, sandbox_dir, osf_auth)
if upload_count > 0:
json2file(target_specpath, spec_json)
osf_upload(options.osf_user, options.osf_pass, osf_proj_id, target_specpath)
else:
logging.debug("All the dependencies has been already inside OSF!")
print "All the dependencies has been already inside OSF!"
elif args[1] == "s3":
if not found_boto3 or not found_botocore:
cleanup(tempfile_list, tempdir_list)
logging.critical("\nUploading umbrella spec dependencies to s3 requires a python package - boto3. Please check the installation page of boto3:\n\n\thttps://boto3.readthedocs.org/en/latest/guide/quickstart.html#installation\n")
sys.exit("\nUploading umbrella spec dependencies to s3 requires a python package - boto3. Please check the installation page of boto3:\n\n\thttps://boto3.readthedocs.org/en/latest/guide/quickstart.html#installation\n")
if len(args) != 5:
cleanup(tempfile_list, tempdir_list)
logging.critical("The syntax for umbrella upload s3 is: umbrella ... upload s3 <bucket_name> <access_control> <target_specpath>\n")
sys.exit("The syntax for umbrella upload s3 is: umbrella ... upload s3 <bucket_name> <access_control> <target_specpath>\n")
acl = ["private", "public-read"]
if args[3] not in acl:
cleanup(tempfile_list, tempdir_list)
sys.exit("The access control for s3 bucket and object can only be: %s" % " or ".join(acl))
target_specpath = os.path.abspath(args[4])
path_exists(target_specpath)
dir_create(target_specpath)
s3_info = []
s3_info.append("s3")
s3_info.append(args[3])
bucket = s3_create(args[2], args[3])
spec_upload(spec_json, meta_json, s3_info, sandbox_dir, s3_bucket=bucket)
if upload_count > 0:
json2file(target_specpath, spec_json)
s3_upload(bucket, target_specpath, args[3])
else:
logging.debug("All the dependencies has been already inside S3!")
print "All the dependencies has been already inside S3!"
cleanup(tempfile_list, tempdir_list)
end = datetime.datetime.now()
diff = end - start
logging.debug("End time: %s", end)
logging.debug("execution time: %d seconds", diff.seconds)
if __name__ == "__main__":
main()
#set sts=4 sw=4 ts=4 expandtab ft=python
|
gpl-2.0
| -3,054,751,530,107,959,000
| 42.014133
| 648
| 0.702808
| false
| 3.167061
| false
| false
| false
|
leshchevds/ganeti
|
lib/jqueue/__init__.py
|
1
|
52112
|
#
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Module implementing the job queue handling.
"""
import logging
import errno
import time
import weakref
import threading
import itertools
import operator
import os
try:
# pylint: disable=E0611
from pyinotify import pyinotify
except ImportError:
import pyinotify
from ganeti import asyncnotifier
from ganeti import constants
from ganeti import serializer
from ganeti import locking
from ganeti import luxi
from ganeti import opcodes
from ganeti import opcodes_base
from ganeti import errors
from ganeti import mcpu
from ganeti import utils
from ganeti import jstore
import ganeti.rpc.node as rpc
from ganeti import runtime
from ganeti import netutils
from ganeti import compat
from ganeti import ht
from ganeti import query
from ganeti import qlang
from ganeti import pathutils
from ganeti import vcluster
from ganeti.cmdlib import cluster
#: Retrieves "id" attribute
_GetIdAttr = operator.attrgetter("id")
class CancelJob(Exception):
"""Special exception to cancel a job.
"""
def TimeStampNow():
"""Returns the current timestamp.
@rtype: tuple
@return: the current time in the (seconds, microseconds) format
"""
return utils.SplitTime(time.time())
def _CallJqUpdate(runner, names, file_name, content):
"""Updates job queue file after virtualizing filename.
"""
virt_file_name = vcluster.MakeVirtualPath(file_name)
return runner.call_jobqueue_update(names, virt_file_name, content)
class _QueuedOpCode(object):
"""Encapsulates an opcode object.
@ivar log: holds the execution log and consists of tuples
of the form C{(log_serial, timestamp, level, message)}
@ivar input: the OpCode we encapsulate
@ivar status: the current status
@ivar result: the result of the LU execution
@ivar start_timestamp: timestamp for the start of the execution
@ivar exec_timestamp: timestamp for the actual LU Exec() function invocation
@ivar stop_timestamp: timestamp for the end of the execution
"""
__slots__ = ["input", "status", "result", "log", "priority",
"start_timestamp", "exec_timestamp", "end_timestamp",
"__weakref__"]
def __init__(self, op):
"""Initializes instances of this class.
@type op: L{opcodes.OpCode}
@param op: the opcode we encapsulate
"""
self.input = op
self.status = constants.OP_STATUS_QUEUED
self.result = None
self.log = []
self.start_timestamp = None
self.exec_timestamp = None
self.end_timestamp = None
# Get initial priority (it might change during the lifetime of this opcode)
self.priority = getattr(op, "priority", constants.OP_PRIO_DEFAULT)
@classmethod
def Restore(cls, state):
"""Restore the _QueuedOpCode from the serialized form.
@type state: dict
@param state: the serialized state
@rtype: _QueuedOpCode
@return: a new _QueuedOpCode instance
"""
obj = _QueuedOpCode.__new__(cls)
obj.input = opcodes.OpCode.LoadOpCode(state["input"])
obj.status = state["status"]
obj.result = state["result"]
obj.log = state["log"]
obj.start_timestamp = state.get("start_timestamp", None)
obj.exec_timestamp = state.get("exec_timestamp", None)
obj.end_timestamp = state.get("end_timestamp", None)
obj.priority = state.get("priority", constants.OP_PRIO_DEFAULT)
return obj
def Serialize(self):
"""Serializes this _QueuedOpCode.
@rtype: dict
@return: the dictionary holding the serialized state
"""
return {
"input": self.input.__getstate__(),
"status": self.status,
"result": self.result,
"log": self.log,
"start_timestamp": self.start_timestamp,
"exec_timestamp": self.exec_timestamp,
"end_timestamp": self.end_timestamp,
"priority": self.priority,
}
class _QueuedJob(object):
"""In-memory job representation.
This is what we use to track the user-submitted jobs. Locking must
be taken care of by users of this class.
@type queue: L{JobQueue}
@ivar queue: the parent queue
@ivar id: the job ID
@type ops: list
@ivar ops: the list of _QueuedOpCode that constitute the job
@type log_serial: int
@ivar log_serial: holds the index for the next log entry
@ivar received_timestamp: the timestamp for when the job was received
@ivar start_timestmap: the timestamp for start of execution
@ivar end_timestamp: the timestamp for end of execution
@ivar writable: Whether the job is allowed to be modified
"""
# pylint: disable=W0212
__slots__ = ["queue", "id", "ops", "log_serial", "ops_iter", "cur_opctx",
"received_timestamp", "start_timestamp", "end_timestamp",
"writable", "archived",
"livelock", "process_id",
"__weakref__"]
def AddReasons(self, pickup=False):
"""Extend the reason trail
Add the reason for all the opcodes of this job to be executed.
"""
count = 0
for queued_op in self.ops:
op = queued_op.input
if pickup:
reason_src_prefix = constants.OPCODE_REASON_SRC_PICKUP
else:
reason_src_prefix = constants.OPCODE_REASON_SRC_OPCODE
reason_src = opcodes_base.NameToReasonSrc(op.__class__.__name__,
reason_src_prefix)
reason_text = "job=%d;index=%d" % (self.id, count)
reason = getattr(op, "reason", [])
reason.append((reason_src, reason_text, utils.EpochNano()))
op.reason = reason
count = count + 1
def __init__(self, queue, job_id, ops, writable):
"""Constructor for the _QueuedJob.
@type queue: L{JobQueue}
@param queue: our parent queue
@type job_id: job_id
@param job_id: our job id
@type ops: list
@param ops: the list of opcodes we hold, which will be encapsulated
in _QueuedOpCodes
@type writable: bool
@param writable: Whether job can be modified
"""
if not ops:
raise errors.GenericError("A job needs at least one opcode")
self.queue = queue
self.id = int(job_id)
self.ops = [_QueuedOpCode(op) for op in ops]
self.AddReasons()
self.log_serial = 0
self.received_timestamp = TimeStampNow()
self.start_timestamp = None
self.end_timestamp = None
self.archived = False
self.livelock = None
self.process_id = None
self.writable = None
self._InitInMemory(self, writable)
assert not self.archived, "New jobs can not be marked as archived"
@staticmethod
def _InitInMemory(obj, writable):
"""Initializes in-memory variables.
"""
obj.writable = writable
obj.ops_iter = None
obj.cur_opctx = None
def __repr__(self):
status = ["%s.%s" % (self.__class__.__module__, self.__class__.__name__),
"id=%s" % self.id,
"ops=%s" % ",".join([op.input.Summary() for op in self.ops])]
return "<%s at %#x>" % (" ".join(status), id(self))
@classmethod
def Restore(cls, queue, state, writable, archived):
"""Restore a _QueuedJob from serialized state:
@type queue: L{JobQueue}
@param queue: to which queue the restored job belongs
@type state: dict
@param state: the serialized state
@type writable: bool
@param writable: Whether job can be modified
@type archived: bool
@param archived: Whether job was already archived
@rtype: _JobQueue
@return: the restored _JobQueue instance
"""
obj = _QueuedJob.__new__(cls)
obj.queue = queue
obj.id = int(state["id"])
obj.received_timestamp = state.get("received_timestamp", None)
obj.start_timestamp = state.get("start_timestamp", None)
obj.end_timestamp = state.get("end_timestamp", None)
obj.archived = archived
obj.livelock = state.get("livelock", None)
obj.process_id = state.get("process_id", None)
if obj.process_id is not None:
obj.process_id = int(obj.process_id)
obj.ops = []
obj.log_serial = 0
for op_state in state["ops"]:
op = _QueuedOpCode.Restore(op_state)
for log_entry in op.log:
obj.log_serial = max(obj.log_serial, log_entry[0])
obj.ops.append(op)
cls._InitInMemory(obj, writable)
return obj
def Serialize(self):
"""Serialize the _JobQueue instance.
@rtype: dict
@return: the serialized state
"""
return {
"id": self.id,
"ops": [op.Serialize() for op in self.ops],
"start_timestamp": self.start_timestamp,
"end_timestamp": self.end_timestamp,
"received_timestamp": self.received_timestamp,
"livelock": self.livelock,
"process_id": self.process_id,
}
def CalcStatus(self):
"""Compute the status of this job.
This function iterates over all the _QueuedOpCodes in the job and
based on their status, computes the job status.
The algorithm is:
- if we find a cancelled, or finished with error, the job
status will be the same
- otherwise, the last opcode with the status one of:
- waitlock
- canceling
- running
will determine the job status
- otherwise, it means either all opcodes are queued, or success,
and the job status will be the same
@return: the job status
"""
status = constants.JOB_STATUS_QUEUED
all_success = True
for op in self.ops:
if op.status == constants.OP_STATUS_SUCCESS:
continue
all_success = False
if op.status == constants.OP_STATUS_QUEUED:
pass
elif op.status == constants.OP_STATUS_WAITING:
status = constants.JOB_STATUS_WAITING
elif op.status == constants.OP_STATUS_RUNNING:
status = constants.JOB_STATUS_RUNNING
elif op.status == constants.OP_STATUS_CANCELING:
status = constants.JOB_STATUS_CANCELING
break
elif op.status == constants.OP_STATUS_ERROR:
status = constants.JOB_STATUS_ERROR
# The whole job fails if one opcode failed
break
elif op.status == constants.OP_STATUS_CANCELED:
status = constants.OP_STATUS_CANCELED
break
if all_success:
status = constants.JOB_STATUS_SUCCESS
return status
def CalcPriority(self):
"""Gets the current priority for this job.
Only unfinished opcodes are considered. When all are done, the default
priority is used.
@rtype: int
"""
priorities = [op.priority for op in self.ops
if op.status not in constants.OPS_FINALIZED]
if not priorities:
# All opcodes are done, assume default priority
return constants.OP_PRIO_DEFAULT
return min(priorities)
def GetLogEntries(self, newer_than):
"""Selectively returns the log entries.
@type newer_than: None or int
@param newer_than: if this is None, return all log entries,
otherwise return only the log entries with serial higher
than this value
@rtype: list
@return: the list of the log entries selected
"""
if newer_than is None:
serial = -1
else:
serial = newer_than
entries = []
for op in self.ops:
entries.extend(filter(lambda entry: entry[0] > serial, op.log))
return entries
def MarkUnfinishedOps(self, status, result):
"""Mark unfinished opcodes with a given status and result.
This is an utility function for marking all running or waiting to
be run opcodes with a given status. Opcodes which are already
finalised are not changed.
@param status: a given opcode status
@param result: the opcode result
"""
not_marked = True
for op in self.ops:
if op.status in constants.OPS_FINALIZED:
assert not_marked, "Finalized opcodes found after non-finalized ones"
continue
op.status = status
op.result = result
not_marked = False
def Finalize(self):
"""Marks the job as finalized.
"""
self.end_timestamp = TimeStampNow()
def Cancel(self):
"""Marks job as canceled/-ing if possible.
@rtype: tuple; (bool, string)
@return: Boolean describing whether job was successfully canceled or marked
as canceling and a text message
"""
status = self.CalcStatus()
if status == constants.JOB_STATUS_QUEUED:
self.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
"Job canceled by request")
self.Finalize()
return (True, "Job %s canceled" % self.id)
elif status == constants.JOB_STATUS_WAITING:
# The worker will notice the new status and cancel the job
self.MarkUnfinishedOps(constants.OP_STATUS_CANCELING, None)
return (True, "Job %s will be canceled" % self.id)
else:
logging.debug("Job %s is no longer waiting in the queue", self.id)
return (False, "Job %s is no longer waiting in the queue" % self.id)
def ChangePriority(self, priority):
"""Changes the job priority.
@type priority: int
@param priority: New priority
@rtype: tuple; (bool, string)
@return: Boolean describing whether job's priority was successfully changed
and a text message
"""
status = self.CalcStatus()
if status in constants.JOBS_FINALIZED:
return (False, "Job %s is finished" % self.id)
elif status == constants.JOB_STATUS_CANCELING:
return (False, "Job %s is cancelling" % self.id)
else:
assert status in (constants.JOB_STATUS_QUEUED,
constants.JOB_STATUS_WAITING,
constants.JOB_STATUS_RUNNING)
changed = False
for op in self.ops:
if (op.status == constants.OP_STATUS_RUNNING or
op.status in constants.OPS_FINALIZED):
assert not changed, \
("Found opcode for which priority should not be changed after"
" priority has been changed for previous opcodes")
continue
assert op.status in (constants.OP_STATUS_QUEUED,
constants.OP_STATUS_WAITING)
changed = True
# Set new priority (doesn't modify opcode input)
op.priority = priority
if changed:
return (True, ("Priorities of pending opcodes for job %s have been"
" changed to %s" % (self.id, priority)))
else:
return (False, "Job %s had no pending opcodes" % self.id)
def SetPid(self, pid):
"""Sets the job's process ID
@type pid: int
@param pid: the process ID
"""
status = self.CalcStatus()
if status in (constants.JOB_STATUS_QUEUED,
constants.JOB_STATUS_WAITING):
if self.process_id is not None:
logging.warning("Replacing the process id %s of job %s with %s",
self.process_id, self.id, pid)
self.process_id = pid
else:
logging.warning("Can set pid only for queued/waiting jobs")
class _OpExecCallbacks(mcpu.OpExecCbBase):
def __init__(self, queue, job, op):
"""Initializes this class.
@type queue: L{JobQueue}
@param queue: Job queue
@type job: L{_QueuedJob}
@param job: Job object
@type op: L{_QueuedOpCode}
@param op: OpCode
"""
super(_OpExecCallbacks, self).__init__()
assert queue, "Queue is missing"
assert job, "Job is missing"
assert op, "Opcode is missing"
self._queue = queue
self._job = job
self._op = op
def _CheckCancel(self):
"""Raises an exception to cancel the job if asked to.
"""
# Cancel here if we were asked to
if self._op.status == constants.OP_STATUS_CANCELING:
logging.debug("Canceling opcode")
raise CancelJob()
def NotifyStart(self):
"""Mark the opcode as running, not lock-waiting.
This is called from the mcpu code as a notifier function, when the LU is
finally about to start the Exec() method. Of course, to have end-user
visible results, the opcode must be initially (before calling into
Processor.ExecOpCode) set to OP_STATUS_WAITING.
"""
assert self._op in self._job.ops
assert self._op.status in (constants.OP_STATUS_WAITING,
constants.OP_STATUS_CANCELING)
# Cancel here if we were asked to
self._CheckCancel()
logging.debug("Opcode is now running")
self._op.status = constants.OP_STATUS_RUNNING
self._op.exec_timestamp = TimeStampNow()
# And finally replicate the job status
self._queue.UpdateJobUnlocked(self._job)
def NotifyRetry(self):
"""Mark opcode again as lock-waiting.
This is called from the mcpu code just after calling PrepareRetry.
The opcode will now again acquire locks (more, hopefully).
"""
self._op.status = constants.OP_STATUS_WAITING
logging.debug("Opcode will be retried. Back to waiting.")
def _AppendFeedback(self, timestamp, log_type, log_msgs):
"""Internal feedback append function, with locks
@type timestamp: tuple (int, int)
@param timestamp: timestamp of the log message
@type log_type: string
@param log_type: log type (one of Types.ELogType)
@type log_msgs: any
@param log_msgs: log data to append
"""
# This should be removed once Feedback() has a clean interface.
# Feedback can be called with anything, we interpret ELogMessageList as
# messages that have to be individually added to the log list, but pushed
# in a single update. Other msgtypes are only transparently passed forward.
if log_type == constants.ELOG_MESSAGE_LIST:
log_type = constants.ELOG_MESSAGE
else:
log_msgs = [log_msgs]
for msg in log_msgs:
self._job.log_serial += 1
self._op.log.append((self._job.log_serial, timestamp, log_type, msg))
self._queue.UpdateJobUnlocked(self._job, replicate=False)
# TODO: Cleanup calling conventions, make them explicit
def Feedback(self, *args):
"""Append a log entry.
Calling conventions:
arg[0]: (optional) string, message type (Types.ELogType)
arg[1]: data to be interpreted as a message
"""
assert len(args) < 3
# TODO: Use separate keyword arguments for a single string vs. a list.
if len(args) == 1:
log_type = constants.ELOG_MESSAGE
log_msg = args[0]
else:
(log_type, log_msg) = args
# The time is split to make serialization easier and not lose
# precision.
timestamp = utils.SplitTime(time.time())
self._AppendFeedback(timestamp, log_type, log_msg)
def CurrentPriority(self):
"""Returns current priority for opcode.
"""
assert self._op.status in (constants.OP_STATUS_WAITING,
constants.OP_STATUS_CANCELING)
# Cancel here if we were asked to
self._CheckCancel()
return self._op.priority
def SubmitManyJobs(self, jobs):
"""Submits jobs for processing.
See L{JobQueue.SubmitManyJobs}.
"""
# Locking is done in job queue
return self._queue.SubmitManyJobs(jobs)
def _EncodeOpError(err):
"""Encodes an error which occurred while processing an opcode.
"""
if isinstance(err, errors.GenericError):
to_encode = err
else:
to_encode = errors.OpExecError(str(err))
return errors.EncodeException(to_encode)
class _TimeoutStrategyWrapper:
def __init__(self, fn):
"""Initializes this class.
"""
self._fn = fn
self._next = None
def _Advance(self):
"""Gets the next timeout if necessary.
"""
if self._next is None:
self._next = self._fn()
def Peek(self):
"""Returns the next timeout.
"""
self._Advance()
return self._next
def Next(self):
"""Returns the current timeout and advances the internal state.
"""
self._Advance()
result = self._next
self._next = None
return result
class _OpExecContext:
def __init__(self, op, index, log_prefix, timeout_strategy_factory):
"""Initializes this class.
"""
self.op = op
self.index = index
self.log_prefix = log_prefix
self.summary = op.input.Summary()
# Create local copy to modify
if getattr(op.input, opcodes_base.DEPEND_ATTR, None):
self.jobdeps = op.input.depends[:]
else:
self.jobdeps = None
self._timeout_strategy_factory = timeout_strategy_factory
self._ResetTimeoutStrategy()
def _ResetTimeoutStrategy(self):
"""Creates a new timeout strategy.
"""
self._timeout_strategy = \
_TimeoutStrategyWrapper(self._timeout_strategy_factory().NextAttempt)
def CheckPriorityIncrease(self):
"""Checks whether priority can and should be increased.
Called when locks couldn't be acquired.
"""
op = self.op
# Exhausted all retries and next round should not use blocking acquire
# for locks?
if (self._timeout_strategy.Peek() is None and
op.priority > constants.OP_PRIO_HIGHEST):
logging.debug("Increasing priority")
op.priority -= 1
self._ResetTimeoutStrategy()
return True
return False
def GetNextLockTimeout(self):
"""Returns the next lock acquire timeout.
"""
return self._timeout_strategy.Next()
class _JobProcessor(object):
(DEFER,
WAITDEP,
FINISHED) = range(1, 4)
def __init__(self, queue, opexec_fn, job,
_timeout_strategy_factory=mcpu.LockAttemptTimeoutStrategy):
"""Initializes this class.
"""
self.queue = queue
self.opexec_fn = opexec_fn
self.job = job
self._timeout_strategy_factory = _timeout_strategy_factory
@staticmethod
def _FindNextOpcode(job, timeout_strategy_factory):
"""Locates the next opcode to run.
@type job: L{_QueuedJob}
@param job: Job object
@param timeout_strategy_factory: Callable to create new timeout strategy
"""
# Create some sort of a cache to speed up locating next opcode for future
# lookups
# TODO: Consider splitting _QueuedJob.ops into two separate lists, one for
# pending and one for processed ops.
if job.ops_iter is None:
job.ops_iter = enumerate(job.ops)
# Find next opcode to run
while True:
try:
(idx, op) = job.ops_iter.next()
except StopIteration:
raise errors.ProgrammerError("Called for a finished job")
if op.status == constants.OP_STATUS_RUNNING:
# Found an opcode already marked as running
raise errors.ProgrammerError("Called for job marked as running")
opctx = _OpExecContext(op, idx, "Op %s/%s" % (idx + 1, len(job.ops)),
timeout_strategy_factory)
if op.status not in constants.OPS_FINALIZED:
return opctx
# This is a job that was partially completed before master daemon
# shutdown, so it can be expected that some opcodes are already
# completed successfully (if any did error out, then the whole job
# should have been aborted and not resubmitted for processing).
logging.info("%s: opcode %s already processed, skipping",
opctx.log_prefix, opctx.summary)
@staticmethod
def _MarkWaitlock(job, op):
"""Marks an opcode as waiting for locks.
The job's start timestamp is also set if necessary.
@type job: L{_QueuedJob}
@param job: Job object
@type op: L{_QueuedOpCode}
@param op: Opcode object
"""
assert op in job.ops
assert op.status in (constants.OP_STATUS_QUEUED,
constants.OP_STATUS_WAITING)
update = False
op.result = None
if op.status == constants.OP_STATUS_QUEUED:
op.status = constants.OP_STATUS_WAITING
update = True
if op.start_timestamp is None:
op.start_timestamp = TimeStampNow()
update = True
if job.start_timestamp is None:
job.start_timestamp = op.start_timestamp
update = True
assert op.status == constants.OP_STATUS_WAITING
return update
@staticmethod
def _CheckDependencies(queue, job, opctx):
"""Checks if an opcode has dependencies and if so, processes them.
@type queue: L{JobQueue}
@param queue: Queue object
@type job: L{_QueuedJob}
@param job: Job object
@type opctx: L{_OpExecContext}
@param opctx: Opcode execution context
@rtype: bool
@return: Whether opcode will be re-scheduled by dependency tracker
"""
op = opctx.op
result = False
while opctx.jobdeps:
(dep_job_id, dep_status) = opctx.jobdeps[0]
(depresult, depmsg) = queue.depmgr.CheckAndRegister(job, dep_job_id,
dep_status)
assert ht.TNonEmptyString(depmsg), "No dependency message"
logging.info("%s: %s", opctx.log_prefix, depmsg)
if depresult == _JobDependencyManager.CONTINUE:
# Remove dependency and continue
opctx.jobdeps.pop(0)
elif depresult == _JobDependencyManager.WAIT:
# Need to wait for notification, dependency tracker will re-add job
# to workerpool
result = True
break
elif depresult == _JobDependencyManager.CANCEL:
# Job was cancelled, cancel this job as well
job.Cancel()
assert op.status == constants.OP_STATUS_CANCELING
break
elif depresult in (_JobDependencyManager.WRONGSTATUS,
_JobDependencyManager.ERROR):
# Job failed or there was an error, this job must fail
op.status = constants.OP_STATUS_ERROR
op.result = _EncodeOpError(errors.OpExecError(depmsg))
break
else:
raise errors.ProgrammerError("Unknown dependency result '%s'" %
depresult)
return result
def _ExecOpCodeUnlocked(self, opctx):
"""Processes one opcode and returns the result.
"""
op = opctx.op
assert op.status in (constants.OP_STATUS_WAITING,
constants.OP_STATUS_CANCELING)
# The very last check if the job was cancelled before trying to execute
if op.status == constants.OP_STATUS_CANCELING:
return (constants.OP_STATUS_CANCELING, None)
timeout = opctx.GetNextLockTimeout()
try:
# Make sure not to hold queue lock while calling ExecOpCode
result = self.opexec_fn(op.input,
_OpExecCallbacks(self.queue, self.job, op),
timeout=timeout)
except mcpu.LockAcquireTimeout:
assert timeout is not None, "Received timeout for blocking acquire"
logging.debug("Couldn't acquire locks in %0.6fs", timeout)
assert op.status in (constants.OP_STATUS_WAITING,
constants.OP_STATUS_CANCELING)
# Was job cancelled while we were waiting for the lock?
if op.status == constants.OP_STATUS_CANCELING:
return (constants.OP_STATUS_CANCELING, None)
# Stay in waitlock while trying to re-acquire lock
return (constants.OP_STATUS_WAITING, None)
except CancelJob:
logging.exception("%s: Canceling job", opctx.log_prefix)
assert op.status == constants.OP_STATUS_CANCELING
return (constants.OP_STATUS_CANCELING, None)
except Exception, err: # pylint: disable=W0703
logging.exception("%s: Caught exception in %s",
opctx.log_prefix, opctx.summary)
return (constants.OP_STATUS_ERROR, _EncodeOpError(err))
else:
logging.debug("%s: %s successful",
opctx.log_prefix, opctx.summary)
return (constants.OP_STATUS_SUCCESS, result)
def __call__(self, _nextop_fn=None):
"""Continues execution of a job.
@param _nextop_fn: Callback function for tests
@return: C{FINISHED} if job is fully processed, C{DEFER} if the job should
be deferred and C{WAITDEP} if the dependency manager
(L{_JobDependencyManager}) will re-schedule the job when appropriate
"""
queue = self.queue
job = self.job
logging.debug("Processing job %s", job.id)
try:
opcount = len(job.ops)
assert job.writable, "Expected writable job"
# Don't do anything for finalized jobs
if job.CalcStatus() in constants.JOBS_FINALIZED:
return self.FINISHED
# Is a previous opcode still pending?
if job.cur_opctx:
opctx = job.cur_opctx
job.cur_opctx = None
else:
if __debug__ and _nextop_fn:
_nextop_fn()
opctx = self._FindNextOpcode(job, self._timeout_strategy_factory)
op = opctx.op
# Consistency check
assert compat.all(i.status in (constants.OP_STATUS_QUEUED,
constants.OP_STATUS_CANCELING)
for i in job.ops[opctx.index + 1:])
assert op.status in (constants.OP_STATUS_QUEUED,
constants.OP_STATUS_WAITING,
constants.OP_STATUS_CANCELING)
assert (op.priority <= constants.OP_PRIO_LOWEST and
op.priority >= constants.OP_PRIO_HIGHEST)
waitjob = None
if op.status != constants.OP_STATUS_CANCELING:
assert op.status in (constants.OP_STATUS_QUEUED,
constants.OP_STATUS_WAITING)
# Prepare to start opcode
if self._MarkWaitlock(job, op):
# Write to disk
queue.UpdateJobUnlocked(job)
assert op.status == constants.OP_STATUS_WAITING
assert job.CalcStatus() == constants.JOB_STATUS_WAITING
assert job.start_timestamp and op.start_timestamp
assert waitjob is None
# Check if waiting for a job is necessary
waitjob = self._CheckDependencies(queue, job, opctx)
assert op.status in (constants.OP_STATUS_WAITING,
constants.OP_STATUS_CANCELING,
constants.OP_STATUS_ERROR)
if not (waitjob or op.status in (constants.OP_STATUS_CANCELING,
constants.OP_STATUS_ERROR)):
logging.info("%s: opcode %s waiting for locks",
opctx.log_prefix, opctx.summary)
assert not opctx.jobdeps, "Not all dependencies were removed"
(op_status, op_result) = self._ExecOpCodeUnlocked(opctx)
op.status = op_status
op.result = op_result
assert not waitjob
if op.status in (constants.OP_STATUS_WAITING,
constants.OP_STATUS_QUEUED):
# waiting: Couldn't get locks in time
# queued: Queue is shutting down
assert not op.end_timestamp
else:
# Finalize opcode
op.end_timestamp = TimeStampNow()
if op.status == constants.OP_STATUS_CANCELING:
assert not compat.any(i.status != constants.OP_STATUS_CANCELING
for i in job.ops[opctx.index:])
else:
assert op.status in constants.OPS_FINALIZED
if op.status == constants.OP_STATUS_QUEUED:
# Queue is shutting down
assert not waitjob
finalize = False
# Reset context
job.cur_opctx = None
# In no case must the status be finalized here
assert job.CalcStatus() == constants.JOB_STATUS_QUEUED
elif op.status == constants.OP_STATUS_WAITING or waitjob:
finalize = False
if not waitjob and opctx.CheckPriorityIncrease():
# Priority was changed, need to update on-disk file
queue.UpdateJobUnlocked(job)
# Keep around for another round
job.cur_opctx = opctx
assert (op.priority <= constants.OP_PRIO_LOWEST and
op.priority >= constants.OP_PRIO_HIGHEST)
# In no case must the status be finalized here
assert job.CalcStatus() == constants.JOB_STATUS_WAITING
else:
# Ensure all opcodes so far have been successful
assert (opctx.index == 0 or
compat.all(i.status == constants.OP_STATUS_SUCCESS
for i in job.ops[:opctx.index]))
# Reset context
job.cur_opctx = None
if op.status == constants.OP_STATUS_SUCCESS:
finalize = False
elif op.status == constants.OP_STATUS_ERROR:
# If we get here, we cannot afford to check for any consistency
# any more, we just want to clean up.
# TODO: Actually, it wouldn't be a bad idea to start a timer
# here to kill the whole process.
to_encode = errors.OpExecError("Preceding opcode failed")
job.MarkUnfinishedOps(constants.OP_STATUS_ERROR,
_EncodeOpError(to_encode))
finalize = True
elif op.status == constants.OP_STATUS_CANCELING:
job.MarkUnfinishedOps(constants.OP_STATUS_CANCELED,
"Job canceled by request")
finalize = True
else:
raise errors.ProgrammerError("Unknown status '%s'" % op.status)
if opctx.index == (opcount - 1):
# Finalize on last opcode
finalize = True
if finalize:
# All opcodes have been run, finalize job
job.Finalize()
# Write to disk. If the job status is final, this is the final write
# allowed. Once the file has been written, it can be archived anytime.
queue.UpdateJobUnlocked(job)
assert not waitjob
if finalize:
logging.info("Finished job %s, status = %s", job.id, job.CalcStatus())
return self.FINISHED
assert not waitjob or queue.depmgr.JobWaiting(job)
if waitjob:
return self.WAITDEP
else:
return self.DEFER
finally:
assert job.writable, "Job became read-only while being processed"
class _JobDependencyManager:
"""Keeps track of job dependencies.
"""
(WAIT,
ERROR,
CANCEL,
CONTINUE,
WRONGSTATUS) = range(1, 6)
def __init__(self, getstatus_fn):
"""Initializes this class.
"""
self._getstatus_fn = getstatus_fn
self._waiters = {}
def JobWaiting(self, job):
"""Checks if a job is waiting.
"""
return compat.any(job in jobs
for jobs in self._waiters.values())
def CheckAndRegister(self, job, dep_job_id, dep_status):
"""Checks if a dependency job has the requested status.
If the other job is not yet in a finalized status, the calling job will be
notified (re-added to the workerpool) at a later point.
@type job: L{_QueuedJob}
@param job: Job object
@type dep_job_id: int
@param dep_job_id: ID of dependency job
@type dep_status: list
@param dep_status: Required status
"""
assert ht.TJobId(job.id)
assert ht.TJobId(dep_job_id)
assert ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))(dep_status)
if job.id == dep_job_id:
return (self.ERROR, "Job can't depend on itself")
# Get status of dependency job
try:
status = self._getstatus_fn(dep_job_id)
except errors.JobLost, err:
return (self.ERROR, "Dependency error: %s" % err)
assert status in constants.JOB_STATUS_ALL
job_id_waiters = self._waiters.setdefault(dep_job_id, set())
if status not in constants.JOBS_FINALIZED:
# Register for notification and wait for job to finish
job_id_waiters.add(job)
return (self.WAIT,
"Need to wait for job %s, wanted status '%s'" %
(dep_job_id, dep_status))
# Remove from waiters list
if job in job_id_waiters:
job_id_waiters.remove(job)
if (status == constants.JOB_STATUS_CANCELED and
constants.JOB_STATUS_CANCELED not in dep_status):
return (self.CANCEL, "Dependency job %s was cancelled" % dep_job_id)
elif not dep_status or status in dep_status:
return (self.CONTINUE,
"Dependency job %s finished with status '%s'" %
(dep_job_id, status))
else:
return (self.WRONGSTATUS,
"Dependency job %s finished with status '%s',"
" not one of '%s' as required" %
(dep_job_id, status, utils.CommaJoin(dep_status)))
def _RemoveEmptyWaitersUnlocked(self):
"""Remove all jobs without actual waiters.
"""
for job_id in [job_id for (job_id, waiters) in self._waiters.items()
if not waiters]:
del self._waiters[job_id]
class JobQueue(object):
"""Queue used to manage the jobs.
"""
def __init__(self, context, cfg):
"""Constructor for JobQueue.
The constructor will initialize the job queue object and then
start loading the current jobs from disk, either for starting them
(if they were queue) or for aborting them (if they were already
running).
@type context: GanetiContext
@param context: the context object for access to the configuration
data and other ganeti objects
"""
self.context = context
self._memcache = weakref.WeakValueDictionary()
self._my_hostname = netutils.Hostname.GetSysName()
# Get initial list of nodes
self._nodes = dict((n.name, n.primary_ip)
for n in cfg.GetAllNodesInfo().values()
if n.master_candidate)
# Remove master node
self._nodes.pop(self._my_hostname, None)
# Job dependencies
self.depmgr = _JobDependencyManager(self._GetJobStatusForDependencies)
def _GetRpc(self, address_list):
"""Gets RPC runner with context.
"""
return rpc.JobQueueRunner(self.context, address_list)
@staticmethod
def _CheckRpcResult(result, nodes, failmsg):
"""Verifies the status of an RPC call.
Since we aim to keep consistency should this node (the current
master) fail, we will log errors if our rpc fail, and especially
log the case when more than half of the nodes fails.
@param result: the data as returned from the rpc call
@type nodes: list
@param nodes: the list of nodes we made the call to
@type failmsg: str
@param failmsg: the identifier to be used for logging
"""
failed = []
success = []
for node in nodes:
msg = result[node].fail_msg
if msg:
failed.append(node)
logging.error("RPC call %s (%s) failed on node %s: %s",
result[node].call, failmsg, node, msg)
else:
success.append(node)
# +1 for the master node
if (len(success) + 1) < len(failed):
# TODO: Handle failing nodes
logging.error("More than half of the nodes failed")
def _GetNodeIp(self):
"""Helper for returning the node name/ip list.
@rtype: (list, list)
@return: a tuple of two lists, the first one with the node
names and the second one with the node addresses
"""
# TODO: Change to "tuple(map(list, zip(*self._nodes.items())))"?
name_list = self._nodes.keys()
addr_list = [self._nodes[name] for name in name_list]
return name_list, addr_list
def _UpdateJobQueueFile(self, file_name, data, replicate):
"""Writes a file locally and then replicates it to all nodes.
This function will replace the contents of a file on the local
node and then replicate it to all the other nodes we have.
@type file_name: str
@param file_name: the path of the file to be replicated
@type data: str
@param data: the new contents of the file
@type replicate: boolean
@param replicate: whether to spread the changes to the remote nodes
"""
getents = runtime.GetEnts()
utils.WriteFile(file_name, data=data, uid=getents.masterd_uid,
gid=getents.daemons_gid,
mode=constants.JOB_QUEUE_FILES_PERMS)
if replicate:
names, addrs = self._GetNodeIp()
result = _CallJqUpdate(self._GetRpc(addrs), names, file_name, data)
self._CheckRpcResult(result, self._nodes, "Updating %s" % file_name)
def _RenameFilesUnlocked(self, rename):
"""Renames a file locally and then replicate the change.
This function will rename a file in the local queue directory
and then replicate this rename to all the other nodes we have.
@type rename: list of (old, new)
@param rename: List containing tuples mapping old to new names
"""
# Rename them locally
for old, new in rename:
utils.RenameFile(old, new, mkdir=True)
# ... and on all nodes
names, addrs = self._GetNodeIp()
result = self._GetRpc(addrs).call_jobqueue_rename(names, rename)
self._CheckRpcResult(result, self._nodes, "Renaming files (%r)" % rename)
@staticmethod
def _GetJobPath(job_id):
"""Returns the job file for a given job id.
@type job_id: str
@param job_id: the job identifier
@rtype: str
@return: the path to the job file
"""
return utils.PathJoin(pathutils.QUEUE_DIR, "job-%s" % job_id)
@staticmethod
def _GetArchivedJobPath(job_id):
"""Returns the archived job file for a give job id.
@type job_id: str
@param job_id: the job identifier
@rtype: str
@return: the path to the archived job file
"""
return utils.PathJoin(pathutils.JOB_QUEUE_ARCHIVE_DIR,
jstore.GetArchiveDirectory(job_id),
"job-%s" % job_id)
@staticmethod
def _DetermineJobDirectories(archived):
"""Build list of directories containing job files.
@type archived: bool
@param archived: Whether to include directories for archived jobs
@rtype: list
"""
result = [pathutils.QUEUE_DIR]
if archived:
archive_path = pathutils.JOB_QUEUE_ARCHIVE_DIR
result.extend(map(compat.partial(utils.PathJoin, archive_path),
utils.ListVisibleFiles(archive_path)))
return result
@classmethod
def _GetJobIDsUnlocked(cls, sort=True, archived=False):
"""Return all known job IDs.
The method only looks at disk because it's a requirement that all
jobs are present on disk (so in the _memcache we don't have any
extra IDs).
@type sort: boolean
@param sort: perform sorting on the returned job ids
@rtype: list
@return: the list of job IDs
"""
jlist = []
for path in cls._DetermineJobDirectories(archived):
for filename in utils.ListVisibleFiles(path):
m = constants.JOB_FILE_RE.match(filename)
if m:
jlist.append(int(m.group(1)))
if sort:
jlist.sort()
return jlist
def _LoadJobUnlocked(self, job_id):
"""Loads a job from the disk or memory.
Given a job id, this will return the cached job object if
existing, or try to load the job from the disk. If loading from
disk, it will also add the job to the cache.
@type job_id: int
@param job_id: the job id
@rtype: L{_QueuedJob} or None
@return: either None or the job object
"""
assert isinstance(job_id, int), "Job queue: Supplied job id is not an int!"
job = self._memcache.get(job_id, None)
if job:
logging.debug("Found job %s in memcache", job_id)
assert job.writable, "Found read-only job in memcache"
return job
try:
job = JobQueue._LoadJobFromDisk(self, job_id, False)
if job is None:
return job
except errors.JobFileCorrupted:
old_path = self._GetJobPath(job_id)
new_path = self._GetArchivedJobPath(job_id)
if old_path == new_path:
# job already archived (future case)
logging.exception("Can't parse job %s", job_id)
else:
# non-archived case
logging.exception("Can't parse job %s, will archive.", job_id)
self._RenameFilesUnlocked([(old_path, new_path)])
return None
assert job.writable, "Job just loaded is not writable"
self._memcache[job_id] = job
logging.debug("Added job %s to the cache", job_id)
return job
@staticmethod
def _LoadJobFromDisk(queue, job_id, try_archived, writable=None):
"""Load the given job file from disk.
Given a job file, read, load and restore it in a _QueuedJob format.
@type job_id: int
@param job_id: job identifier
@type try_archived: bool
@param try_archived: Whether to try loading an archived job
@rtype: L{_QueuedJob} or None
@return: either None or the job object
"""
path_functions = [(JobQueue._GetJobPath, False)]
if try_archived:
path_functions.append((JobQueue._GetArchivedJobPath, True))
raw_data = None
archived = None
for (fn, archived) in path_functions:
filepath = fn(job_id)
logging.debug("Loading job from %s", filepath)
try:
raw_data = utils.ReadFile(filepath)
except EnvironmentError, err:
if err.errno != errno.ENOENT:
raise
else:
break
if not raw_data:
logging.debug("No data available for job %s", job_id)
return None
if writable is None:
writable = not archived
try:
data = serializer.LoadJson(raw_data)
job = _QueuedJob.Restore(queue, data, writable, archived)
except Exception, err: # pylint: disable=W0703
raise errors.JobFileCorrupted(err)
return job
@staticmethod
def SafeLoadJobFromDisk(queue, job_id, try_archived, writable=None):
"""Load the given job file from disk.
Given a job file, read, load and restore it in a _QueuedJob format.
In case of error reading the job, it gets returned as None, and the
exception is logged.
@type job_id: int
@param job_id: job identifier
@type try_archived: bool
@param try_archived: Whether to try loading an archived job
@rtype: L{_QueuedJob} or None
@return: either None or the job object
"""
try:
return JobQueue._LoadJobFromDisk(queue, job_id, try_archived,
writable=writable)
except (errors.JobFileCorrupted, EnvironmentError):
logging.exception("Can't load/parse job %s", job_id)
return None
@classmethod
def SubmitManyJobs(cls, jobs):
"""Create and store multiple jobs.
"""
return luxi.Client(address=pathutils.QUERY_SOCKET).SubmitManyJobs(jobs)
@staticmethod
def _ResolveJobDependencies(resolve_fn, deps):
"""Resolves relative job IDs in dependencies.
@type resolve_fn: callable
@param resolve_fn: Function to resolve a relative job ID
@type deps: list
@param deps: Dependencies
@rtype: tuple; (boolean, string or list)
@return: If successful (first tuple item), the returned list contains
resolved job IDs along with the requested status; if not successful,
the second element is an error message
"""
result = []
for (dep_job_id, dep_status) in deps:
if ht.TRelativeJobId(dep_job_id):
assert ht.TInt(dep_job_id) and dep_job_id < 0
try:
job_id = resolve_fn(dep_job_id)
except IndexError:
# Abort
return (False, "Unable to resolve relative job ID %s" % dep_job_id)
else:
job_id = dep_job_id
result.append((job_id, dep_status))
return (True, result)
def _GetJobStatusForDependencies(self, job_id):
"""Gets the status of a job for dependencies.
@type job_id: int
@param job_id: Job ID
@raise errors.JobLost: If job can't be found
"""
# Not using in-memory cache as doing so would require an exclusive lock
# Try to load from disk
job = JobQueue.SafeLoadJobFromDisk(self, job_id, True, writable=False)
if job:
assert not job.writable, "Got writable job" # pylint: disable=E1101
if job:
return job.CalcStatus()
raise errors.JobLost("Job %s not found" % job_id)
def UpdateJobUnlocked(self, job, replicate=True):
"""Update a job's on disk storage.
After a job has been modified, this function needs to be called in
order to write the changes to disk and replicate them to the other
nodes.
@type job: L{_QueuedJob}
@param job: the changed job
@type replicate: boolean
@param replicate: whether to replicate the change to remote nodes
"""
if __debug__:
finalized = job.CalcStatus() in constants.JOBS_FINALIZED
assert (finalized ^ (job.end_timestamp is None))
assert job.writable, "Can't update read-only job"
assert not job.archived, "Can't update archived job"
filename = self._GetJobPath(job.id)
data = serializer.DumpJson(job.Serialize())
logging.debug("Writing job %s to %s", job.id, filename)
self._UpdateJobQueueFile(filename, data, replicate)
def HasJobBeenFinalized(self, job_id):
"""Checks if a job has been finalized.
@type job_id: int
@param job_id: Job identifier
@rtype: boolean
@return: True if the job has been finalized,
False if the timeout has been reached,
None if the job doesn't exist
"""
job = JobQueue.SafeLoadJobFromDisk(self, job_id, True, writable=False)
if job is not None:
return job.CalcStatus() in constants.JOBS_FINALIZED
elif cluster.LUClusterDestroy.clusterHasBeenDestroyed:
# FIXME: The above variable is a temporary workaround until the Python job
# queue is completely removed. When removing the job queue, also remove
# the variable from LUClusterDestroy.
return True
else:
return None
def CancelJob(self, job_id):
"""Cancels a job.
This will only succeed if the job has not started yet.
@type job_id: int
@param job_id: job ID of job to be cancelled.
"""
logging.info("Cancelling job %s", job_id)
return self._ModifyJobUnlocked(job_id, lambda job: job.Cancel())
def ChangeJobPriority(self, job_id, priority):
"""Changes a job's priority.
@type job_id: int
@param job_id: ID of the job whose priority should be changed
@type priority: int
@param priority: New priority
"""
logging.info("Changing priority of job %s to %s", job_id, priority)
if priority not in constants.OP_PRIO_SUBMIT_VALID:
allowed = utils.CommaJoin(constants.OP_PRIO_SUBMIT_VALID)
raise errors.GenericError("Invalid priority %s, allowed are %s" %
(priority, allowed))
def fn(job):
(success, msg) = job.ChangePriority(priority)
return (success, msg)
return self._ModifyJobUnlocked(job_id, fn)
def _ModifyJobUnlocked(self, job_id, mod_fn):
"""Modifies a job.
@type job_id: int
@param job_id: Job ID
@type mod_fn: callable
@param mod_fn: Modifying function, receiving job object as parameter,
returning tuple of (status boolean, message string)
"""
job = self._LoadJobUnlocked(job_id)
if not job:
logging.debug("Job %s not found", job_id)
return (False, "Job %s not found" % job_id)
assert job.writable, "Can't modify read-only job"
assert not job.archived, "Can't modify archived job"
(success, msg) = mod_fn(job)
if success:
# If the job was finalized (e.g. cancelled), this is the final write
# allowed. The job can be archived anytime.
self.UpdateJobUnlocked(job)
return (success, msg)
|
bsd-2-clause
| -2,647,619,656,363,776,500
| 29.403734
| 80
| 0.644055
| false
| 3.897098
| false
| false
| false
|
tmoer/multimodal_varinf
|
networks/network_rl.py
|
1
|
7832
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 2 14:48:24 2017
@author: thomas
"""
#from layers import Latent_Layer
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
from tfutils.helpers import repeat_v2
from tfutils.distributions import logsumexp, discretized_logistic
from layers import Latent_Layer
class Network(object):
''' VAE & RL template '''
def __init__(self,hps,state_dim,binsize=6):
# binsize = the number of discrete categories per dimension of the state (x and y below).
# Input and output are normalized over this quantity.
# placeholders
self.x = x = tf.placeholder("float32", shape=[None,state_dim])
self.y = y = tf.placeholder("float32", shape=[None,state_dim])
self.a = a = tf.placeholder("float32", shape=[None,1])
self.Qtarget = Qtarget = tf.placeholder("float32", shape=[None,1])
self.is_training = is_training = tf.placeholder("bool") # if True: sample from q, else sample from p
self.k = k = tf.placeholder('int32') # number of importance samples
self.temp = temp = tf.Variable(5.0,name='temperature',trainable=False) # Temperature for discrete latents
self.lamb = lamb = tf.Variable(1.0,name="lambda",trainable=False) # Lambda for KL annealing
xa = tf.concat([x/binsize,a],axis=1)
# Importance sampling: repeats along second dimension
xa_rep = repeat_v2(xa,k)
y_rep = repeat_v2(y/binsize,k)
# RL part of the graph
with tf.variable_scope('q_net'):
rl1 = slim.fully_connected(x,50,tf.nn.relu)
rl2 = slim.fully_connected(rl1,50,tf.nn.relu)
rl3 = slim.fully_connected(rl2,50,activation_fn=None)
self.Qsa = Qsa = slim.fully_connected(rl3,4,activation_fn=None)
if hps.use_target_net:
with tf.variable_scope('target_net'):
rl1_t = slim.fully_connected(x,50,tf.nn.relu)
rl2_t = slim.fully_connected(rl1_t,50,tf.nn.relu)
rl3_t = slim.fully_connected(rl2_t,50,activation_fn=None)
self.Qsa_t = slim.fully_connected(rl3_t,4,activation_fn=None)
copy_ops = []
q_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='q_net')
tar_var = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='target_net')
for tar,q in zip(q_var,tar_var):
copy_op = q.assign(tar)
copy_ops.append(copy_op)
self.copy_op = tf.group(*copy_ops, name='copy_op')
a_onehot = tf.one_hot(tf.to_int32(tf.squeeze(a,axis=1)),4,1.0,0.0)
Qs = tf.reduce_sum(a_onehot*Qsa,reduction_indices=1) ## identify Qsa based on a
self.rl_cost = rl_cost = tf.nn.l2_loss(Qs - Qtarget)
# Batch norm: skip for now
# Encoder x,y --> h
xy = tf.concat([xa_rep,y_rep],1) # concatenate along last dim
h_up = slim.fully_connected(xy,hps.h_size,tf.nn.relu)
# Initialize ladders
layers = []
for i in range(hps.depth):
layers.append(Latent_Layer(hps,hps.var_type[i],i))
# Ladder up
for i,layer in enumerate(layers):
h_up = layer.up(h_up)
# Ladder down
# Prior x --> p_z
h_down = slim.fully_connected(xa_rep,hps.h_size,tf.nn.relu)
kl_sum = 0.0
kl_sample = 0.0
for i,layer in reversed(list(enumerate(layers))):
h_down, kl_cur, kl_sam = layer.down(h_down,is_training,temp,lamb)
kl_sum += kl_cur
kl_sample += kl_sam
# Decoder: x,z --> y
xz = tf.concat([slim.flatten(h_down),xa_rep],1)
dec1 = slim.fully_connected(xz,250,tf.nn.relu)
dec2 = slim.fully_connected(dec1,250,tf.nn.relu)
dec3 = slim.fully_connected(dec2,250,activation_fn=None)
mu_y = slim.fully_connected(dec3,state_dim,activation_fn=None)
if hps.ignore_sigma_outcome:
log_dec_noise = tf.zeros(tf.shape(mu_y))
else:
log_dec_noise = slim.fully_connected(dec3,1,activation_fn=None)
# p(y|x,z)
if hps.out_lik == 'normal':
dec_noise = tf.exp(tf.clip_by_value(log_dec_noise,-10,10))
outdist = tf.contrib.distributions.Normal(mu_y,dec_noise)
self.log_py_x = log_py_x = tf.reduce_sum(outdist.log_prob(y_rep),axis=1)
self.nats = -1*tf.reduce_mean(logsumexp(tf.reshape(log_py_x - kl_sample,[-1,k])) - tf.log(tf.to_float(k)))
y_sample = outdist.sample() if not hps.ignore_sigma_outcome else mu_y
self.y_sample = tf.to_int32(tf.round(tf.clip_by_value(y_sample,0,1)*binsize))
elif hps.out_lik == 'discretized_logistic':
self.log_py_x = log_py_x = tf.reduce_sum(discretized_logistic(mu_y,log_dec_noise,binsize=1,sample=y_rep),axis=1)
outdist = tf.contrib.distributions.Logistic(loc=mu_y,scale = tf.exp(log_dec_noise))
self.nats = -1*tf.reduce_mean(logsumexp(tf.reshape(tf.reduce_sum(outdist.log_prob(y_rep),axis=1) - kl_sample,[-1,k]))- tf.log(tf.to_float(k)))
y_sample = outdist.sample() if not hps.ignore_sigma_outcome else mu_y
self.y_sample = tf.to_int32(tf.round(tf.clip_by_value(y_sample,0,1)*binsize))
elif hps.out_lik == 'discrete':
logits_y = slim.fully_connected(dec3,state_dim*(binsize+1),activation_fn=None)
logits_y = tf.reshape(logits_y,[-1,state_dim,binsize+1])
disc_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_y,labels=tf.to_int32(tf.round(y_rep*6)))
self.log_py_x = log_py_x = -tf.reduce_sum(disc_loss,[1])
self.nats = -1*tf.reduce_mean(logsumexp(tf.reshape(log_py_x - kl_sample,[-1,k])) - tf.log(tf.to_float(k)))
outdist = tf.contrib.distributions.Categorical(logits=logits_y)
self.y_sample = outdist.sample() if not hps.ignore_sigma_outcome else tf.argmax(logits_y,axis=2)
# To display
self.kl = tf.reduce_mean(kl_sum)
# ELBO
log_divergence = tf.reshape(log_py_x - kl_sum,[-1,k]) # shape [batch_size,k]
if np.abs(hps.alpha-1.0)>1e-3: # use Renyi alpha-divergence
log_divergence = log_divergence * (1-hps.alpha)
logF = logsumexp(log_divergence)
self.elbo = elbo = tf.reduce_mean(logF - tf.log(tf.to_float(k)))/ (1-hps.alpha)
else:
# use KL divergence
self.elbo = elbo = tf.reduce_mean(log_divergence)
self.loss = loss = -elbo
### Optimizer
self.lr = lr = tf.Variable(0.001,name="learning_rate",trainable=False)
global_step = tf.Variable(0,name='global_step',trainable=False)
optimizer = tf.train.AdamOptimizer(learning_rate=lr)
if hps.max_grad != None:
grads_and_vars = optimizer.compute_gradients(loss)
for idx, (grad, var) in enumerate(grads_and_vars):
if grad is not None:
grads_and_vars[idx] = (tf.clip_by_norm(grad, hps.max_grad), var)
self.train_op = optimizer.apply_gradients(grads_and_vars)
self.grads_and_vars = grads_and_vars
else:
self.train_op = optimizer.minimize(loss,global_step=global_step)
self.grads_and_vars = tf.constant(0)
self.train_op_rl = optimizer.minimize(rl_cost)
self.init_op=tf.global_variables_initializer()
|
mit
| 8,419,598,953,240,772,000
| 47.652174
| 154
| 0.588994
| false
| 3.125299
| false
| false
| false
|
KaiserAndres/kaiserBot
|
bot_executables.py
|
1
|
4751
|
import roller
import random
DEFAULT_CARD_AMOUNT = 1
MAX_CARDS = 15
CARD_SEPARATOR = "||"
def ping_exec(irc, message):
pong = 'PONG ' + message.text.split(" ")[1] + '\r\n'
irc.send(pong.encode("utf-8"))
def roll_exec(irc, message):
'''
A !roll comand has the following structure:
!roll diceAmount+d+diceSize+"+"+modifier
* Dice amount is an integer up to 20000
* Dice Size is an integer
* Modifier is an integer that is added onto the roll after
The !Roll command can also have this structure:
!!roll d+diceAmount+d+diceSize+"+"+modifier
* Dice amount is the result of a roll of said size and then proceeds
to roll that many of the following dice
* Dice Size is an integer
* Modifier is an integer that is added onto the roll after
'''
diceNumbers = roller.getRolledNumbers(message.text)
messageToSend = ''
# -------------------------------------------------------------------
# Hard limits on the dice sizes
# -------------------------------------------------------------------
if diceNumbers[0] > 10:
diceNumbers[0] = 10
if diceNumbers[0] < 1:
diceNumbers[0] = 1
if diceNumbers[1] > 2000:
diceNumbers[1] = 2000
if diceNumbers[1] < 1:
diceNumbers[1] = 1
if diceNumbers[2] < 1:
diceNumbers[2] = 1
rolledArray = roller.roll(diceNumbers[0],
diceNumbers[1],
diceNumbers[2])
for rollNum in rolledArray:
# REMINDER: make a message maker function cause this is ugly!
if (diceNumbers[3] == 0):
messageToSend = (messageToSend +
"\x0312,15(" + str(diceNumbers[1]) +
"d" + str(diceNumbers[2]) + ") \x032,15[" +
str(rollNum) + "]\x031,15 : \x034,15{" +
str(rollNum + diceNumbers[3]) + "} ")
else:
messageToSend = (messageToSend + "\x0312,15(" +
str(diceNumbers[1]) + "d" +
str(diceNumbers[2]) + "+" +
str(diceNumbers[3]) + ") \x032,15[" +
str(rollNum) + "+" +
str(diceNumbers[3]) +
"]\x031,15 : \x034,15{" +
str(rollNum + diceNumbers[3]) + "} ")
irc.send(message.reply(messageToSend))
def join_exec(irc, message):
'''
A join command has the following structure:
!JOIN #CHANNEL
A message is sent to the irc server requesting to join #CHANNEL
'''
chann = ""
foundLink = False
for char in message.text:
if char == "#":
foundLink = True
if foundLink:
chann = chann + char
if chann != "":
join_message = "JOIN " + chann + "\n"
irc.send(join_message.encode("utf-8"))
else:
irc.send(message.reply("Error 02: bad channel."))
def tarot_exec(irc, message):
'''
Tarot command asks for the number of cards to be drawn and returns them.
A tarot command has the following structure:
!tarot <NUMBER OF CARDS>
'''
card_amount = get_card_amount(message)
card_spread = spread_cards(card_amount)
output_message = "You got these cards: " + CARD_SEPARATOR.join(card_spread)
irc.send(message.reply(output_message))
def spread_cards(card_amount):
card_spread = []
local_deck = load_deck("deck")
for time in range(0, card_amount):
card_index = random.randint(0, len(local_deck) - 1)
is_reversed = random.randint(0, 1) == 1
card_text = local_deck[card_index]
if is_reversed:
card_text = card_text + "(reversed)"
card_spread.append(card_text)
local_deck.remove(local_deck[card_index])
return card_spread
def get_card_amount(message):
number_buffer = ""
number_end = 9
for characterIndex in range(0, len(message.text)):
try:
int(message.text[characterIndex])
if characterIndex < number_end:
number_buffer = number_buffer + message.text[characterIndex]
except ValueError:
continue
try:
card_amount = int(number_buffer)
except ValueError:
card_amount = DEFAULT_CARD_AMOUNT
if card_amount > MAX_CARDS:
card_amount = MAX_CARDS
return card_amount
def load_deck(deck_file_name):
deck_file = open(deck_file_name, "r")
deck_text = deck_file.readlines()
deck = []
deck_file.close()
for card in deck_text:
deck.append(card[:-1])
return deck
|
mit
| -1,279,902,818,268,667,600
| 29.455128
| 80
| 0.53273
| false
| 3.708821
| false
| false
| false
|
thermokarst/advent-of-code-2015
|
day20.py
|
1
|
2724
|
# Matthew Ryan Dillon
# github.com/thermokarst
#
# --- Day 20: Infinite Elves and Infinite Houses ---
#
# To keep the Elves busy, Santa has them deliver some presents by hand,
# door-to-door. He sends them down a street with infinite houses numbered
# sequentially: 1, 2, 3, 4, 5, and so on.
#
# Each Elf is assigned a number, too, and delivers presents to houses based on
# that number:
#
# - The first Elf (number 1) delivers presents to every house: 1, 2, 3, 4, 5, ....
# - The second Elf (number 2) delivers presents to every second house: 2, 4, 6,
# 8, 10, ....
# - Elf number 3 delivers presents to every third house: 3, 6, 9, 12, 15, ....
#
# There are infinitely many Elves, numbered starting with 1. Each Elf delivers
# presents equal to ten times his or her number at each house.
#
# So, the first nine houses on the street end up like this:
#
# House 1 got 10 presents.
# House 2 got 30 presents.
# House 3 got 40 presents.
# House 4 got 70 presents.
# House 5 got 60 presents.
# House 6 got 120 presents.
# House 7 got 80 presents.
# House 8 got 150 presents.
# House 9 got 130 presents.
#
# The first house gets 10 presents: it is visited only by Elf 1, which delivers 1
# * 10 = 10 presents. The fourth house gets 70 presents, because it is visited by
# Elves 1, 2, and 4, for a total of 10 + 20 + 40 = 70 presents.
#
# What is the lowest house number of the house to get at least as many presents
# as the number in your puzzle input?
#
# --- Part Two ---
#
# The Elves decide they don't want to visit an infinite number of houses.
# Instead, each Elf will stop after delivering presents to 50 houses. To make up
# for it, they decide to deliver presents equal to eleven times their number at
# each house.
#
# With these changes, what is the new lowest house number of the house to get at
# least as many presents as the number in your puzzle input?
INPUT = 34000000
def visit_homes(pph, max_visit=None):
homes = [0 for x in range(int(INPUT/pph))]
for elf in range(1, len(homes)+1):
house = elf
count = 0
while house < len(homes):
if max_visit and count >= max_visit:
break
homes[house] += elf*pph
house += elf
count += 1
return homes
def check_homes(homes):
for house, presents in enumerate(homes):
if presents >= INPUT:
return (house, presents)
homes = visit_homes(10)
house, presents = check_homes(homes)
print("pt 1: house {}, presents {}".format(house, presents))
homes = visit_homes(11, max_visit=50)
house, presents = check_homes(homes)
print("pt 2: house {}, presents {}".format(house, presents))
|
mit
| -2,547,104,543,869,876,000
| 34.842105
| 82
| 0.656021
| false
| 3.182243
| false
| false
| false
|
emmettk/pvrsex
|
tiff_file_folder_divider.py
|
1
|
5268
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 16:14:22 2017
@author: ekrupczak on LaVision
Divide tiffs up into subfolders with maximum number of files per folder
This allows them to be imported into DaVis which seems unwilling to import more than about 10000 files at a time.
Or pull all tiffs from specified folder between start and end file numbers
"""
import os
import math
import re
def divide_tiffs(path, max_per_folder = 10000):
"""
Divides all tiffs in path into subfolders with up to max_per_folder files per subfolder
"""
tiffs = [file for file in os.listdir(path) if ".tif" in file]
num_sub_dir = math.ceil(len(tiffs)/max_per_folder)
print("Dividing", len(tiffs), "tiffs into", num_sub_dir, "directories")
for i in range(1,num_sub_dir+1):
os.mkdir(path+r"\tiffs_pt"+str(i).zfill(2))
if i < num_sub_dir:
for file in tiffs[max_per_folder*(i-1):max_per_folder*i]:
os.rename(path+r"\\"+file, path+r"\tiffs_pt"+str(i)+r"\\"+file)
elif i == num_sub_dir:
for file in tiffs[max_per_folder*(i-1):]:
os.rename(path+r"\\"+file, path+r"\tiffs_pt"+str(i)+r"\\"+file)
print("Directory", "tiffs_pt"+str(i), "populated")
def unpack_folders(path):
"""
Undoes divide_tiffs by unpacking all files in subfolders into the main folder
"""
for folder in [f for f in os.listdir(path) if "." not in f]:
print("unpacking", folder)
for file in os.listdir(path+"/"+folder):
os.rename(path+"/"+folder+"/"+file, path+"/"+file)
print("deleting empty folder", folder)
os.rmdir(path+"/"+folder)
def pull_nth_tiff(path, n):
"""
Pulls every nth tiff into a separate folder
Designed for reading into DaVis
Run 'unpack folders' after to undo this action
"""
tiffs = [file for file in os.listdir(path) if '.tif' in file.lower()]
print(len(tiffs), "tiffs in ", path)
newdirname = r"\every_"+str(n)+"th_tiff"
os.mkdir(path+newdirname)
for tiff in tiffs[0::n]:
os.rename(path+r"\\"+tiff, path+newdirname+"\\"+tiff)
print("Every", str(n)+"th tiff put in ", path+newdirname)
print("Folder contains ", len(os.listdir(path+newdirname)), "files")
def pull_tiffs_in_range(path, start, stop):
"""
Pull all tiffs between file number start and file number stop.
Assumes tiff names are formatted as follows: tiff_name_00001.tif
"""
tiffs = [file for file in os.listdir(path) if '.tif' in file.lower()]
print(len(tiffs), "tiffs in ", path)
newdirname = r"\tiffs_in_range"+str(start)+"_"+str(stop)
os.mkdir(path+newdirname)
for tiff in tiffs:
filenum = int(re.findall("(?:_)([0-9]+)(?:_grayscale\.tif|\.TIF)", tiff)[0])
# print(filenum, filenum > start, filenum < stop)
if start<=filenum<=stop:
# print(filenum, tiff)
os.rename(path+r"\\"+tiff, path+newdirname+"\\"+tiff)
print("Files placed in",path+newdirname)
print("Folder contains", len(os.listdir(path+newdirname)))
if __name__ == "__main__":
##2.5 hz
# n = 2 ##tower EO
# n = 6 ##pier EO
## ~2hz
# n = 8 ##pier EO (1.875hz)
##1.5 hz
# n = 3 #tower EO (1.66 hz)
##1 hz
# n = 15 ##pier EO
# n = 30 ##tower IR / pier IR
# n = 5 ## tower EO
## 0.66 Hz
# n = 8 ##tower EO (0.625 Hz)
##0.5 Hz
# n = 30 #pier EO
##0.33 Hz
n = 15 #tower EO
##0.166 Hz
# n = 30 #tower EO
#
# camera = "tower_EO_12mm"
# camera = "pier_EO_08mm"
# camera = "tower_IR_16mm"
# camera = "pier_IR_09mm"
# run = r"20170926_1000_towerEO_pierEO/"
# run = r"20170926_1100_pierIR_pierEO/"
# run = r"20170926_1200_towerIR_pierIR/"
# run = r"20170926_1300_towerIR_towerEO/"
#
# path = r"D:/RSEX17_TIFF/0926/"+run+camera
# path = r'D:/RSEX17_TIFF/1005/201710051000/'+camera+"/tiffs_in_range4488_7488"
#path = r'D:\RSEX17_TIFF\1015\201710151610\201710151610_tower_color'
# path = r'D:\RSEX17_TIFF\1005\201710051000\tower_1015_1025'
# path = r'D:\RSEX17_TIFF\1005\201710051000\tower_EO_12mm_range_4488_7488_grayscale'
# path = r'D:\RSEX17_TIFF\1005\201710051000\pier_EO_08mm'
path = r'D:\RSEX17_TIFF\1005\201710051000\tower_EO_12mm'
# path = r'E:\RSEX17_TIFF\1005\201710051000\pier_EO_08mm\tiffs_in_range13464_22464'
# path = r'D:\RSEX17_TIFF\1015\201710151610\201710151610_tower_grayscale'
# path = r"D:/RSEX17_TIFF/1013/201710131200/"+camera
# divide_tiffs(path, max_per_folder = 20*10**3)
# print("Tiffs divided")
# path = r'D:\RSEX17_TIFF\1005\201710051000\tower_EO_12mm_range_4488_7488_grayscale'
unpack_folders(path)
# pull_nth_tiff(path, n)
# path = r'D:/RSEX17_TIFF/1005/201710051000/tower_EO_12mm'
# unpack_folders(path)
#
# path = r"D:\RSEX17_TIFF\1005\201710051000\tower_EO_12mm_every_2th_tiff_grayscale"
# pull_tiffs_in_range(path, 4488, 7488)
# pull_tiffs_in_range(path, 13464, 22464)
# path = path+"\every_"+str(n)+"th_tiff"
# unpack_folders(path)
# path = r'E:\RSEX17_TIFF\1005\201710051000\pier_EO_08mm\tiffs_in_range13464_22464'
# pull_nth_tiff(path, n)
|
mit
| -5,883,737,634,653,318,000
| 33.664474
| 113
| 0.610478
| false
| 2.679552
| false
| false
| false
|
czcorpus/kontext
|
lib/bgcalc/csv_cache.py
|
1
|
1387
|
# Copyright (c) 2021 Charles University, Faculty of Arts,
# Institute of the Czech National Corpus
# Copyright (c) 2021 Tomas Machalek <tomas.machalek@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
import csv
def load_cached_partial(path, offset, limit):
with open(path, 'r') as fr:
csv_reader = csv.reader(fr)
_, total_str = next(csv_reader)
for i in range(0, offset):
next(csv_reader)
ans = []
i = offset
for row in csv_reader:
if i == offset + limit:
break
ans.append((row[0], ) + tuple(int(x) for x in row[1:]))
i += 1
return int(total_str), ans
def load_cached_full(path):
ans = []
with open(path, 'r') as fr:
csv_reader = csv.reader(fr)
_, total_str = next(csv_reader)
for row in csv_reader:
ans.append((row[0], ) + tuple(int(x) for x in row[1:]))
return int(total_str), ans
|
gpl-2.0
| 5,040,845,778,632,978,000
| 32.829268
| 67
| 0.618601
| false
| 3.583979
| false
| false
| false
|
arnavd96/Cinemiezer
|
myvenv/lib/python3.4/site-packages/music21/demos/smt2011.py
|
1
|
5140
|
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: smt2011.py
# Purpose: Demonstrations for the SMT 2011 demo
#
# Authors: Christopher Ariza
# Michael Scott Cuthbert
#
# Copyright: Copyright © 2011 Michael Scott Cuthbert and the music21 Project
# License: BSD or LGPL, see license.txt
#-------------------------------------------------------------------------------
import copy
from music21 import environment, corpus
_MOD = 'demo/smt2011.py'
environLocal = environment.Environment(_MOD)
def ex01():
# beethoven
#s1 = corpus.parse('opus18no1/movement3.xml')
#s1.show()
# has lots of triplets toward end
# viola not coming in as alto clef
# s2 = corpus.parse('haydn/opus17no1/movement3.zip')
# s2.show()
s2 = corpus.parse('haydn/opus17no2/movement3.zip')
# works well; some triplets are missing but playback correctly
s2Chordified = s2.measures(1, 25).chordify()
s2Chordified.show()
#-------------------------------------------------------------------------------
def chordsToAnalysis(chordStream, manifest, scale):
'''
manifest is a list of tuples in the following form:
(measureNumber, chordNumberOrNone, scaleDegree, octaveDisplay, durationTypeDisplay)
'''
from music21 import note, bar
chordMeasures = chordStream.getElementsByClass('Measure')
measureTemplate = copy.deepcopy(chordMeasures)
for i, m in enumerate(measureTemplate):
m.removeByClass(['GeneralNote'])
# assuming we have measure numbers
for (measureNumber, chordNumberOrNone, scaleDegree, octaveDisplay,
durationTypeDisplay, textDisplay) in manifest:
# assume measures are in order; replace with different method
m = chordMeasures[measureNumber-1]
mPost = measureTemplate[measureNumber-1]
if chordNumberOrNone is None:
c = m.notes[0]
else:
c = m.notes[chordNumberOrNone-1] # assume counting from 1
pTarget = scale.pitchFromDegree(scaleDegree)
match = False
p = None
for p in c.pitches:
if p.name == pTarget.name:
match = True
break
if not match:
print('no scale degree found in specified chord', p, pTarget)
pTarget.octave = octaveDisplay
n = note.Note(pTarget)
if durationTypeDisplay in ['whole']:
n.noteheadFill = False
else:
n.noteheadFill = True
n.stemDirection = 'noStem'
n.addLyric(textDisplay)
mPost.insert(c.getOffsetBySite(m), n)
# fill with rests
for m in measureTemplate:
m.rightBarline = bar.Barline('none')
# need to hide rests
if len(m.notes) == 0:
r = note.Rest(quarterLength=4)
r.hideObjectOnPrint = True
m.append(r)
return measureTemplate
def exShenker():
from music21 import stream, scale, bar
# wtc no 1
src = corpus.parse('bwv846')
#src.show()
melodicSrc = src.parts[0]
measureTemplate = copy.deepcopy(melodicSrc.getElementsByClass('Measure'))
for i, m in enumerate(measureTemplate):
m.removeByClass(['GeneralNote'])
m.number = i + 1
# this stream has triple bar lines, clefs, etc
unused_chords = src.flat.makeChords(minimumWindowSize=2)
analysis = stream.Score()
chordReduction = copy.deepcopy(measureTemplate)
for i, m in enumerate(chordReduction.getElementsByClass('Measure')):
mNotes = src.flat.getElementsByOffset(m.offset,
m.offset+m.barDuration.quarterLength, includeEndBoundary=False)
mNotes.makeChords(minimumWindowSize=4, inPlace=True)
c = mNotes.flat.notes[0]
c.duration.type = 'whole'
m.append(c)
m.rightBarline = bar.Barline('regular')
# add parts
scaleCMajor = scale.MajorScale('c')
#measureNumber, chordNumberOrNone, scaleDegree, octaveDisplay,
# durationTypeDisplay, textDisplay
manifest = [(1, None, 3, 5, 'whole', '3'),
(24, None, 2, 5, 'whole', '2'),
(35, None, 1, 5, 'whole', '1'),
]
analysis1 = chordsToAnalysis(chordReduction, manifest, scaleCMajor)
manifest = [(1, None, 1, 4, 'whole', 'I'),
(24, None, 5, 3, 'whole', 'V'),
(31, None, 4, 4, 'quarter', '--7'),
(35, None, 1, 4, 'whole', 'I'),
]
analysis2 = chordsToAnalysis(chordReduction, manifest, scaleCMajor)
analysis.insert(0, analysis1)
analysis.insert(0, analysis2)
analysis.insert(0, chordReduction)
analysis.show()
def demoMakeChords():
# wtc no 1
#src = corpus.parse('bwv65.2').measures(0, 5)
src = corpus.parse('opus18no1/movement3.xml').measures(0, 10)
src.flattenParts().makeChords(minimumWindowSize=3).show()
src = corpus.parse('opus18no1/movement3.xml').measures(0, 10)
src.chordify().show()
if __name__ == '__main__':
#ex01()
#exShenker()
demoMakeChords()
|
mit
| -2,055,209,700,920,989,400
| 30.527607
| 87
| 0.590971
| false
| 3.616467
| false
| false
| false
|
jaeddy/bripipetools
|
bripipetools/dbification/flowcellrun.py
|
1
|
8314
|
"""
Class for importing data from a sequencing run into GenLIMS and the
Research DB as new objects.
"""
import logging
import os
import re
from .. import parsing
from .. import database
from .. import annotation
logger = logging.getLogger(__name__)
class FlowcellRunImporter(object):
"""
Collects FlowcellRun and SequencedLibrary objects from a sequencing run,
converts to documents, inserts into database.
"""
def __init__(self, path, db, run_opts):
logger.debug("creating `SequencingImporter` instance")
logger.debug("...with arguments (path: '{}', db: '{}')"
.format(path, db.name))
self.path = path
self.db = db
self.run_opts = run_opts
def _collect_flowcellrun(self):
"""
Collect FlowcellRun object for flowcell run.
"""
path_items = parsing.parse_flowcell_path(self.path)
logger.info("collecting info for flowcell run {}"
.format(path_items['run_id']))
return annotation.FlowcellRunAnnotator(
run_id=path_items['run_id'],
pipeline_root=path_items['pipeline_root'],
db=self.db
).get_flowcell_run()
def _collect_sequencedlibraries(self):
"""
Collect list of SequencedLibrary objects for flowcell run.
"""
path_items = parsing.parse_flowcell_path(self.path)
logger.info("Collecting sequenced libraries for flowcell run '{}'"
.format(path_items['run_id']))
return annotation.FlowcellRunAnnotator(
run_id=path_items['run_id'],
pipeline_root=path_items['pipeline_root'],
db=self.db
).get_sequenced_libraries()
def _collect_librarygenecounts(self):
"""
Collect list of library gene count objects for flowcell run.
"""
path_items = parsing.parse_flowcell_path(self.path)
# print("path: {}, items: {}".format(self.path, path_items))
logger.info("Collecting library gene counts for flowcell run '{}'"
.format(path_items['run_id']))
return annotation.FlowcellRunAnnotator(
run_id=path_items['run_id'],
pipeline_root=path_items['pipeline_root'],
db=self.db
).get_library_gene_counts()
def _collect_librarymetrics(self):
"""
Collect list of library metrics objects for flowcell run.
"""
path_items = parsing.parse_flowcell_path(self.path)
# print("path: {}, items: {}".format(self.path, path_items))
logger.info("Collecting library metrics for flowcell run '{}'"
.format(path_items['run_id']))
return annotation.FlowcellRunAnnotator(
run_id=path_items['run_id'],
pipeline_root=path_items['pipeline_root'],
db=self.db
).get_library_metrics()
def _insert_flowcellrun(self, collection='all'):
"""
Convert FlowcellRun object and insert into GenLIMS database.
"""
flowcellrun = self._collect_flowcellrun()
logger.debug("inserting flowcell run {} into {}"
.format(flowcellrun, self.db.name))
database.put_runs(self.db, flowcellrun.to_json())
def _insert_sequencedlibraries(self):
"""
Convert SequencedLibrary objects and insert into GenLIMS database.
"""
sequencedlibraries = self._collect_sequencedlibraries()
for sl in sequencedlibraries:
logger.debug("inserting sequenced library {}".format(sl))
database.put_samples(self.db, sl.to_json())
def _insert_genomicsSequencedlibraries(self):
"""
Convert SequencedLibrary objects and insert into Research database.
"""
sequencedlibraries = self._collect_sequencedlibraries()
for sl in sequencedlibraries:
logger.debug("inserting sequenced library {}".format(sl))
database.put_genomicsSamples(self.db, sl.to_json())
def _insert_librarygenecounts(self):
"""
Convert Library Results objects and insert into Research database.
"""
librarygenecounts = self._collect_librarygenecounts()
for lgc in librarygenecounts:
logger.debug("inserting library gene counts '{}'".format(lgc))
database.put_genomicsCounts(self.db, lgc.to_json())
def _insert_librarymetrics(self):
"""
Convert Library Results objects and insert into GenLIMS database.
"""
librarymetrics = self._collect_librarymetrics()
for lgc in librarymetrics:
logger.debug("inserting library metrics '{}'".format(lgc))
database.put_metrics(self.db, lgc.to_json())
def _insert_genomicsLibrarymetrics(self):
"""
Convert Library Results objects and insert into Research database.
"""
librarymetrics = self._collect_librarymetrics()
for lgc in librarymetrics:
logger.debug("inserting library metrics '{}'".format(lgc))
database.put_genomicsMetrics(self.db, lgc.to_json())
def _insert_genomicsWorkflowbatches(self):
"""
Collect WorkflowBatch objects and insert them into database.
"""
path_items = parsing.parse_flowcell_path(self.path)
batchfile_dir = os.path.join(self.path, "globus_batch_submission")
logger.info("collecting info for workflow batch files in '{}'"
.format(batchfile_dir))
batchfile_list = [batchfile for batchfile in os.listdir(batchfile_dir)
if not re.search('DS_Store', batchfile)]
for curr_batchfile in batchfile_list:
workflowbatch = annotation.WorkflowBatchAnnotator(
workflowbatch_file=os.path.join(batchfile_dir, curr_batchfile),
pipeline_root=path_items['pipeline_root'],
db=self.db,
run_opts = self.run_opts
).get_workflow_batch()
logger.debug("inserting workflow batch '{}'".format(workflowbatch))
database.put_genomicsWorkflowbatches(self.db, workflowbatch.to_json())
def insert(self, collection='genlims'):
"""
Insert documents into GenLIMS or ResearchDB databases.
Note that ResearchDB collections are prepended by 'genomics'
to indicate the data origin.
"""
# Sample information into ResDB/GenLIMS
if collection in ['all', 'researchdb', 'genomicsSamples']:
logger.info(("Inserting sequenced libraries for flowcell '{}' "
"into '{}'").format(self.path, self.db.name))
self._insert_genomicsSequencedlibraries()
if collection in ['all', 'genlims', 'samples']:
logger.info(("Inserting sequenced libraries for flowcell '{}' "
"into '{}'").format(self.path, self.db.name))
self._insert_sequencedlibraries()
# Gene counts - only into ResDB
if collection in ['all', 'researchdb', 'genomicsCounts']:
logger.info(("Inserting gene counts for libraries for flowcell '{}' "
"into '{}'").format(self.path, self.db.name))
self._insert_librarygenecounts()
# Metrics information - only into ResDB
if collection in ['all', 'researchdb', 'genomicsMetrics']:
logger.info(("Inserting metrics for libraries for flowcell '{}' "
"into '{}'").format(self.path, self.db.name))
self._insert_genomicsLibrarymetrics()
# Workflow Batch files - only into ResDB
if collection in ['all', 'researchdb', 'genomicsWorkflowbatches']:
logger.info(("Inserting workflow batches for flowcell '{}' "
"into '{}'").format(self.path, self.db.name))
self._insert_genomicsWorkflowbatches()
# Run information into GenLIMS
if collection in ['all', 'genlims', 'flowcell', 'runs']:
logger.info("Inserting flowcell run '{}' into '{}'"
.format(self.path, self.db.name))
self._insert_flowcellrun()
|
mit
| 3,064,618,017,734,528,000
| 39.955665
| 82
| 0.595141
| false
| 4.294421
| false
| false
| false
|
hidashun/django-typed-models
|
typedmodels/tests.py
|
1
|
8182
|
from django.utils import unittest
try:
import yaml # NOQA
PYYAML_AVAILABLE = True
except ImportError:
PYYAML_AVAILABLE = False
from django.core import serializers
from django.test import TestCase
from django.db.models.query_utils import DeferredAttribute
from .test_models import AngryBigCat, Animal, BigCat, Canine, Feline, Parrot, AbstractVegetable, Vegetable, Fruit
class SetupStuff(TestCase):
def setUp(self):
Feline.objects.create(name="kitteh")
Feline.objects.create(name="cheetah")
Canine.objects.create(name="fido")
BigCat.objects.create(name="simba")
AngryBigCat.objects.create(name="mufasa")
Parrot.objects.create(name="Kajtek")
class TestTypedModels(SetupStuff):
def test_cant_instantiate_base_model(self):
# direct instantiation shouldn't work
self.assertRaises(RuntimeError, Animal.objects.create, name="uhoh")
# ... unless a type is specified
Animal.objects.create(name="dingo", type="typedmodels.canine")
# ... unless that type is stupid
try:
Animal.objects.create(name="dingo", type="macaroni.buffaloes")
except ValueError:
pass
def test_get_types(self):
self.assertEqual(set(Animal.get_types()), set(['typedmodels.canine', 'typedmodels.bigcat', 'typedmodels.parrot', 'typedmodels.angrybigcat', 'typedmodels.feline']))
self.assertEqual(set(Canine.get_types()), set(['typedmodels.canine']))
self.assertEqual(set(Feline.get_types()), set(['typedmodels.bigcat', 'typedmodels.angrybigcat', 'typedmodels.feline']))
def test_get_type_classes(self):
self.assertEqual(set(Animal.get_type_classes()), set([Canine, BigCat, Parrot, AngryBigCat, Feline]))
self.assertEqual(set(Canine.get_type_classes()), set([Canine]))
self.assertEqual(set(Feline.get_type_classes()), set([BigCat, AngryBigCat, Feline]))
def test_base_model_queryset(self):
# all objects returned
qs = Animal.objects.all().order_by('type')
self.assertEqual(len(qs), 6)
self.assertEqual([obj.type for obj in qs], ['typedmodels.angrybigcat', 'typedmodels.bigcat', 'typedmodels.canine', 'typedmodels.feline', 'typedmodels.feline', 'typedmodels.parrot'])
self.assertEqual([type(obj) for obj in qs], [AngryBigCat, BigCat, Canine, Feline, Feline, Parrot])
def test_proxy_model_queryset(self):
qs = Canine.objects.all().order_by('type')
self.assertEqual(qs.count(), 1)
self.assertEqual(len(qs), 1)
self.assertEqual([obj.type for obj in qs], ['typedmodels.canine'])
self.assertEqual([type(obj) for obj in qs], [Canine])
qs = Feline.objects.all().order_by('type')
self.assertEqual(qs.count(), 4)
self.assertEqual(len(qs), 4)
self.assertEqual([obj.type for obj in qs], ['typedmodels.angrybigcat', 'typedmodels.bigcat', 'typedmodels.feline', 'typedmodels.feline'])
self.assertEqual([type(obj) for obj in qs], [AngryBigCat, BigCat, Feline, Feline])
def test_doubly_proxied_model_queryset(self):
qs = BigCat.objects.all().order_by('type')
self.assertEqual(qs.count(), 2)
self.assertEqual(len(qs), 2)
self.assertEqual([obj.type for obj in qs], ['typedmodels.angrybigcat', 'typedmodels.bigcat'])
self.assertEqual([type(obj) for obj in qs], [AngryBigCat, BigCat])
def test_triply_proxied_model_queryset(self):
qs = AngryBigCat.objects.all().order_by('type')
self.assertEqual(qs.count(), 1)
self.assertEqual(len(qs), 1)
self.assertEqual([obj.type for obj in qs], ['typedmodels.angrybigcat'])
self.assertEqual([type(obj) for obj in qs], [AngryBigCat])
def test_recast_auto(self):
cat = Feline.objects.get(name='kitteh')
cat.type = 'typedmodels.bigcat'
cat.recast()
self.assertEqual(cat.type, 'typedmodels.bigcat')
self.assertEqual(type(cat), BigCat)
def test_recast_string(self):
cat = Feline.objects.get(name='kitteh')
cat.recast('typedmodels.bigcat')
self.assertEqual(cat.type, 'typedmodels.bigcat')
self.assertEqual(type(cat), BigCat)
def test_recast_modelclass(self):
cat = Feline.objects.get(name='kitteh')
cat.recast(BigCat)
self.assertEqual(cat.type, 'typedmodels.bigcat')
self.assertEqual(type(cat), BigCat)
def test_recast_fail(self):
cat = Feline.objects.get(name='kitteh')
self.assertRaises(ValueError, cat.recast, AbstractVegetable)
self.assertRaises(ValueError, cat.recast, 'typedmodels.abstractvegetable')
self.assertRaises(ValueError, cat.recast, Vegetable)
self.assertRaises(ValueError, cat.recast, 'typedmodels.vegetable')
def test_fields_in_subclasses(self):
canine = Canine.objects.all()[0]
angry = AngryBigCat.objects.all()[0]
angry.mice_eaten = 5
angry.save()
self.assertEqual(AngryBigCat.objects.get(pk=angry.pk).mice_eaten, 5)
angry.canines_eaten.add(canine)
self.assertEqual(list(angry.canines_eaten.all()), [canine])
# Feline class was created before Parrot and has mice_eaten field which is non-m2m, so it may break accessing
# known_words field in Parrot instances (since Django 1.5).
parrot = Parrot.objects.all()[0]
parrot.known_words = 500
parrot.save()
self.assertEqual(Parrot.objects.get(pk=parrot.pk).known_words, 500)
def test_fields_cache(self):
mice_eaten = Feline._meta.get_field('mice_eaten')
known_words = Parrot._meta.get_field('known_words')
self.assertIn(mice_eaten, AngryBigCat._meta.fields)
self.assertIn(mice_eaten, Feline._meta.fields)
self.assertNotIn(mice_eaten, Parrot._meta.fields)
self.assertIn(known_words, Parrot._meta.fields)
self.assertNotIn(known_words, AngryBigCat._meta.fields)
self.assertNotIn(known_words, Feline._meta.fields)
def test_m2m_cache(self):
canines_eaten = AngryBigCat._meta.get_field_by_name('canines_eaten')[0]
self.assertIn(canines_eaten, AngryBigCat._meta.many_to_many)
self.assertNotIn(canines_eaten, Feline._meta.many_to_many)
self.assertNotIn(canines_eaten, Parrot._meta.many_to_many)
def test_related_names(self):
'''Ensure that accessor names for reverse relations are generated properly.'''
canine = Canine.objects.all()[0]
self.assertTrue(hasattr(canine, 'angrybigcat_set'))
def test_queryset_defer(self):
"""
Ensure that qs.defer() works correctly
"""
Vegetable.objects.create(name='cauliflower', color='white', yumness=1)
Vegetable.objects.create(name='spinach', color='green', yumness=5)
Vegetable.objects.create(name='sweetcorn', color='yellow', yumness=10)
Fruit.objects.create(name='Apple', color='red', yumness=7)
qs = AbstractVegetable.objects.defer('yumness')
objs = set(qs)
for o in objs:
print(o)
self.assertIsInstance(o, AbstractVegetable)
self.assertTrue(o._deferred)
self.assertIsInstance(o.__class__.__dict__['yumness'], DeferredAttribute)
# does a query, since this field was deferred
self.assertIsInstance(o.yumness, float)
def _check_serialization(self, serialization_format):
"""Helper function used to check serialization and deserialization for concrete format."""
animals = Animal.objects.order_by('pk')
serialized_animals = serializers.serialize(serialization_format, animals)
deserialized_animals = [wrapper.object for wrapper in serializers.deserialize(serialization_format, serialized_animals)]
self.assertEqual(set(deserialized_animals), set(animals))
def test_xml_serialization(self):
self._check_serialization('xml')
def test_json_serialization(self):
self._check_serialization('json')
@unittest.skipUnless(PYYAML_AVAILABLE, 'PyYAML is not available.')
def test_yaml_serialization(self):
self._check_serialization('yaml')
|
bsd-3-clause
| -235,403,817,046,583,680
| 43.467391
| 189
| 0.666585
| false
| 3.466949
| true
| false
| false
|
Zogg/Tiltai
|
tiltai/sdn/docker.py
|
1
|
1700
|
from tiltai.utils import tiltai_logs_format
import socket
from logbook import Logger, StderrHandler
err = StderrHandler(format_string=tiltai_logs_format)
log = Logger("sdn[docker]")
def dockersdn(queue_name, resolver, storage):
"""
Get addresses and type of the socket from within docker container. A
hostname of the container is used as the identifier to receive network links
definition.
Parameters
----------
queue_name : string
Name of the queue, for which to get network settings
resolver : callable
A `name` -> `network address` mapper. More than likely one of resolvers
provided by `tiltai.sdn` modules
storage : callable
A data backend which provides network mapping: definition of links
between gates. More than likely one of the methods provided by
`tiltai.sdn` modules
Returns
-------
network : dict
A dict of shape `{'endpoints': [], 'type': value}`
"""
with err.applicationbound():
hostname = socket.gethostname()
log.debug('My hostname is: ' + hostname)
links = storage(hostname)
if links:
for link in links['links']:
if link['queue'] == queue_name:
if link.get('outgate', None):
protocolized_nodes = ['tcp://' + address for address in resolver(link['outgate'])]
endpoints = {'endpoints': protocolized_nodes}
else:
endpoints = {'endpoints': link.get('addresses', [])}
if link.get('type', None):
endpoints['type'] = link['type']
log.debug('Topology resolved to ip addresses: ' + str(endpoints))
return endpoints
return {'endpoints': []}
|
gpl-3.0
| -5,203,554,288,579,424,000
| 29.357143
| 94
| 0.63
| false
| 4.228856
| false
| false
| false
|
AdamsLee/mongo-connector
|
mongo_connector/connector.py
|
1
|
31437
|
# Copyright 2013-2014 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Discovers the mongo cluster and starts the connector.
"""
import json
import logging
import logging.handlers
import optparse
import os
import pymongo
import re
import shutil
import sys
import threading
import time
import imp
from mongo_connector import constants, errors, util
from mongo_connector.locking_dict import LockingDict
from mongo_connector.oplog_manager import OplogThread
from mongo_connector.doc_managers import doc_manager_simulator as simulator
from pymongo import MongoClient
class Connector(threading.Thread):
"""Checks the cluster for shards to tail.
"""
def __init__(self, address, oplog_checkpoint, target_url, ns_set,
u_key, auth_key, doc_manager=None, auth_username=None,
collection_dump=True, batch_size=constants.DEFAULT_BATCH_SIZE,
fields=None, dest_mapping={},
auto_commit_interval=constants.DEFAULT_COMMIT_INTERVAL):
if target_url and not doc_manager:
raise errors.ConnectorError("Cannot create a Connector with a "
"target URL but no doc manager!")
def is_string(s):
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str)
def load_doc_manager(path):
name, _ = os.path.splitext(os.path.basename(path))
try:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader(name, path)
module = loader.load_module(name)
except ImportError:
module = imp.load_source(name, path)
return module
doc_manager_modules = None
if doc_manager is not None:
# backwards compatilibity: doc_manager may be a string
if is_string(doc_manager):
doc_manager_modules = [load_doc_manager(doc_manager)]
# doc_manager is a list
else:
doc_manager_modules = []
for dm in doc_manager:
doc_manager_modules.append(load_doc_manager(dm))
super(Connector, self).__init__()
#can_run is set to false when we join the thread
self.can_run = True
#The name of the file that stores the progress of the OplogThreads
self.oplog_checkpoint = oplog_checkpoint
#main address - either mongos for sharded setups or a primary otherwise
self.address = address
#The URLs of each target system, respectively
if is_string(target_url):
self.target_urls = [target_url]
elif target_url:
self.target_urls = list(target_url)
else:
self.target_urls = None
#The set of relevant namespaces to consider
self.ns_set = ns_set
#The dict of source namespace to destination namespace
self.dest_mapping = dest_mapping
#The key that is a unique document identifier for the target system.
#Not necessarily the mongo unique key.
self.u_key = u_key
#Password for authentication
self.auth_key = auth_key
#Username for authentication
self.auth_username = auth_username
#The set of OplogThreads created
self.shard_set = {}
#Boolean chooses whether to dump the entire collection if no timestamp
# is present in the config file
self.collection_dump = collection_dump
#Num entries to process before updating config file with current pos
self.batch_size = batch_size
#Dict of OplogThread/timestamp pairs to record progress
self.oplog_progress = LockingDict()
# List of fields to export
self.fields = fields
try:
docman_kwargs = {"unique_key": u_key,
"namespace_set": ns_set,
"auto_commit_interval": auto_commit_interval}
# No doc managers specified, using simulator
if doc_manager is None:
self.doc_managers = [simulator.DocManager(**docman_kwargs)]
else:
self.doc_managers = []
for i, d in enumerate(doc_manager_modules):
# self.target_urls may be shorter than
# self.doc_managers, or left as None
if self.target_urls and i < len(self.target_urls):
target_url = self.target_urls[i]
else:
target_url = None
if target_url:
self.doc_managers.append(
d.DocManager(self.target_urls[i],
**docman_kwargs))
else:
self.doc_managers.append(
d.DocManager(**docman_kwargs))
# If more target URLs were given than doc managers, may need
# to create additional doc managers
for url in self.target_urls[i + 1:]:
self.doc_managers.append(
doc_manager_modules[-1].DocManager(url,
**docman_kwargs))
except errors.ConnectionFailed:
err_msg = "MongoConnector: Could not connect to target system"
logging.critical(err_msg)
self.can_run = False
return
if self.oplog_checkpoint is not None:
if not os.path.exists(self.oplog_checkpoint):
info_str = ("MongoConnector: Can't find %s, "
"attempting to create an empty progress log" %
self.oplog_checkpoint)
logging.info(info_str)
try:
# Create oplog progress file
open(self.oplog_checkpoint, "w").close()
except IOError as e:
logging.critical("MongoConnector: Could not "
"create a progress log: %s" %
str(e))
sys.exit(2)
else:
if (not os.access(self.oplog_checkpoint, os.W_OK)
and not os.access(self.oplog_checkpoint, os.R_OK)):
logging.critical("Invalid permissions on %s! Exiting" %
(self.oplog_checkpoint))
sys.exit(2)
def join(self):
""" Joins thread, stops it from running
"""
self.can_run = False
for dm in self.doc_managers:
dm.stop()
threading.Thread.join(self)
def write_oplog_progress(self):
""" Writes oplog progress to file provided by user
"""
if self.oplog_checkpoint is None:
return None
# write to temp file
backup_file = self.oplog_checkpoint + '.backup'
os.rename(self.oplog_checkpoint, backup_file)
# for each of the threads write to file
with open(self.oplog_checkpoint, 'w') as dest:
with self.oplog_progress as oplog_prog:
oplog_dict = oplog_prog.get_dict()
for oplog, time_stamp in oplog_dict.items():
oplog_str = str(oplog)
timestamp = util.bson_ts_to_long(time_stamp)
json_str = json.dumps([oplog_str, timestamp])
try:
dest.write(json_str)
except IOError:
# Basically wipe the file, copy from backup
dest.truncate()
with open(backup_file, 'r') as backup:
shutil.copyfile(backup, dest)
break
os.remove(self.oplog_checkpoint + '.backup')
def read_oplog_progress(self):
"""Reads oplog progress from file provided by user.
This method is only called once before any threads are spanwed.
"""
if self.oplog_checkpoint is None:
return None
# Check for empty file
try:
if os.stat(self.oplog_checkpoint).st_size == 0:
logging.info("MongoConnector: Empty oplog progress file.")
return None
except OSError:
return None
source = open(self.oplog_checkpoint, 'r')
try:
data = json.load(source)
except ValueError: # empty file
reason = "It may be empty or corrupt."
logging.info("MongoConnector: Can't read oplog progress file. %s" %
(reason))
source.close()
return None
source.close()
count = 0
oplog_dict = self.oplog_progress.get_dict()
for count in range(0, len(data), 2):
oplog_str = data[count]
time_stamp = data[count + 1]
oplog_dict[oplog_str] = util.long_to_bson_ts(time_stamp)
#stored as bson_ts
def run(self):
"""Discovers the mongo cluster and creates a thread for each primary.
"""
main_conn = MongoClient(self.address)
if self.auth_key is not None:
main_conn['admin'].authenticate(self.auth_username, self.auth_key)
self.read_oplog_progress()
conn_type = None
try:
main_conn.admin.command("isdbgrid")
except pymongo.errors.OperationFailure:
conn_type = "REPLSET"
if conn_type == "REPLSET":
# Make sure we are connected to a replica set
is_master = main_conn.admin.command("isMaster")
if not "setName" in is_master:
logging.error(
'No replica set at "%s"! A replica set is required '
'to run mongo-connector. Shutting down...' % self.address
)
return
# Establish a connection to the replica set as a whole
main_conn.disconnect()
main_conn = MongoClient(self.address,
replicaSet=is_master['setName'])
if self.auth_key is not None:
main_conn.admin.authenticate(self.auth_username, self.auth_key)
#non sharded configuration
oplog_coll = main_conn['local']['oplog.rs']
oplog = OplogThread(
primary_conn=main_conn,
main_address=self.address,
oplog_coll=oplog_coll,
is_sharded=False,
doc_manager=self.doc_managers,
oplog_progress_dict=self.oplog_progress,
namespace_set=self.ns_set,
auth_key=self.auth_key,
auth_username=self.auth_username,
repl_set=is_master['setName'],
collection_dump=self.collection_dump,
batch_size=self.batch_size,
fields=self.fields,
dest_mapping=self.dest_mapping
)
self.shard_set[0] = oplog
logging.info('MongoConnector: Starting connection thread %s' %
main_conn)
oplog.start()
while self.can_run:
if not self.shard_set[0].running:
logging.error("MongoConnector: OplogThread"
" %s unexpectedly stopped! Shutting down" %
(str(self.shard_set[0])))
self.oplog_thread_join()
for dm in self.doc_managers:
dm.stop()
return
self.write_oplog_progress()
time.sleep(1)
else: # sharded cluster
while self.can_run is True:
for shard_doc in main_conn['config']['shards'].find():
shard_id = shard_doc['_id']
if shard_id in self.shard_set:
if not self.shard_set[shard_id].running:
logging.error("MongoConnector: OplogThread "
"%s unexpectedly stopped! Shutting "
"down" %
(str(self.shard_set[shard_id])))
self.oplog_thread_join()
for dm in self.doc_managers:
dm.stop()
return
self.write_oplog_progress()
time.sleep(1)
continue
try:
repl_set, hosts = shard_doc['host'].split('/')
except ValueError:
cause = "The system only uses replica sets!"
logging.error("MongoConnector: %s", cause)
self.oplog_thread_join()
for dm in self.doc_managers:
dm.stop()
return
shard_conn = MongoClient(hosts, replicaSet=repl_set)
oplog_coll = shard_conn['local']['oplog.rs']
oplog = OplogThread(
primary_conn=shard_conn,
main_address=self.address,
oplog_coll=oplog_coll,
is_sharded=True,
doc_manager=self.doc_managers,
oplog_progress_dict=self.oplog_progress,
namespace_set=self.ns_set,
auth_key=self.auth_key,
auth_username=self.auth_username,
collection_dump=self.collection_dump,
batch_size=self.batch_size,
fields=self.fields,
dest_mapping=self.dest_mapping
)
self.shard_set[shard_id] = oplog
msg = "Starting connection thread"
logging.info("MongoConnector: %s %s" % (msg, shard_conn))
oplog.start()
self.oplog_thread_join()
self.write_oplog_progress()
def oplog_thread_join(self):
"""Stops all the OplogThreads
"""
logging.info('MongoConnector: Stopping all OplogThreads')
for thread in self.shard_set.values():
thread.join()
def main():
""" Starts the mongo connector (assuming CLI)
"""
parser = optparse.OptionParser()
#-m is for the main address, which is a host:port pair, ideally of the
#mongos. For non sharded clusters, it can be the primary.
parser.add_option("-m", "--main", action="store", type="string",
dest="main_addr", default="localhost:27217",
help="""Specify the main address, which is a"""
""" host:port pair. For sharded clusters, this"""
""" should be the mongos address. For individual"""
""" replica sets, supply the address of the"""
""" primary. For example, `-m localhost:27217`"""
""" would be a valid argument to `-m`. Don't use"""
""" quotes around the address.""")
#-o is to specify the oplog-config file. This file is used by the system
#to store the last timestamp read on a specific oplog. This allows for
#quick recovery from failure.
parser.add_option("-o", "--oplog-ts", action="store", type="string",
dest="oplog_config", default="config.txt",
help="""Specify the name of the file that stores the """
"""oplog progress timestamps. """
"""This file is used by the system to store the last """
"""timestamp read on a specific oplog. This allows """
"""for quick recovery from failure. By default this """
"""is `config.txt`, which starts off empty. An empty """
"""file causes the system to go through all the mongo """
"""oplog and sync all the documents. Whenever the """
"""cluster is restarted, it is essential that the """
"""oplog-timestamp config file be emptied - otherwise """
"""the connector will miss some documents and behave """
"""incorrectly.""")
#--no-dump specifies whether we should read an entire collection from
#scratch if no timestamp is found in the oplog_config.
parser.add_option("--no-dump", action="store_true", default=False, help=
"If specified, this flag will ensure that "
"mongo_connector won't read the entire contents of a "
"namespace iff --oplog-ts points to an empty file.")
#--batch-size specifies num docs to read from oplog before updating the
#--oplog-ts config file with current oplog position
parser.add_option("--batch-size", action="store",
default=constants.DEFAULT_BATCH_SIZE, type="int",
help="Specify an int to update the --oplog-ts "
"config file with latest position of oplog every "
"N documents. By default, the oplog config isn't "
"updated until we've read through the entire oplog. "
"You may want more frequent updates if you are at risk "
"of falling behind the earliest timestamp in the oplog")
#-t is to specify the URL to the target system being used.
parser.add_option("-t", "--target-url", "--target-urls", action="store",
type="string", dest="urls", default=None, help=
"""Specify the URL to each target system being """
"""used. For example, if you were using Solr out of """
"""the box, you could use '-t """
"""http://localhost:8080/solr' with the """
"""SolrDocManager to establish a proper connection. """
"""URLs should be specified in the same order as """
"""their respective doc managers in the """
"""--doc-managers option. URLs are assigned to doc """
"""managers respectively. Additional doc managers """
"""are implied to have no target URL. Additional """
"""URLs are implied to have the same doc manager """
"""type as the last doc manager for which a URL was """
"""specified. """
"""Don't use quotes around addresses. """)
#-n is to specify the namespaces we want to consider. The default
#considers all the namespaces
parser.add_option("-n", "--namespace-set", action="store", type="string",
dest="ns_set", default=None, help=
"""Used to specify the namespaces we want to """
"""consider. For example, if we wished to store all """
"""documents from the test.test and alpha.foo """
"""namespaces, we could use `-n test.test,alpha.foo`. """
"""The default is to consider all the namespaces, """
"""excluding the system and config databases, and """
"""also ignoring the "system.indexes" collection in """
"""any database.""")
#-u is to specify the mongoDB field that will serve as the unique key
#for the target system,
parser.add_option("-u", "--unique-key", action="store", type="string",
dest="u_key", default="_id", help=
"""The name of the MongoDB field that will serve """
"""as the unique key for the target system. """
"""Note that this option does not apply """
"""when targeting another MongoDB cluster. """
"""Defaults to "_id".""")
#-f is to specify the authentication key file. This file is used by mongos
#to authenticate connections to the shards, and we'll use it in the oplog
#threads.
parser.add_option("-f", "--password-file", action="store", type="string",
dest="auth_file", default=None, help=
"""Used to store the password for authentication."""
""" Use this option if you wish to specify a"""
""" username and password but don't want to"""
""" type in the password. The contents of this"""
""" file should be the password for the admin user.""")
#-p is to specify the password used for authentication.
parser.add_option("-p", "--password", action="store", type="string",
dest="password", default=None, help=
"""Used to specify the password."""
""" This is used by mongos to authenticate"""
""" connections to the shards, and in the"""
""" oplog threads. If authentication is not used, then"""
""" this field can be left empty as the default """)
#-a is to specify the username for authentication.
parser.add_option("-a", "--admin-username", action="store", type="string",
dest="admin_name", default="__system", help=
"""Used to specify the username of an admin user to """
"""authenticate with. To use authentication, the user """
"""must specify both an admin username and a keyFile. """
"""The default username is '__system'""")
#-d is to specify the doc manager file.
parser.add_option("-d", "--docManager", "--doc-managers", action="store",
type="string", dest="doc_managers", default=None, help=
"""Used to specify the path to each doc manager """
"""file that will be used. DocManagers should be """
"""specified in the same order as their respective """
"""target addresses in the --target-urls option. """
"""URLs are assigned to doc managers """
"""respectively. Additional doc managers are """
"""implied to have no target URL. Additional URLs """
"""are implied to have the same doc manager type as """
"""the last doc manager for which a URL was """
"""specified. By default, Mongo Connector will use """
"""'doc_manager_simulator.py'. It is recommended """
"""that all doc manager files be kept in the """
"""doc_managers folder in mongo-connector. For """
"""more information about making your own doc """
"""manager, see 'Writing Your Own DocManager' """
"""section of the wiki""")
#-g is the destination namespace
parser.add_option("-g", "--dest-namespace-set", action="store",
type="string", dest="dest_ns_set", default=None, help=
"""Specify a destination namespace mapping. Each """
"""namespace provided in the --namespace-set option """
"""will be mapped respectively according to this """
"""comma-separated list. These lists must have """
"""equal length. The default is to use the identity """
"""mapping. This is currently only implemented """
"""for mongo-to-mongo connections.""")
#-s is to enable syslog logging.
parser.add_option("-s", "--enable-syslog", action="store_true",
dest="enable_syslog", default=False, help=
"""Used to enable logging to syslog."""
""" Use -l to specify syslog host.""")
#--syslog-host is to specify the syslog host.
parser.add_option("--syslog-host", action="store", type="string",
dest="syslog_host", default="localhost:514", help=
"""Used to specify the syslog host."""
""" The default is 'localhost:514'""")
#--syslog-facility is to specify the syslog facility.
parser.add_option("--syslog-facility", action="store", type="string",
dest="syslog_facility", default="user", help=
"""Used to specify the syslog facility."""
""" The default is 'user'""")
#-i to specify the list of fields to export
parser.add_option("-i", "--fields", action="store", type="string",
dest="fields", default=None, help=
"""Used to specify the list of fields to export. """
"""Specify a field or fields to include in the export. """
"""Use a comma separated list of fields to specify multiple """
"""fields. The '_id', 'ns' and '_ts' fields are always """
"""exported.""")
#--auto-commit-interval to specify auto commit time interval
parser.add_option("--auto-commit-interval", action="store",
dest="commit_interval", type="int",
default=constants.DEFAULT_COMMIT_INTERVAL,
help="""Seconds in-between calls for the Doc Manager"""
""" to commit changes to the target system. A value of"""
""" 0 means to commit after every write operation."""
""" When left unset, Mongo Connector will not make"""
""" explicit commits. Some systems have"""
""" their own mechanism for adjusting a commit"""
""" interval, which should be preferred to this"""
""" option.""")
#-v enables vebose logging
parser.add_option("-v", "--verbose", action="store_true",
dest="verbose", default=False,
help="Sets verbose logging to be on.")
#-w enable logging to a file
parser.add_option("-w", "--logfile", dest="logfile",
help=("Log all output to a file rather than stream to "
"stderr. Omit to stream to stderr."))
(options, args) = parser.parse_args()
logger = logging.getLogger()
loglevel = logging.INFO
if options.verbose:
loglevel = logging.DEBUG
logger.setLevel(loglevel)
if options.enable_syslog and options.logfile:
print ("You cannot specify syslog and a logfile simultaneously, please"
" choose the logging method you would prefer.")
sys.exit(1)
if options.enable_syslog:
syslog_info = options.syslog_host.split(":")
syslog_host = logging.handlers.SysLogHandler(
address=(syslog_info[0], int(syslog_info[1])),
facility=options.syslog_facility
)
syslog_host.setLevel(loglevel)
logger.addHandler(syslog_host)
elif options.logfile is not None:
log_out = logging.FileHandler(options.logfile)
log_out.setLevel(loglevel)
log_out.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(log_out)
else:
log_out = logging.StreamHandler()
log_out.setLevel(loglevel)
log_out.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(log_out)
logger.info('Beginning Mongo Connector')
# Get DocManagers and target URLs
# Each DocManager is assigned the respective (same-index) target URL
# Additional DocManagers may be specified that take no target URL
doc_managers = options.doc_managers
doc_managers = doc_managers.split(",") if doc_managers else doc_managers
target_urls = options.urls.split(",") if options.urls else None
if options.doc_managers is None:
logger.info('No doc managers specified, using simulator.')
if options.ns_set is None:
ns_set = []
else:
ns_set = options.ns_set.split(',')
if options.dest_ns_set is None:
dest_ns_set = ns_set
else:
dest_ns_set = options.dest_ns_set.split(',')
if len(dest_ns_set) != len(ns_set):
logger.error("Destination namespace must be the same length as the "
"origin namespace!")
sys.exit(1)
elif len(set(ns_set)) + len(set(dest_ns_set)) != 2 * len(ns_set):
logger.error("Namespace set and destination namespace set should not "
"contain any duplicates!")
sys.exit(1)
else:
## Create a mapping of source ns to dest ns as a dict
dest_mapping = dict(zip(ns_set, dest_ns_set))
fields = options.fields
if fields is not None:
fields = options.fields.split(',')
key = None
if options.auth_file is not None:
try:
key = open(options.auth_file).read()
re.sub(r'\s', '', key)
except IOError:
logger.error('Could not parse password authentication file!')
sys.exit(1)
if options.password is not None:
key = options.password
if key is None and options.admin_name != "__system":
logger.error("Admin username specified without password!")
sys.exit(1)
if options.commit_interval is not None and options.commit_interval < 0:
raise ValueError("--auto-commit-interval must be non-negative")
connector = Connector(
address=options.main_addr,
oplog_checkpoint=options.oplog_config,
target_url=target_urls,
ns_set=ns_set,
u_key=options.u_key,
auth_key=key,
doc_manager=doc_managers,
auth_username=options.admin_name,
collection_dump=(not options.no_dump),
batch_size=options.batch_size,
fields=fields,
dest_mapping=dest_mapping,
auto_commit_interval=options.commit_interval
)
connector.start()
while True:
try:
time.sleep(3)
if not connector.is_alive():
break
except KeyboardInterrupt:
logging.info("Caught keyboard interrupt, exiting!")
connector.join()
break
if __name__ == '__main__':
main()
|
apache-2.0
| -3,153,926,013,907,341,300
| 42.967832
| 85
| 0.533193
| false
| 4.748074
| true
| false
| false
|
v4hn/ecto
|
test/scripts/test_tendrils.py
|
1
|
2868
|
#!/usr/bin/env python
#
# Copyright (c) 2011, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions 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 the Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import ecto
import ecto.ecto_test as ecto_test
def test_tendrils():
t = ecto.Tendrils()
t.declare("Hello","doc str",6)
assert t.Hello == 6
assert t["Hello"] == 6
t.declare("x","a number", "str")
assert len(t) == 2
assert t["x"] == "str"
assert t.x == "str"
#test the redeclare
try:
t.declare("Hello","new doc", "you")
util.fail()
except ecto.TendrilRedeclaration, e:
print str(e)
assert('TendrilRedeclaration' in str(e))
try:
#read error
t.nonexistant = 1
util.fail()
except ecto.NonExistant, e:
print str(e)
assert "tendril_key nonexistant" in str(e)
try:
#index error
print t["nonexistant"]
util.fail()
except ecto.NonExistant, e:
print str(e)
assert "tendril_key nonexistant" in str(e)
assert len(t.keys()) == 2
assert len(t.values()) == 2
print t
#by value
_x = t.x
_x = 10
assert t.x != 10
x = t.x
t.x = 11
assert x != 11
#by reference
x = t.at("x")
t.x = 13
assert x.val == 13
t.x = 17
assert t.x == 17
t.x = 199
t.x = 15
print t.x
assert t.x == 15
if __name__ == '__main__':
test_tendrils()
|
bsd-3-clause
| 3,189,837,938,713,107,000
| 31.590909
| 77
| 0.656206
| false
| 3.681643
| false
| false
| false
|
lazuxd/teste-admitere-snpap
|
slidingpanel.py
|
1
|
3425
|
# -*- coding: utf-8 -*-
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import OptionProperty, NumericProperty, StringProperty, \
BooleanProperty, ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout
Builder.load_string("""
#: import Window kivy.core.window.Window
<SlidingPanel>
orientation: 'vertical'
size_hint_x: None
width: Window.width - dp(56) if Window.width - dp(56) < dp(320) else dp(320)
x: -1 * self.width if self.side == 'left' else Window.width
<PanelShadow>
canvas:
Color:
rgba: root.color
Rectangle:
size: root.size
""")
class PanelShadow(BoxLayout):
color = ListProperty([0, 0, 0, 0])
class SlidingPanel(BoxLayout):
anim_length_close = NumericProperty(0.3)
anim_length_open = NumericProperty(0.3)
animation_t_open = StringProperty('out_sine')
animation_t_close = StringProperty('out_sine')
side = OptionProperty('left', options=['left', 'right'])
_open = False
def __init__(self, **kwargs):
super(SlidingPanel, self).__init__(**kwargs)
self.width = Window.width - dp(56) if Window.width - dp(56) < dp(320) else dp(320)
self.shadow = PanelShadow()
Clock.schedule_once(lambda x: Window.add_widget(self.shadow,89), 0)
Clock.schedule_once(lambda x: Window.add_widget(self,90), 0)
def toggle(self):
Animation.stop_all(self, 'x')
Animation.stop_all(self.shadow, 'color')
if self._open:
if self.side == 'left':
target_x = -1 * self.width
else:
target_x = Window.width
sh_anim = Animation(duration=self.anim_length_open,
t=self.animation_t_open,
color=[0, 0, 0, 0])
sh_anim.start(self.shadow)
self._get_main_animation(duration=self.anim_length_close,
t=self.animation_t_close,
x=target_x,
is_closing=True).start(self)
self._open = False
else:
if self.side == 'left':
target_x = 0
else:
target_x = Window.width - self.width
Animation(duration=self.anim_length_open, t=self.animation_t_open,
color=[0, 0, 0, 0.5]).start(self.shadow)
self._get_main_animation(duration=self.anim_length_open,
t=self.animation_t_open,
x=target_x,
is_closing=False).start(self)
self._open = True
def _get_main_animation(self, duration, t, x, is_closing):
return Animation(duration=duration, t=t, x=x)
def on_touch_down(self, touch):
# Prevents touch events from propagating to anything below the widget.
super(SlidingPanel, self).on_touch_down(touch)
if self.collide_point(*touch.pos) or self._open:
return True
def on_touch_up(self, touch):
super(SlidingPanel, self).on_touch_up(touch)
if not self.collide_point(touch.x, touch.y) and self._open:
self.toggle()
return True
|
mit
| -6,720,822,278,794,531,000
| 35.827957
| 90
| 0.574015
| false
| 3.767877
| false
| false
| false
|
sophilabs/py101
|
py101/lists/__init__.py
|
1
|
1763
|
""""
Introduction Adventure
Author: Ignacio Avas (iavas@sophilabs.com)
"""
import codecs
import io
import sys
import unittest
from story.adventures import AdventureVerificationError, BaseAdventure
from story.translation import gettext as _
class TestOutput(unittest.TestCase):
"""Variables Adventure test"""
def __init__(self, candidate_code, file_name='<inline>'):
"""Init the test"""
super(TestOutput, self).__init__()
self.candidate_code = candidate_code
self.file_name = file_name
def setUp(self):
self.__old_stdout = sys.stdout
sys.stdout = self.__mockstdout = io.StringIO()
def tearDown(self):
sys.stdout = self.__old_stdout
self.__mockstdout.close()
def runTest(self):
"""Makes a simple test of the output"""
code = compile(self.candidate_code, self.file_name, 'exec', optimize=0)
self.assertIn('languages',
code.co_names,
'Should have defined languages variable')
exec(code)
lines = self.__mockstdout.getvalue().split('\n')
self.assertEqual([str(["ADA", "Pascal", "Fortran", "Smalltalk"]), ''],
lines,
'Should have same output'
)
class Adventure(BaseAdventure):
"""Lists Adventure"""
title = _('Lists')
@classmethod
def test(cls, sourcefile):
"""Test against the provided file"""
suite = unittest.TestSuite()
raw_program = codecs.open(sourcefile).read()
suite.addTest(TestOutput(raw_program, sourcefile))
result = unittest.TextTestRunner().run(suite)
if not result.wasSuccessful():
raise AdventureVerificationError()
|
mit
| 1,598,433,818,799,941,000
| 29.396552
| 79
| 0.601815
| false
| 4.177725
| true
| false
| false
|
ZeitOnline/zeit.push
|
src/zeit/push/browser/mobile.py
|
1
|
1348
|
from zope.cachedescriptors.property import Lazy as cachedproperty
import logging
import sys
import zeit.push.interfaces
import zope.security.proxy
log = logging.getLogger(__name__)
class FindTitle(object):
def __call__(self):
name = self.request.form.get('q')
if not name:
return ''
source = zeit.push.interfaces.PAYLOAD_TEMPLATE_SOURCE.factory
template = source.find(name)
return source.getDefaultTitle(template)
class PreviewPayload(object):
@cachedproperty
def message(self):
# We need to talk to private API
push = zope.security.proxy.getObject(
zeit.push.interfaces.IPushMessages(self.context))
return push._create_message(
'mobile', self.context, push.get(type='mobile'))
@cachedproperty
def rendered(self):
return self.message._render()
def rendered_linenumbers(self):
result = []
for i, line in enumerate(self.rendered.split('\n')):
result.append(u'%03d %s' % (i, line))
return '\n'.join(result)
@cachedproperty
def error(self):
try:
self.message.validate_template(self.rendered)
except Exception, e:
e.traceback = zeit.cms.browser.error.getFormattedException(
sys.exc_info())
return e
|
bsd-3-clause
| 2,564,557,959,152,968,000
| 27.083333
| 71
| 0.626855
| false
| 4.084848
| false
| false
| false
|
grafgustav/accessmail
|
src/Service/ImapReceiver.py
|
1
|
1024
|
__author__ = 'phillip'
from .MailReceiver import MailReceiver
import poplib
class IMAPReceiver(MailReceiver):
def __init__(self, config):
self._conn = None
def connect(self, config):
self._server = poplib.POP3_SSL()
self._server.apop()
def delete_mail(self, n):
self._server.dele(n)
def list_folders(self):
pass
def create_folder(self, name):
pass
def get_number_of_mails(self):
count, size = self._server.stat()
return count
def change_folder(self, path):
pass
def get_header(self, n):
return self._server.top(n,0)
def can_create_folder(self):
return False
def delete_folder(self, name):
pass
def get_total_mails(self):
return self.get_number_of_mails()
def get_mail(self, n):
return self._server.retr(n)
def get_mailbox_size(self):
count, size = self._server.stat()
return size
def quit(self):
self._server.quit()
|
mit
| -1,807,214,119,877,362,200
| 18.711538
| 41
| 0.584961
| false
| 3.605634
| false
| false
| false
|
kurennon/misc-tools
|
find_validator/find_validator.py
|
1
|
1259
|
#!/usr/bin/env python3
DIG_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def find_validator(dig_string, old_base):
dig_sum = sum_digits(dig_string, old_base)
return dig_sum[-1:].upper()
def sum_digits(dig_string, old_base):
int_sum = 0
while dig_string:
int_sum += int(dig_string[:1], base=old_base)
dig_string = dig_string[1:]
dig_sum = unint(int_sum, old_base)
return dig_sum
def unint(int_val, new_base):
if int_val < new_base:
return DIG_CHARS[int_val]
else:
return unint(int_val//new_base, new_base) + DIG_CHARS[int_val%new_base]
if __name__ == "__main__":
print("Welcome to find_validator.py!\nPlease enter an invalid base to quit" +
"\nor q at the validator to choose a new base.")
work_base = 1
while 0 < work_base < 35:
dig_string = ""
work_base = int(input("\nEnter the base of the number(s) you would like to validate: "))
if work_base <= 0 or work_base > 35:
break
while dig_string.lower() != "q":
dig_string = input("Enter a number to validate: ")
if dig_string.lower() == "q":
break
print("The validator is:", find_validator(dig_string, work_base))
|
gpl-3.0
| 3,645,768,671,179,305,500
| 36.029412
| 96
| 0.590151
| false
| 3.375335
| false
| false
| false
|
yggi49/wtforms-polyglot
|
wtf_polyglot/meta.py
|
1
|
2876
|
from __future__ import unicode_literals
try:
from html import escape
from html.parser import HTMLParser
except ImportError:
from cgi import escape
from HTMLParser import HTMLParser
from wtforms.meta import DefaultMeta
from wtforms.widgets.core import HTMLString
class PolyglotHTMLParser(HTMLParser):
"""This simplified ``HTMLParser`` converts its input to polyglot HTML.
It works by making sure that stand-alone tags like ``<input>`` have a
slash before the closing angle bracket, that attribute values are always
quoted, and that boolean attributes have their value set to the attribute
name (e.g., ``checked="checked"``).
Note: boolean attributes are simply identified as attributes with no value
at all. Specifically, an attribute with an empty string (e.g.,
``checked=""``) will *not* be identified as boolean attribute, i.e., there
is no semantic intelligence involved.
>>> parser = PolyglotHTMLParser()
>>> parser.feed('''<input type=checkbox name=foo value=y checked>''')
>>> print(parser.get_output())
<input type="checkbox" name="foo" value="y" checked="checked" />
"""
def __init__(self):
HTMLParser.__init__(self)
self.reset()
self.output = []
def html_params(self, attrs):
output = []
for key, value in attrs:
if value is None:
value = key
output.append(' {}="{}"'.format(key, escape(value, quote=True)))
return ''.join(output)
def handle_starttag(self, tag, attrs):
if tag == 'input':
return self.handle_startendtag(tag, attrs)
self.output.append('<{}{}>'.format(tag, self.html_params(attrs)))
def handle_endtag(self, tag):
self.output.append('</{}>'.format(tag))
def handle_startendtag(self, tag, attrs):
self.output.append('<{}{} />'.format(tag, self.html_params(attrs)))
def handle_data(self, data):
self.output.append(data)
def handle_entityref(self, name):
self.output.append('&{};'.format(name))
def handle_charref(self, name):
self.output.append('&#{};'.format(name))
def get_output(self):
return ''.join(self.output)
class PolyglotMeta(DefaultMeta):
"""
This meta class works exactly like ``DefaultMeta``, except that fields of
forms using this meta class will output polyglot markup.
"""
def render_field(self, field, render_kw):
"""
Render a widget, and convert its output to polyglot HTML.
"""
other_kw = getattr(field, 'render_kw', None)
if other_kw is not None:
render_kw = dict(other_kw, **render_kw)
html = field.widget(field, **render_kw)
parser = PolyglotHTMLParser()
parser.feed(html)
output = HTMLString(parser.get_output())
return output
|
bsd-3-clause
| -4,385,307,373,991,363,000
| 31.681818
| 78
| 0.631085
| false
| 4.050704
| false
| false
| false
|
torchingloom/edx-platform
|
common/lib/xmodule/xmodule/master_class_module.py
|
1
|
15766
|
# -*- coding: utf-8 -*-
"""Word cloud is ungraded xblock used by students to
generate and view word cloud.
On the client side we show:
If student does not yet answered - `num_inputs` numbers of text inputs.
If student have answered - words he entered and cloud.
"""
import json
import logging
import datetime
import csv
import StringIO
from pkg_resources import resource_string
from xmodule.raw_module import EmptyDataRawDescriptor
from xmodule.editing_module import MetadataOnlyEditingDescriptor
from xmodule.x_module import XModule
from django.contrib.auth.models import User
from django.utils.timezone import UTC
from xblock.fields import Scope, Dict, Boolean, List, Integer, String
from xmodule.modulestore import Location
log = logging.getLogger(__name__)
from django.utils.translation import ugettext as _
from django.conf import settings
def pretty_bool(value):
"""Check value for possible `True` value.
Using this function we can manage different type of Boolean value
in xml files.
"""
bool_dict = [True, "True", "true", "T", "t", "1"]
return value in bool_dict
class MasterClassFields(object):
"""XFields for word cloud."""
display_name = String(
display_name=_("Display Name"),
help=_("Display name for this module"),
scope=Scope.settings,
default=_("Master Class")
)
total_places = Integer(
display_name=_("Max places"),
help=_("Number of places available for students to register for masterclass."),
scope=Scope.settings,
default=30,
values={"min": 1}
)
autopass_score = Integer(
display_name=_("Autopass score"),
help=_("Autopass score to automaticly pass registration for masterclass."),
scope=Scope.settings,
default=250,
values={"min": 1}
)
problem_id = String(
display_name=_("Masterclass problem id"),
help=_("Full id of the problem which is to be acomplished to pass registration for masterclass."),
scope=Scope.settings,
#default=_("Master Class") # no default
)
auto_register_if_passed = Boolean(
display_name=_("Auto registration"),
help=_("Auto registration for masterclass if a user passed the test"),
scope=Scope.settings,
default=False,
)
# Fields for descriptor.
submitted = Boolean(
help=_("Whether this student has been register for this master class."),
scope=Scope.user_state,
default=False
)
all_registrations = List(
help=_("All registrations from all students."),
scope=Scope.user_state_summary
)
passed_registrations = List(
help=_("Passed registrations."),
scope=Scope.user_state_summary
)
passed_masterclass_test = Boolean(
help=_("Whether this student has passed the task to register for the masterclass."),
scope=Scope.user_state,
default=False
)
class MasterClassModule(MasterClassFields, XModule):
"""MasterClass Xmodule"""
js = {
'coffee': [resource_string(__name__, 'js/src/javascript_loader.coffee')],
'js': [resource_string(__name__, 'js/src/word_cloud/d3.min.js'),
resource_string(__name__, 'js/src/word_cloud/d3.layout.cloud.js'),
resource_string(__name__, 'js/src/master_class/master_class.js'),
resource_string(__name__, 'js/src/master_class/master_class_main.js')]
}
css = {'scss': [resource_string(__name__, 'css/master_class/display.scss')]}
js_module_name = "MasterClass"
def get_state(self):
"""Return success json answer for client."""
total_register = len(self.passed_registrations)
message = ""
message2 = ""
if self.runtime.user.email in self.passed_registrations:
message = _("You have been registered for this master class. We will provide addition information soon.")
elif self.runtime.user.email in self.all_registrations:
message = _("You are pending for registration for this master class. Please visit this page later for result.")
else:
message2 = _("You have not been registered for this master class. Probably you have to pass a test first or there is not enough places.")
if (total_register is None):
total_register = 0
additional_data = {}
allreg = []
passreg = []
for email in self.all_registrations:
try:
user = User.objects.get(email=email)
allreg += [{'email': email, 'name': user.profile.lastname + ' ' + user.profile.firstname + ' ' + user.profile.middlename}]
except:
pass
for email in self.passed_registrations:
try:
user = User.objects.get(email=email)
passreg += [{'email': email, 'name': user.profile.lastname + ' ' + user.profile.firstname + ' ' + user.profile.middlename}]
except:
pass
if self.runtime.user_is_staff:
additional_data['all_registrations'] = allreg
additional_data['passed_registrations'] = passreg
additional_data['is_staff'] = self.runtime.user_is_staff
additional_data['csv_name'] = self.runtime.course_id + " " + self.display_name
if self.submitted and self.runtime.user.email not in self.all_registrations and self.runtime.user.email not in self.passed_registrations:
self.submitted = False
if self.submitted:
data = {
'status': 'success',
'submitted': True,
'is_closed': self.is_past_due(),
'total_places': self.total_places,
'total_register': total_register,
'message': message,
'problem_id': self.problem_id,
'auto_register_if_passed': self.auto_register_if_passed,
}
data.update(additional_data)
return json.dumps(data)
else:
data = {
'status': 'success',
'submitted': False,
'is_closed': self.is_past_due(),
'total_places': self.total_places,
'total_register': total_register,
'problem_id': self.problem_id,
'message': message2,
'auto_register_if_passed': self.auto_register_if_passed,
}
data.update(additional_data)
return json.dumps(data)
def handle_ajax(self, dispatch, data):
"""Ajax handler.
Args:
dispatch: string request slug
data: dict request get parameters
Returns:
json string
"""
if dispatch == 'submit':
if self.is_past_due():
return json.dumps({
'status': 'fail',
'error': 'Registration is closed due to date.'
})
if self.submitted:
return json.dumps({
'status': 'fail',
'error': 'You have already posted your data.'
})
# Student words from client.
# FIXME: we must use raw JSON, not a post data (multipart/form-data)
master_class = data.getall('master_class[]')
if self.problem_id is None:
self.all_registrations.append(self.runtime.user.email)
self.submitted = True
return self.get_state()
problem_location = Location(self.problem_id)
problem_descriptor = self.runtime.descriptor_runtime.modulestore.get_item(problem_location)
problem_score = self.runtime.get_score(self.runtime.course_id, self.runtime.user, problem_descriptor, self.runtime.get_module)
self.passed_masterclass_test = problem_score is not None and len(problem_score) >= 2 and problem_score[0] >= self.autopass_score
if self.passed_masterclass_test:
if self.auto_register_if_passed:
if len(self.passed_registrations) < self.total_places:
self.passed_registrations.append(self.runtime.user.email)
self.submitted = True
else:
self.all_registrations.append(self.runtime.user.email)
self.submitted = True
return self.get_state()
elif dispatch == 'get_state':
return self.get_state()
elif dispatch == 'register':
logging.error(data)
if self.runtime.user_is_staff:
for email in data.getall('emails[]'):
if (len(self.passed_registrations) < self.total_places):
if (self.all_registrations.count(email) > 0):
self.passed_registrations.append(email)
self.all_registrations.remove(email)
subject = u"Подтверждение регистрации на {masterclass}".format(masterclass=self.display_name)
body = u"Уважаемый(ая) {fullname}!\nВаша заявка на {masterclass} была одобрена. Подробности Вы можете узнать по ссылке: {url}.\nС уважением, Команда ГБОУ ЦПМ.".format(
fullname=User.objects.get(email=email).profile.name,
masterclass=self.display_name,
url='https://' + settings.SITE_NAME + '/courses/' + self.course_id + '/jump_to/{}'.format(Location(self.location))
)
mail = self.runtime.bulkmail.create(self.course_id,
self.runtime.user,
'list',
subject,
body,
location=self.id,
to_list=[email]
)
try:
mail.send()
return self.get_state()
except:
return json.dumps({
'status': 'fail',
'msg': _('Your email can not be sent.')
})
else:
return json.dumps({
'status': 'fail',
'error': _("Not enough places for this master class.")
})
return self.get_state()
else:
return json.dumps({
'status': 'fail',
'error': 'Unknown Command!'
})
elif dispatch == 'unregister':
logging.error(data)
if self.runtime.user_is_staff:
for email in data.getall('emails[]'):
if (self.passed_registrations.count(email) > 0):
self.passed_registrations.remove(email)
self.all_registrations.append(email)
return self.get_state()
else:
return json.dumps({
'status': 'fail',
'error': 'Unknown Command!'
})
elif dispatch == 'remove':
logging.error(data)
if self.runtime.user_is_staff:
for email in data.getall('emails[]'):
if (self.passed_registrations.count(email) > 0):
self.passed_registrations.remove(email)
if (self.all_registrations.count(email) > 0):
self.all_registrations.remove(email)
return self.get_state()
else:
return json.dumps({
'status': 'fail',
'error': 'Unknown Command!'
})
elif dispatch == 'csv':
if self.runtime.user_is_staff:
header = [u'Email', u'Фамилия', u'Имя', u'Отчество',]
datatable = {'header': header, 'students': []}
data = []
for email in self.passed_registrations:
datarow = []
user = User.objects.get(email=email)
datarow += [user.email, user.profile.lastname, user.profile.firstname, user.profile.middlename]
data += [datarow]
datatable['data'] = data
return self.return_csv(" ", datatable, encoding="cp1251", dialect="excel-tab")
else:
return json.dumps({
'status': 'fail',
'error': 'Unknown Command!'
})
elif dispatch == 'email':
subject = data.get('subject')
body = data.get('body')
mail = self.runtime.bulkmail.create(self.course_id, self.runtime.user, 'list', subject, body, location=self.id, to_list=self.passed_registrations)
mail.send()
return json.dumps({
'status': 'success',
'msg': _('Your email was successfully queued for sending.')
})
else:
return json.dumps({
'status': 'fail',
'error': 'Unknown Command!'
})
def is_past_due(self):
"""
Is it now past this problem's due date, including grace period?
"""
return (self.due is not None and
datetime.datetime.now(UTC()) > self.due)
def get_html(self):
"""Template rendering."""
logging.info(type(self.location))
logging.info(self.get_progress())
logging.info(self.runtime.seed)
logging.info(self.runtime.anonymous_student_id)
logging.info(self.runtime)
context = {
'display_name': self.display_name,
'due': self.due,
'element_id': self.location.html_id(),
'element_class': self.location.category,
'ajax_url': self.system.ajax_url,
'submitted': self.submitted,
'is_staff': self.runtime.user_is_staff,
'all_registrations': self.all_registrations,
'passed_registrations': self.passed_registrations
}
self.content = self.system.render_template('master_class.html', context)
return self.content
def return_csv(self, func, datatable, file_pointer=None, encoding="utf-8", dialect="excel"):
"""Outputs a CSV file from the contents of a datatable."""
if file_pointer is None:
response = StringIO.StringIO()
else:
response = file_pointer
writer = csv.writer(response, dialect=dialect, quotechar='"', quoting=csv.QUOTE_ALL)
encoded_row = [unicode(s).encode(encoding) for s in datatable['header']]
writer.writerow(encoded_row)
for datarow in datatable['data']:
encoded_row = [unicode(s).encode(encoding) for s in datarow]
writer.writerow(encoded_row)
if file_pointer is None:
return response.getvalue()
else:
return response
class MasterClassDescriptor(MasterClassFields, MetadataOnlyEditingDescriptor, EmptyDataRawDescriptor):
"""Descriptor for MasterClass Xmodule."""
module_class = MasterClassModule
template_dir_name = 'master_class'
|
agpl-3.0
| -7,321,570,871,203,777,000
| 39.703125
| 195
| 0.540179
| false
| 4.418999
| false
| false
| false
|
googleapis/googleapis-gen
|
google/cloud/aiplatform/v1/aiplatform-v1-py/google/cloud/aiplatform_v1/services/pipeline_service/transports/grpc_asyncio.py
|
1
|
18872
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or 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.
#
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import gapic_v1 # type: ignore
from google.api_core import grpc_helpers_async # type: ignore
from google.api_core import operations_v1 # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import packaging.version
import grpc # type: ignore
from grpc.experimental import aio # type: ignore
from google.cloud.aiplatform_v1.types import pipeline_service
from google.cloud.aiplatform_v1.types import training_pipeline
from google.cloud.aiplatform_v1.types import training_pipeline as gca_training_pipeline
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
from .base import PipelineServiceTransport, DEFAULT_CLIENT_INFO
from .grpc import PipelineServiceGrpcTransport
class PipelineServiceGrpcAsyncIOTransport(PipelineServiceTransport):
"""gRPC AsyncIO backend transport for PipelineService.
A service for creating and managing Vertex AI's pipelines. This
includes both ``TrainingPipeline`` resources (used for AutoML and
custom training) and ``PipelineJob`` resources (used for Vertex
Pipelines).
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
_grpc_channel: aio.Channel
_stubs: Dict[str, Callable] = {}
@classmethod
def create_channel(cls,
host: str = 'aiplatform.googleapis.com',
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs) -> aio.Channel:
"""Create and return a gRPC AsyncIO channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
aio.Channel: A gRPC AsyncIO channel object.
"""
return grpc_helpers_async.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs
)
def __init__(self, *,
host: str = 'aiplatform.googleapis.com',
credentials: ga_credentials.Credentials = None,
credentials_file: Optional[str] = None,
scopes: Optional[Sequence[str]] = None,
channel: aio.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id=None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
channel (Optional[aio.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
self._operations_client = None
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
# Ignore credentials if a channel was passed.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
)
if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
self._host,
credentials=self._credentials,
credentials_file=credentials_file,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Wrap messages. This must be done after self._grpc_channel exists
self._prep_wrapped_messages(client_info)
@property
def grpc_channel(self) -> aio.Channel:
"""Create the channel designed to connect to this service.
This property caches on the instance; repeated calls return
the same channel.
"""
# Return the channel from cache.
return self._grpc_channel
@property
def operations_client(self) -> operations_v1.OperationsAsyncClient:
"""Create the client designed to process long-running operations.
This property caches on the instance; repeated calls return the same
client.
"""
# Sanity check: Only create a new client if we do not already have one.
if self._operations_client is None:
self._operations_client = operations_v1.OperationsAsyncClient(
self.grpc_channel
)
# Return the client from cache.
return self._operations_client
@property
def create_training_pipeline(self) -> Callable[
[pipeline_service.CreateTrainingPipelineRequest],
Awaitable[gca_training_pipeline.TrainingPipeline]]:
r"""Return a callable for the create training pipeline method over gRPC.
Creates a TrainingPipeline. A created
TrainingPipeline right away will be attempted to be run.
Returns:
Callable[[~.CreateTrainingPipelineRequest],
Awaitable[~.TrainingPipeline]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'create_training_pipeline' not in self._stubs:
self._stubs['create_training_pipeline'] = self.grpc_channel.unary_unary(
'/google.cloud.aiplatform.v1.PipelineService/CreateTrainingPipeline',
request_serializer=pipeline_service.CreateTrainingPipelineRequest.serialize,
response_deserializer=gca_training_pipeline.TrainingPipeline.deserialize,
)
return self._stubs['create_training_pipeline']
@property
def get_training_pipeline(self) -> Callable[
[pipeline_service.GetTrainingPipelineRequest],
Awaitable[training_pipeline.TrainingPipeline]]:
r"""Return a callable for the get training pipeline method over gRPC.
Gets a TrainingPipeline.
Returns:
Callable[[~.GetTrainingPipelineRequest],
Awaitable[~.TrainingPipeline]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'get_training_pipeline' not in self._stubs:
self._stubs['get_training_pipeline'] = self.grpc_channel.unary_unary(
'/google.cloud.aiplatform.v1.PipelineService/GetTrainingPipeline',
request_serializer=pipeline_service.GetTrainingPipelineRequest.serialize,
response_deserializer=training_pipeline.TrainingPipeline.deserialize,
)
return self._stubs['get_training_pipeline']
@property
def list_training_pipelines(self) -> Callable[
[pipeline_service.ListTrainingPipelinesRequest],
Awaitable[pipeline_service.ListTrainingPipelinesResponse]]:
r"""Return a callable for the list training pipelines method over gRPC.
Lists TrainingPipelines in a Location.
Returns:
Callable[[~.ListTrainingPipelinesRequest],
Awaitable[~.ListTrainingPipelinesResponse]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'list_training_pipelines' not in self._stubs:
self._stubs['list_training_pipelines'] = self.grpc_channel.unary_unary(
'/google.cloud.aiplatform.v1.PipelineService/ListTrainingPipelines',
request_serializer=pipeline_service.ListTrainingPipelinesRequest.serialize,
response_deserializer=pipeline_service.ListTrainingPipelinesResponse.deserialize,
)
return self._stubs['list_training_pipelines']
@property
def delete_training_pipeline(self) -> Callable[
[pipeline_service.DeleteTrainingPipelineRequest],
Awaitable[operations_pb2.Operation]]:
r"""Return a callable for the delete training pipeline method over gRPC.
Deletes a TrainingPipeline.
Returns:
Callable[[~.DeleteTrainingPipelineRequest],
Awaitable[~.Operation]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'delete_training_pipeline' not in self._stubs:
self._stubs['delete_training_pipeline'] = self.grpc_channel.unary_unary(
'/google.cloud.aiplatform.v1.PipelineService/DeleteTrainingPipeline',
request_serializer=pipeline_service.DeleteTrainingPipelineRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs['delete_training_pipeline']
@property
def cancel_training_pipeline(self) -> Callable[
[pipeline_service.CancelTrainingPipelineRequest],
Awaitable[empty_pb2.Empty]]:
r"""Return a callable for the cancel training pipeline method over gRPC.
Cancels a TrainingPipeline. Starts asynchronous cancellation on
the TrainingPipeline. The server makes a best effort to cancel
the pipeline, but success is not guaranteed. Clients can use
[PipelineService.GetTrainingPipeline][google.cloud.aiplatform.v1.PipelineService.GetTrainingPipeline]
or other methods to check whether the cancellation succeeded or
whether the pipeline completed despite cancellation. On
successful cancellation, the TrainingPipeline is not deleted;
instead it becomes a pipeline with a
[TrainingPipeline.error][google.cloud.aiplatform.v1.TrainingPipeline.error]
value with a [google.rpc.Status.code][google.rpc.Status.code] of
1, corresponding to ``Code.CANCELLED``, and
[TrainingPipeline.state][google.cloud.aiplatform.v1.TrainingPipeline.state]
is set to ``CANCELLED``.
Returns:
Callable[[~.CancelTrainingPipelineRequest],
Awaitable[~.Empty]]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if 'cancel_training_pipeline' not in self._stubs:
self._stubs['cancel_training_pipeline'] = self.grpc_channel.unary_unary(
'/google.cloud.aiplatform.v1.PipelineService/CancelTrainingPipeline',
request_serializer=pipeline_service.CancelTrainingPipelineRequest.serialize,
response_deserializer=empty_pb2.Empty.FromString,
)
return self._stubs['cancel_training_pipeline']
__all__ = (
'PipelineServiceGrpcAsyncIOTransport',
)
|
apache-2.0
| 227,159,472,070,711,040
| 46.417085
| 109
| 0.632524
| false
| 4.751259
| false
| false
| false
|
puttarajubr/commcare-hq
|
custom/ilsgateway/tests/test_locations_sync.py
|
1
|
4004
|
from datetime import datetime
import json
import os
from django.test import TestCase
from corehq.apps.commtrack.models import CommtrackConfig
from corehq.apps.commtrack.tests.util import bootstrap_domain as initial_bootstrap
from corehq.apps.locations.models import Location, SQLLocation
from custom.ilsgateway.api import Location as Loc, ILSGatewayAPI
from custom.ilsgateway.tests.mock_endpoint import MockEndpoint
from custom.logistics.api import ApiSyncObject
from custom.logistics.commtrack import synchronization
from custom.logistics.models import MigrationCheckpoint
TEST_DOMAIN = 'ilsgateway-commtrack-locations-test'
class LocationSyncTest(TestCase):
def setUp(self):
self.endpoint = MockEndpoint('http://test-api.com/', 'dummy', 'dummy')
self.api_object = ILSGatewayAPI(TEST_DOMAIN, self.endpoint)
self.datapath = os.path.join(os.path.dirname(__file__), 'data')
domain = initial_bootstrap(TEST_DOMAIN)
CommtrackConfig(domain=domain.name).save()
self.api_object.prepare_commtrack_config()
for location in Location.by_domain(TEST_DOMAIN):
location.delete()
def test_create_facility_location(self):
with open(os.path.join(self.datapath, 'sample_locations.json')) as f:
location = Loc(**json.loads(f.read())[0])
ilsgateway_location = self.api_object.location_sync(location)
self.assertEqual(ilsgateway_location.name, location.name)
self.assertEqual(ilsgateway_location.location_type, location.type)
self.assertEqual(ilsgateway_location.longitude, float(location.longitude))
self.assertEqual(ilsgateway_location.latitude, float(location.latitude))
self.assertEqual(int(ilsgateway_location.parent.sql_location.external_id), location.parent_id)
self.assertIsNotNone(ilsgateway_location.linked_supply_point())
self.assertIsNotNone(ilsgateway_location.sql_location.supply_point_id)
def test_create_non_facility_location(self):
with open(os.path.join(self.datapath, 'sample_locations.json')) as f:
location = Loc(**json.loads(f.read())[1])
ilsgateway_location = self.api_object.location_sync(location)
self.assertEqual(ilsgateway_location.name, location.name)
self.assertEqual(ilsgateway_location.location_type, location.type)
self.assertEqual(ilsgateway_location.longitude, float(location.longitude))
self.assertEqual(ilsgateway_location.latitude, float(location.latitude))
self.assertIsNone(ilsgateway_location.parent)
self.assertIsNone(ilsgateway_location.linked_supply_point())
self.assertIsNone(ilsgateway_location.sql_location.supply_point_id)
def test_locations_migration(self):
checkpoint = MigrationCheckpoint(
domain=TEST_DOMAIN,
start_date=datetime.utcnow(),
date=datetime.utcnow(),
api='product',
limit=100,
offset=0
)
location_api = ApiSyncObject(
'location_facility',
self.endpoint.get_locations,
self.api_object.location_sync,
filters=dict(type='facility')
)
synchronization(location_api, checkpoint, None, 100, 0)
self.assertEqual('location_facility', checkpoint.api)
self.assertEqual(100, checkpoint.limit)
self.assertEqual(0, checkpoint.offset)
self.assertEqual(5, len(list(Location.by_domain(TEST_DOMAIN))))
self.assertEqual(5, SQLLocation.objects.filter(domain=TEST_DOMAIN).count())
sql_location = SQLLocation.objects.get(domain=TEST_DOMAIN, site_code='DM520053')
self.assertEqual('FACILITY', sql_location.location_type.name)
self.assertIsNotNone(sql_location.supply_point_id)
sql_location2 = SQLLocation.objects.get(domain=TEST_DOMAIN, site_code='region-dodoma')
self.assertEqual('REGION', sql_location2.location_type.name)
self.assertIsNone(sql_location2.supply_point_id)
|
bsd-3-clause
| 6,287,786,364,255,786,000
| 47.829268
| 102
| 0.709041
| false
| 3.894942
| true
| false
| false
|
davidvg/google_api
|
google_api/gmail_api.py
|
1
|
13120
|
'''
Basic Python3 implementation of some functionality of the Gmail API.
Based on the code from the Gmail API documentation.
Requires a 'secret file' to allow authentication (see [1])
Installation
-----------
In Python3, install the API using pip3:
pip3 install --upgrade google-api-python-client
Install packages:
python3 setup.py develop
[1] https://developers.google.com/gmail/api/quickstart/python
'''
import httplib2
import os.path
import base64
import email
import time
import datetime as dt
from googleapiclient import discovery
from googleapiclient.http import BatchHttpRequest as batchRequest
from oauth2client import file, client, tools
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail_api-python.json
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = '../client_secret.json'
APPLICATION_NAME = 'Gmail API downloader'
class Client(object):
def __init__(self, scopes_=SCOPES, secret_=CLIENT_SECRET_FILE):
'''
Initialize the class' variables
'''
# Internals
self.__scopes = scopes_
self.__secret = secret_
self.service = None
# Members
self.msg_ids = []
self.raw_messages = []
self.messages = []
self.__format = None
# Path for storing credentials
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail_api-python.json')
store = file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(self.__secret, self.__scopes)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
# Build the service
http = credentials.authorize(httplib2.Http())
self.service = discovery.build('gmail', 'v1', http=http)
def __parse_id(self, id_):
'''
Parses an id when passed to a function, to make sure it works for
every method.
Seems redundant with Client.get_id() when called on a message.
'''
if isinstance(id_, dict):
return id_['id']
elif isinstance(id_, str):
return id_
else:
# Is it a message?
try:
id_ = id_['id']
except:
print(' >>>> __parse_id(): No valid message id.')
return None
def get_msg_ids_from_labels(self, labels):
'''
'''
# Clear previous msg_ids
self.msg_ids = []
response = self.service.users().messages().list(userId='me',
labelIds=labels
).execute()
# First page of results
if 'messages' in response:
self.msg_ids.extend(response['messages'])
# Check if there are more result pages
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = self.service.users().messages().list(
userId='me',
labelIds=labels,
pageToken = page_token
).execute()
self.msg_ids.extend(response['messages'])
def get_msg_ids_from_query(self, query):
# Clear previous msg_ids
self.msg_ids = []
response = self.service.users().messages().list(userId='me',
q=query,
).execute()
# First page of results
if 'messages' in response:
self.msg_ids.extend(response['messages'])
# Check if there are more result pages
while 'nextPageToken' in response:
page_token = response['nextPageToken']
response = self.service.users().messages().list(
userId='me',
q=query,
pageToken = page_token
).execute()
self.msg_ids.extend(response['messages'])
def get_batch_messages(self, msg_ids, format='full'):
'''
Download a group of messages, given its ids.
Arguments:
- msg_ids: a list of message ids as returned by the API.
- format: the format for the downloaded message: 'full', 'raw',
'metadata', 'minimal'
Returns:
- A list with the messages.
'''
# Store current format
self.__format__ = format
messages = []
def callback_(req_id, resp, exception):
if exception:
print(' >>> CallbackException')
pass
else:
messages.append(resp)
def batch_request():
batch = self.service.new_batch_http_request(callback_)
ids_ = [elem['id'] for elem in msg_ids]
for id_ in ids_:
batch.add(self.service.users().messages().get(userId='me',
id=id_,
format=format))
batch.execute()
if len(self.msg_ids) < 1000:
batch_request()
else:
# To Do: implement the case for 1000+ messages
pass
self.raw_messages = messages
def get_message(self, msg_id, format='full'):
# Store current format
self.__format__ = format
# Check type of msg_id argument
msg_id = self.__parse_id(msg_id)
# Get messages
res = self.service.users().messages().get(userId='me',
id=msg_id,
format=format).execute()
return res
def get_messages(self, msg_ids=None, labels=None, query=None, format='full'):
# Store current format
self.__format__ = format
# Get the id for messages corresponding to labels/query
if msg_ids:
self.msg_ids = msg_ids
elif labels:
self.get_msg_ids_from_labels(labels=labels)
elif query:
self.get_msg_ids_from_query(query=query)
else:
print(' >>> get_messages(): No labels or query passed. Nothing is done.')
# Download the messages
self.get_batch_messages(self.msg_ids, format=format)
### Parsing and decoding the messages
'''
Message structure for the different formats
* Full
----
- snippet
- internalDate: ms from Epoch
- id
- payload
- filename
- headers: list of 26 dicts with keys {'name', 'value'}
- Received: date (multiple occurences ?)
- MIME-Version
- Content-Type: text/html, charset
- From
- Subject
- ...
- mimeType: text/html, ...
- parts
- body: dict
- data: base64
- size: int
- sizeEstimate
- historyId
- labelIds: list of labels
- threadId
* Raw
---
- threadId
- snippet
- historyId
- internalDate
- id
- raw: base64
- labelIds
- sizeEstimate
* Metadata: dict with 8 dicts
--------
- threadId
- snippet
- historyId
- inernalDate
- id
- labelIds
- payload: dict
- mimeType: text/html, ...
- headers
- sizeEstimate
* Minimal
-------
- historyId
- id
- labelIds
- sizeEstimate
- snippet
- threadId
'''
def get_id(self, message):
'''
Returns the message id for a single raw message.
'''
return str(message['id'])
def get_labels(self, message):
'''
Returns a list of labels for a single raw message.
'''
return message['labelIds']
def modify_labels(self, obj, add=[], remove=[]):
"""
Adds or removes labels from a message.
"""
id_ = self.__parse_id(obj)
self.service.users().messages().modify(
userId='me',
id=id_,
body={'addLabelIds': add,
'removeLabelIds': remove}).execute()
def is_unread(self, message):
# Check if the message is already been decoded
return 'UNREAD' in message['labels']
def mark_as_read(self, obj):
id_ = self.__parse_id(obj)
self.modify_labels(id_, remove=['UNREAD'])
def get_date(self, message):
''' Returns the reception date for a single raw message in a string
using strftime.
'''
internal = float(message['internalDate'])/1000. # seconds from Epoch
date = time.gmtime(internal)
res = dt.datetime(year=date.tm_year,
month=date.tm_mon,
day=date.tm_mday,
hour=date.tm_hour,
minute=date.tm_min,
second=date.tm_sec)
return res.strftime('%Y-%m-%dT%H:%M:%S')
def get_subject(self, message):
headers = message['payload']['headers']
for h in headers:
if h['name'] == 'Subject':
return h['value']
return None
def get_body(self, message):
if self.__format__ is 'full':
payload = message['payload']
if not 'parts' in payload:
raw = payload['body']['data']
else:
### CHECK THIS!!
raw = payload['parts'][0]['body']['data']
body = base64.urlsafe_b64decode(raw.encode('ASCII'))
elif self.__format__ is 'raw':
raw = message['raw']
raw = base64.urlsafe_b64decode(raw.encode('ASCII'))
mime = email.message_from_bytes(raw)
body = mime.get_payload(decode=True)
return body
def decode_messages(self, keys=None):
'''
For 'full' and 'raw' formats; 'minimal' and 'metadata' have no message
body.
Takes messages stored in Client.raw_messages and extracts info from them.
The result is stored in Client.messages
'''
self.messages = []
for msg in self.raw_messages:
decoded = {}
if not keys:
keys = ['id', 'date', 'snippet', 'body', 'labels', 'subject',
'headers']
for key in keys:
decoded[key] = None
decoded['id'] = self.get_id(msg)
decoded['date'] = self.get_date(msg)
decoded['labels'] = self.get_labels(msg)
decoded['snippet'] = msg['snippet']
if self.__format__ is 'full':
decoded['body'] = self.get_body(msg)
decoded['subject'] = self.get_subject(msg)
decoded['headers'] = msg['payload']['headers']
elif self.__format__ is 'raw':
decoded['body'] = self.get_body(msg)
pass
elif self.__format__ is 'metadata':
# At the moment it returns the payload dictionary
decoded['headers'] = msg['payload']['headers']
elif self.__format__ is 'minimal':
pass
self.messages.append(decoded)
def write(self, message, use='date', to='html'):
"""
Write the body of the message to a file.
- use: which key use to generate name (currently only 'date')
- to: file extension
"""
if use is 'date':
name = message[use]
else:
pass
out = '%s.%s' % (name, to)
if self.__format__ is 'full' or self.__format__ is 'raw':
body = message['body'].decode('utf-8')
with open(out, 'w') as f:
f.write(body)
else:
print(' >>> Client.write(): no body to write (format = %s)'
% self.__format__)
def main():
pass
if __name__ == '__main__':
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
gm = Client()
gm.get_msg_ids_from_labels('Label_59')
ids = gm.msg_ids[:2]
gm.get_messages(msg_ids=ids, format='full')
gm.decode_messages()
m = gm.messages[0]
gm.write(m, to='txt')
|
mit
| -5,331,380,682,368,593,000
| 32.384224
| 88
| 0.509604
| false
| 4.462585
| false
| false
| false
|
Lax/Packages
|
ganglia-gmond-modules-python-plugins/usr/lib64/ganglia/python_modules/sockstat.py
|
1
|
2803
|
# sockstat module for ganglia 3.1.x and above
# Copyright (C) Wang Jian <lark@linux.net.cn>, 2009
import os, sys
import time
last_poll_time = 0
sockstats = {
'tcp_total': 0,
'tcp_established': 0,
'tcp_orphan': 0,
'tcp_timewait': 0,
'udp_total': 0 }
def metric_update():
global sockstats
f = open('/proc/net/sockstat', 'r')
for l in f:
line = l.split()
if (line[0] == 'TCP:'):
sockstats['tcp_total'] = int(line[2])
sockstats['tcp_orphan'] = int(line[4])
sockstats['tcp_established'] = int(line[2]) - int(line[4])
sockstats['tcp_timewait'] = int(line[6])
continue
if (line[0] == 'UDP:'):
sockstats['udp_total'] = int(line[2])
continue
f.close()
def metric_read(name):
global last_poll_time
global sockstats
now_time = time.time()
'''time skewed'''
if now_time < last_poll_time:
last_poll_time = now_time
return 0
'''we cache statistics for 2 sec, it's enough for polling all 3 counters'''
if (now_time - last_poll_time) > 2:
metric_update()
last_poll_time = now_time
return sockstats[name]
descriptors = [{
'name': 'tcp_total',
'call_back': metric_read,
'time_max': 20,
'value_type': 'uint',
'units': 'Sockets',
'slope': 'both',
'format': '%u',
'description': 'Total TCP sockets',
'groups': 'network',
},
{
'name': 'tcp_established',
'call_back': metric_read,
'time_max': 20,
'value_type': 'uint',
'units': 'Sockets',
'slope': 'both',
'format': '%u',
'description': 'TCP established sockets',
'groups': 'network',
},
{
'name': 'tcp_timewait',
'call_back': metric_read,
'time_max': 20,
'value_type': 'uint',
'units': 'Sockets',
'slope': 'both',
'format': '%u',
'description': 'TCP timewait sockets',
'groups': 'network',
},
{
'name': 'udp_total',
'call_back': metric_read,
'time_max': 20,
'value_type': 'uint',
'units': 'Sockets',
'slope': 'both',
'format': '%u',
'description': 'Total UDP sockets',
'groups': 'network',
}]
def metric_init(params):
return descriptors
def metric_cleanup():
pass
# for unit testing
if __name__ == '__main__':
metric_init(None)
for d in descriptors:
v = d['call_back'](d['name'])
print '%s = %d' % (d['name'], v)
print "----"
while 1:
time.sleep(1)
for d in descriptors:
v = d['call_back'](d['name'])
print '%s = %d' % (d['name'], v)
print "----"
|
gpl-3.0
| -1,002,256,754,032,724,500
| 23.163793
| 79
| 0.49447
| false
| 3.393462
| false
| false
| false
|
paolomonella/ursus
|
xmlToolBox/minidomToolBox.py
|
1
|
7687
|
#! /usr/bin/env python
# This is a toolbox I'm using to look for specific things in the XML DOM
##################
# Import modules #
##################
from __future__ import print_function
from xml.dom.minidom import parse, parseString
#import xml.dom.minidom
#################
# Parse the XML #
#################
xmldoc=parse('/home/ilbuonme/siti/paolo.monella/ursus/casanatensis.xml')
###########
# Methods #
###########
def checkIDs():
"""
This function checks whether there are duplicated or
non-sequential xml:id's for <w> elements.
"""
wordElementList = xmldoc.getElementsByTagName('ref')
prevIdN = 0
for r in wordElementList:
#print('cRef: '+r.attributes.getNamedItem('cRef').nodeValue)
for c in r.childNodes:
if c.nodeType == c.ELEMENT_NODE and c.tagName == 'w':
#print(c.attributes.getNamedItem('xml:id').nodeValue, end=', ')
myId = c.attributes.getNamedItem('xml:id').nodeValue
myIdN = int(myId[1:])
#print(myIdN, end=', ')
if not myIdN > prevIdN:
print('Trouble! Not greater...')
#print(myIdN, 'is greater than ', prevIdN)
if myIdN == prevIdN:
print('Trouble! Equal')
def searchPcChildrenOfUnclear():
"""
Print all <pc> elments that are children of <unclear>.
"""
wordElementList = xmldoc.getElementsByTagName('ref')
x = False
for r in wordElementList:
#print('cRef: '+r.attributes.getNamedItem('cRef').nodeValue)
for c in r.childNodes:
if c.nodeType == c.ELEMENT_NODE:
if c.tagName == 'w' and x:
print(c.attributes.getNamedItem('xml:id').nodeValue, end=' viene dopo ')
x = False
if c.tagName == 'unclear':
for w in c.childNodes:
#print(x, end=', ')
if w.nodeType == w.ELEMENT_NODE and w.tagName == 'pc':
print('Eureka!')
print(w.attributes.getNamedItem('n').nodeValue)
x = True
def searchTextNodesChildrenOfUnclear():
"""
Print all textNodes that are children of <unclear>.
"""
wordElementList = xmldoc.getElementsByTagName('ref')
for r in wordElementList:
#print('cRef: '+r.attributes.getNamedItem('cRef').nodeValue)
for c in r.childNodes:
if c.nodeType == c.ELEMENT_NODE:
if c.tagName == 'unclear':
for w in c.childNodes:
if w.nodeType == w.ELEMENT_NODE and w.tagName != 'w':
#print(w.attributes.getNamedItem('n').nodeValue)
print(w.tagName)
if w.nodeType != w.ELEMENT_NODE and w.nodeValue != '\n' and w.nodeValue != '\n\t':
print('"'+w.nodeValue+'"\n---\n')
def listChildrenOfAnElement(elemName):
"""
Return a list of elements that are direct children of the
element with tag name elemName (e.g. 'w' or 'ref').
"""
wordElementList = xmldoc.getElementsByTagName(elemName)
cs=[]
for e in wordElementList:
for c in e.childNodes:
if c.nodeType == c.ELEMENT_NODE:
cs.append(c.tagName)
return(set(cs))
def searchAttrib(elemName):
"""
Check attributes of an element
"""
L = []
wordElementList = xmldoc.getElementsByTagName(elemName)
for e in wordElementList:
if e.attributes.getNamedItem('type'):
n = e.attributes.getNamedItem('type').nodeValue
if n == 'emendation':
if not e.attributes.getNamedItem('cert'):
L.append(e.attributes.getNamedItem('subtype').nodeValue)
#L.append(e.attributes.getNamedItem('subtype').nodeValue)
for l in set(L):
print(l)
def listDescendantsOfElement(myElement):
ds=[]
elementList = xmldoc.getElementsByTagName(myElement)
for w in elementList:
d = w.getElementsByTagName('*')
for x in d:
#if x.nodeType == x.ELEMENT_NODE and x.tagName != 'note':
if x.nodeType == x.ELEMENT_NODE:
ds.append(x.tagName)
for y in set(ds):
print(y)
def graphemeLint():
"""
This function checks that all graphemes encoded directly within
<w> elements (or within those of its descendant element that are
supposed to include graphemes) are actually declared in the
Graphemic Table of Signs. If they are not declared, it prints
an 'Alas!' message.
"""
# Import the graphemes in column 'Grapheme' of GToS.csv into list 'gl'
gl = []
with open('/home/ilbuonme/siti/paolo.monella/ursus/GToS.csv') as gtosFile:
lineCount=0
for l in gtosFile:
if lineCount>0: # I'm skipping the first line (which has the column headers)
gl.append(l[0])
lineCount += 1
# Possible descendants of <w>
allowedElem=['lb', 'pc', 'am', 'choice', 'note', 'expan', 'add', 'hi', 'abbr', 'gap']
noGraphemeContent=['lb', 'pc', 'gap', 'note', 'expan', 'choice'] # <expan> has alphabemes, not graphemes, as content
graphemeContent=['am', 'hi']
# Check the descendants of <w> (elements and textNodes)
elementList = xmldoc.getElementsByTagName('w')
for w in elementList:
g = '' # This is a string including all graphemes in the <w> element
for c in w.childNodes:
if c.nodeType != c.ELEMENT_NODE: # With this we harvest all text nodes directly children of <w>
g = g + c.nodeValue
for x in w.getElementsByTagName('*'):
if x.tagName not in allowedElem:
print('<' + x.tagName + '> is not allowed as a descendant of <w>')
elif x.tagName in graphemeContent: # These elements only have one textNode child, with graphemes
g = g + x.firstChild.nodeValue
elif x.tagName == 'abbr': # Its children can be <am> or <hi> (already taken care of), or textNode
for y in x.childNodes:
if y.nodeType != y.ELEMENT_NODE: # textNode child
g = g + y.nodeValue
else: # element child: the only case as of 2017-03-16 is a <choice> child, so
# no need to worry about this, because its children <abbr>, <expan>
# and <am> are already taken care of
pass
elif x.tagName == 'add': # Its children can be <w> or textNode
for y in x.childNodes:
if y.nodeType != y.ELEMENT_NODE: # textNode child
g = g + y.nodeValue
else: # element child: the only case as of 2017-03-16 is a <choice> child, so
# no need to worry about this, because its children <abbr>, <expan>
# and <am> are already taken care of
pass
for gx in g: # For each character in the graphematic content of <w>
if (gx not in gl) and (gx not in ['\n', '\t']): # If it's not in the GToS (and it's not a tab or newline)
print('Alas! Character "'+gx+'" is not in the Graphemic Table of Signs')
##################
# Call functions #
##################
# List children of <w>
# for x in listChildrenOfAnElement('w'): print(x, end=', ')
# print()
# List descendants of <w>
#graphemeLint()
#listDescendantsOfElement('choice')
searchAttrib('note')
|
gpl-2.0
| 6,549,222,712,097,434,000
| 38.420513
| 120
| 0.552751
| false
| 3.894124
| false
| false
| false
|
niallrmurphy/pyvern
|
test_tree.py
|
1
|
20890
|
#!/usr/bin/env python
# encoding: utf-8
# Niall Richard Murphy <niallm@gmail.com>
"""Test the tree (gap-production) object."""
import sys
import constants
import random
import tree
# Perhaps unittest2 is available. Try to import it, for
# those cases where we are running python 2.7.
try:
import unittest2 as unittest
except ImportError:
import unittest
class NodeTest(unittest.TestCase):
def setUp(self):
self.n = tree.Node(supplied_data = "Test")
self.n2 = tree.Node(supplied_data = "Test2")
self.n3 = tree.Node(supplied_data = "Test3")
self.n4 = tree.Node(supplied_data = "Test4")
self.n5 = tree.Node(supplied_data = "Test5")
def test_node_get_used(self):
self.failUnless(self.n.used == False)
def test_node_set_used(self):
self.n.used = True
self.failUnless(self.n.used == True)
def test_node_get_data(self):
self.failUnless(self.n.GetData() == "Test")
def test_node_set_data(self):
self.n.SetData("Wobble")
self.failUnless(self.n.GetData() == "Wobble")
def test_node_getset_left(self):
self.n.SetLeft(self.n2)
self.failUnless(self.n.GetLeft() == self.n2)
def test_node_getset_right(self):
self.n.SetRight(self.n2)
self.failUnless(self.n.GetRight() == self.n2)
def test_node_getset_parent(self):
self.n.SetLeft(self.n2)
self.n2.SetParent(self.n)
self.n.SetRight(self.n3)
self.n3.SetParent(self.n)
self.failUnless(self.n2.GetParent() == self.n)
self.failUnless(self.n3.GetParent() == self.n)
def test_node_getset_level(self):
self.assertEqual(self.n.GetLevel(), 0)
self.n2.SetParent(self.n)
self.n.SetLeft(self.n2)
self.assertEqual(self.n2.GetLevel(), 1)
self.n2.SetLeft(self.n3)
self.n3.SetParent(self.n2)
self.assertEqual(self.n3.GetLevel(), 2)
def test_node_getset_leftright(self):
self.n.SetLeft(self.n2)
self.n2.SetParent(self.n)
self.n.SetRight(self.n3)
self.n3.SetParent(self.n)
self.assertEqual(self.n2.AmLeft(), True)
self.assertEqual(self.n3.AmRight(), True)
def test_node_amroot(self):
self.assertEqual(self.n.AmRoot(), True)
def test_node_getbinary(self):
self.n.SetLeft(self.n2)
self.n2.SetParent(self.n)
self.n.SetRight(self.n3)
self.n3.SetParent(self.n)
self.assertEqual(self.n2.GetBinary(), 0)
self.assertEqual(self.n3.GetBinary(), 1)
def test_node_get_path(self):
self.n.SetLeft(self.n2)
self.n2.SetParent(self.n)
self.n.SetRight(self.n3)
self.n3.SetParent(self.n)
self.n4.SetParent(self.n2)
self.n5.SetParent(self.n2)
self.n2.SetLeft(self.n4)
self.n2.SetRight(self.n5)
self.assertEqual(self.n2.GetPath(), "0")
self.assertEqual(self.n3.GetPath(), "1")
self.assertEqual(self.n4.GetPath(), "00")
self.assertEqual(self.n5.GetPath(), "01")
class TreeTest(unittest.TestCase):
def setUp(self):
self.t = tree.Tree()
def structuralSetUp(self):
# Setup for structual comparisons & marking-as-used
self.n = tree.Node(supplied_data = "Root")
self.n2 = tree.Node(supplied_data = "Test2")
self.n3 = tree.Node(supplied_data = "Test3")
self.n4 = tree.Node(supplied_data = "Test4")
self.n5 = tree.Node(supplied_data = "Test5")
self.n6 = tree.Node(supplied_data = "Test6")
self.n7 = tree.Node(supplied_data = "Test7")
self.t.SetRoot(self.n)
self.t.GetRoot().SetLeft(self.n2)
self.n2.SetParent(self.n)
self.t.GetRoot().GetLeft().SetLeft(self.n3)
self.n3.SetParent(self.n2)
self.t.GetRoot().GetLeft().SetRight(self.n4)
self.n4.SetParent(self.n2)
self.t.GetRoot().SetRight(self.n5)
self.n5.SetParent(self.n)
self.t.GetRoot().GetRight().SetLeft(self.n6)
self.n6.SetParent(self.n5)
self.t.GetRoot().GetRight().SetRight(self.n7)
self.n7.SetParent(self.n5)
self.n3.used = True
self.n4.used = True
self.n6.used = True
self.n7.used = True
def test_tree_new(self):
self.failUnless('Insert' in dir(self.t))
def test_tree_path_to_dot_quad(self):
binstr = "1111"
x = self.t.PathToDotQuad(binstr, 4)
self.assertEqual(x, "240.0.0.0/4")
binstr = "10100111111"
y = self.t.PathToDotQuad(binstr, 16)
self.assertEqual(y, "167.224.0.0/16")
def test_tree_get_root_properties(self):
self.failUnless(self.t.GetRoot().GetData() == 'Root')
self.failUnless(self.t.GetRoot().GetLeft() == None)
self.failUnless(self.t.GetRoot().GetRight() == None)
self.failUnless(self.t.GetRoot().GetParent() == None)
def test_tree_generate_for_prefix(self):
for x in self.t.GenerateForPrefix(2):
self.failUnless(x in ['0.0.0.0/2', '64.0.0.0/2',
'128.0.0.0/2', '192.0.0.0/2'])
def test_tree_insert_default_route(self):
obj = self.t.Insert('0.0.0.0/0', "test03point5", test_dup = False)
self.assertEqual(obj, self.t.GetRoot())
def test_tree_structural_comparison(self):
# N
# N2 N5
# N3 N4 N6 N7
self.structuralSetUp()
for x in self.t.IterateNodes():
self.failUnless(x in ['0.0.0.0/2', '64.0.0.0/2',
'128.0.0.0/2', '192.0.0.0/2'])
self.t2 = tree.Tree()
self.t2.Insert('0.0.0.0/2', 'structural')
self.t2.Insert('64.0.0.0/2', 'structural')
self.t2.Insert('128.0.0.0/2', 'structural')
self.t2.Insert('192.0.0.0/2', 'structural')
for x in self.t2.IterateNodes():
self.failUnless(x in ['0.0.0.0/2', '64.0.0.0/2',
'128.0.0.0/2', '192.0.0.0/2'])
def test_tree_follow_chain(self):
self.t.Insert('192.168.0.0/16', 'test_tree_follow_chain')
obj = self.t.Lookup('192.168.0.0/16')
current = obj
self.assertEqual(current.GetLevel(), 16)
while current != self.t.root:
old_level = current.GetLevel()
current = current.GetParent()
new_level = current.GetLevel()
self.assertEqual(old_level, new_level + 1)
# TODO(niallm): check for membership of array [n - level] -> 192.168.0.0 here
self.t.Insert('192.169.0.0/16', 'test_tree_follow_chain_2')
new_obj = self.t.Lookup('192.169.0.0/16', 'test_tree_follow_chain_3')
self.assertEqual(obj.GetParent(), new_obj.GetParent())
def test_tree_recursive_marking(self):
self.structuralSetUp()
self.assertEqual(self.n2.used, False)
self.t.CheckRecursivelyUsed(self.n3)
self.assertEqual(self.n2.used, True)
self.assertEqual(self.n.used, False)
self.n5.used = True
self.t.CheckRecursivelyUsed(self.n3)
self.assertEqual(self.n.used, True)
def test_tree_insert_one_prefix_left(self):
obj = self.t.Insert('0.0.0.0/1', "testInsertSmall")
data = obj.GetData()
used = obj.used
left = obj.GetLeft()
right = obj.GetRight()
parent = obj.GetParent()
level = obj.GetLevel()
root = self.t.GetRoot()
self.assertEqual(data, "testInsertSmall")
self.assertEqual(used, True)
self.assertEqual(parent, root)
self.assertEqual(left, None)
self.assertEqual(right, None)
self.failUnless(obj.GetParent().GetLeft() == obj)
self.assertEqual(level, 1)
def test_tree_insert_flags(self):
result = self.t.Insert('0.0.0.0/8', '4.5treeobj', mark_used = False,
test_used = True, test_none = False)
self.assertEqual(result.used, False)
def test_tree_insert_two_prefixes_getbinary(self):
obj = self.t.Insert('0.0.0.0/1', "testInsertSmall")
bin = obj.GetBinary()
self.failUnless(str(bin) == "0")
obj = self.t.Insert('128.0.0.0/1', "testInsertSmall")
bin = obj.GetBinary()
self.failUnless(str(bin) == "1")
def test_tree_insert_one_prefix_right(self):
obj = self.t.Insert('128.0.0.0/1', "testInsertSmall")
data = obj.GetData()
used = obj.used
left = obj.GetLeft()
right = obj.GetRight()
parent = obj.GetParent()
level = obj.GetLevel()
path = obj.GetPath()
self.assertEqual(data, "testInsertSmall")
self.assertEqual(used, True)
self.assertEqual(parent, self.t.GetRoot())
self.assertEqual(left, None)
self.assertEqual(right, None)
self.assertEqual(obj.GetParent().GetRight(), obj)
self.assertEqual(level, 1)
self.assertEqual(path, "1")
def test_tree_insert_one_longer_prefix(self):
obj = self.t.Insert('10.0.0.0/8', "testInsertLarge")
data = obj.GetData()
used = obj.used
left = obj.GetLeft()
right = obj.GetRight()
parent = obj.GetParent()
level = obj.GetLevel()
path = obj.GetPath()
self.failUnless(obj.GetData() == 'testInsertLarge')
self.assertEqual(right, None)
self.assertEqual(left, None)
self.assertEqual(level, 8)
self.assertEqual(path, "00001010")
def test_tree_get_path_to_real_prefix(self):
obj = self.t.Insert('10.0.0.0/8', "testGetPath")
path = obj.GetPath()
self.failUnless(path == "00001010", "unexpected path to node: [%s] " % path)
obj = self.t.Insert('137.43.0.0/16', "testInsertLarge")
path = obj.GetPath()
self.failUnless(path == "1000100100101011", "unexpected path to node: [%s] " % path)
def test_tree_lookup_succeed(self):
obj = self.t.Insert('10.0.0.0/8', "testLookup")
obj2 = self.t.Lookup('10.0.0.0/8')
self.assertEqual(obj, obj2)
def test_tree_lookup_fail(self):
obj = self.t.Insert('10.0.0.0/8', "testNegLookup")
obj2 = self.t.Lookup('127.0.0.1')
self.assertEqual(obj2, None)
self.assertNotEqual(obj, None)
def test_tree_lookup_funky(self):
for count in range(4,12):
objdict = {}
total_route_set = []
for route in self.t.GenerateForPrefix(count):
total_route_set.append(route)
picks = random.sample(total_route_set, count/2)
for item in picks:
objdict[item] = self.t.Insert(item,
"complex_find_gap", mark_used = False)
for item in total_route_set:
if item in picks:
self.assertEqual(self.t.Lookup(item), objdict[item],
"Picks lookup [%s] got [%s]" % (self.t.Lookup(item),
objdict[item]))
else:
self.assertEqual(self.t.Lookup(item), None,
"Non-picks lookup get [%s] not none" %
self.t.Lookup(item))
def test_insert_duplicate_fails(self):
#self.t.debug=30
obj1 = self.t.Insert('137.43.0.0/16', 'testInsertDup')
self.assertEqual(False, self.t.Insert('137.43.0.0/16',
'testInsertDup'))
#self.t.debug=0
def test_tree_quick_insert_multiple_prefixes(self):
obj1 = self.t.Insert('0.0.0.0/8', "testInsertMultiple")
obj2 = self.t.Insert('1.0.0.0/8', "testInsertMultiple")
data1 = obj1.GetData()
used1 = obj1.used
left1 = obj1.GetLeft()
right1 = obj1.GetRight()
parent1 = obj1.GetParent()
level1 = obj1.GetLevel()
left2 = obj2.GetLeft()
right2 = obj2.GetRight()
parent2 = obj2.GetParent()
level2 = obj2.GetLevel()
self.assertEqual(data1, 'testInsertMultiple')
self.assertEqual(left1, None)
self.assertEqual(left2, None)
self.assertEqual(level1, 8)
self.assertEqual(level2, 8)
class TreeTestGaps(unittest.TestCase):
def setUp(self):
self.t = tree.Tree()
def test_tree_quick_find_gap_vanilla(self):
# Simple insert
self.t.Insert('0.0.0.0/8', "testFindGap")
ret = self.t.FindGap(8)
self.assertEqual(ret, "1.0.0.0/8",
"Find gap returned [%s], not 1.0.0.0/8" % ret)
# Route of same length immediately beside
self.t.Insert('1.0.0.0/8', "testFindGap2")
ret2 = self.t.FindGap(8)
self.assertEqual(ret2, "2.0.0.0/8",
"Find gap returned [%s], not 2.0.0.0/8" % ret2)
# And up two levels and down again
self.t.Insert("2.0.0.0/8", "testFindGap")
ret3 = self.t.FindGap(8)
self.assertEqual(ret3, "3.0.0.0/8",
"Find gap returned [%s], not " % ret3)
# Insert covering route (0-3/8)
self.t.Insert("0.0.0.0/6", "testFindGap")
ret4 = self.t.FindGap(6)
self.assertEqual(ret4, "4.0.0.0/6")
# Find a large gap after some small routes inserted
self.t.Insert("0.0.0.0/4", "testFindGap")
ret5 = self.t.FindGap(6)
self.assertEqual(ret5, "16.0.0.0/6")
# Bang over to the other side of the tree altogether
ret6 = self.t.FindGap(1)
self.assertEqual(ret6, "128.0.0.0/1")
def test_tree_quick_find_gap_random(self):
for count in range(1,10):
self.t = None
self.t = tree.Tree()
# Looking for route with a relevant prefix size.
# Generate a list of all possible prefixes leaving out one at random.
total_route_set = []
for route in self.t.GenerateForPrefix(count):
total_route_set.append(route)
remove_me = random.choice(total_route_set)
total_route_set.remove(remove_me)
for item in total_route_set:
obj1 = self.t.Insert(item, "testFindGap2")
found = self.t.FindGap(count)
self.assertEqual(found, remove_me, "Find gap gave [%s] not expected \
[%s]" % (found, remove_me))
def test_tree_different_size_find_gap(self):
self.t.Insert('0.0.0.0/8', 'reason1')
self.t.Insert('1.0.0.0/8', 'reason2')
r1 = self.t.FindGap(8)
self.assertEqual(r1, '2.0.0.0/8')
self.t.Insert(r1, 'reason1')
r2 = self.t.FindGap(8)
self.assertEqual(r2, '3.0.0.0/8')
self.t.Insert(r2, 'reason2')
r3 = self.t.FindGap(20)
self.assertEqual(r3, '4.0.0.0/20')
self.t.Insert(r3, 'reason3')
r4 = self.t.FindGap(8)
self.assertEqual(r4, '5.0.0.0/8')
r5 = self.t.FindGap(10)
self.assertEqual(r5, '4.64.0.0/10')
self.t.Insert(r5, 'reason5')
r6 = self.t.FindGap(6)
self.assertEqual(r6, '8.0.0.0/6')
r7 = self.t.FindGap(30)
self.assertEqual(r7, '4.0.16.0/30')
def test_tree_different_size_find_gap_from(self):
#self.t.debug = 10
self.t.Insert('0.0.0.0/8', 'reason1')
self.t.Insert('1.0.0.0/8', 'reason2')
r1 = self.t.FindGapFrom('0.0.0.0/1', 8)
self.assertEqual(r1, '2.0.0.0/8')
self.t.Insert(r1, 'reason1')
r2 = self.t.FindGapFrom('0.0.0.0/1', 8)
self.assertEqual(r2, '3.0.0.0/8')
self.t.Insert(r2, 'reason2')
r3 = self.t.FindGapFrom('0.0.0.0/1', 20)
self.assertEqual(r3, '4.0.0.0/20')
self.t.Insert(r3, 'reason3')
r4 = self.t.FindGapFrom('0.0.0.0/1', 8)
self.assertEqual(r4, '5.0.0.0/8')
r5 = self.t.FindGapFrom('0.0.0.0/1', 10)
self.assertEqual(r5, '4.64.0.0/10')
self.t.Insert(r5, 'reason5')
r6 = self.t.FindGapFrom('0.0.0.0/1', 6)
self.assertEqual(r6, '8.0.0.0/6')
r7 = self.t.FindGapFrom('0.0.0.0/1', 30)
self.assertEqual(r7, '4.0.16.0/30')
def test_tree_find_gap(self):
for count in range(4,12):
total_route_set = []
for route in self.t.GenerateForPrefix(count):
total_route_set.append(route)
picks = random.sample(total_route_set, count/2)
for item in picks:
obj1 = self.t.Insert(item, "testFindGap3")
for item in picks:
gap = self.t.FindGap(count)
self.failUnless(gap in total_route_set, "Gap found [%s] not in total \
route set!" % gap)
if gap not in picks:
# Add it and try again
self.t.Insert(gap, "testFindGap3Update")
else:
print "??????"
def test_tree_find_gap_from_simple(self):
self.t.Insert("0.0.0.0/8", 'testFindGapFrom', mark_used = False,
test_none = False)
gap = self.t.FindGapFrom("0.0.0.0/8", 24)
self.assertEqual(gap, "0.0.0.0/24",
"Should find 0.0.0.0/24, instead found [%s]" % gap)
gap = self.t.FindGapFrom("1.0.0.0/8", 24)
self.assertEqual(gap, None,
"Should find no gap, instead got [%s]" % gap)
def test_tree_find_gap_from_simple_higher(self):
self.t.Insert("0.0.0.0/8", 'testFindGapFrom', mark_used = False,
test_none = False)
gap = self.t.FindGapFrom("0.0.0.0/8", 7)
self.assertEqual(gap, None,
"Should find no gap, instead got [%s]" % gap)
def test_tree_find_gap_from_simple_samesize(self):
self.t.Insert("0.0.0.0/8", 'testFindGapFrom', mark_used = False,
test_none = False)
gap = self.t.FindGapFrom("0.0.0.0/8", 8)
self.assertEqual(gap, "0.0.0.0/8")
def test_tree_find_gap_from_middling(self):
self.t.Insert("172.16.0.0/12", "findgapmiddling", mark_used = False,
test_none = False)
gap = self.t.FindGapFrom("172.16.0.0/12", 16)
self.assertEqual(gap, "172.16.0.0/16")
self.t.Insert("172.16.0.0/16", "findgapmiddling")
gap = self.t.FindGapFrom("172.16.0.0/12", 16)
self.assertEqual(gap, "172.17.0.0/16")
self.t.Insert("172.17.0.0/16", "findgapmiddling")
gap = self.t.FindGapFrom("172.16.0.0/12", 24)
self.assertEqual(gap, "172.18.0.0/24")
self.t.Insert("172.16.0.0/13", "findgapmiddling")
self.t.Insert("172.24.0.0/13", "findgapmiddling")
gap = self.t.FindGapFrom("172.16.0.0/12", 8)
self.assertEqual(gap, None)
def test_tree_find_gap_middling_occupied(self):
node = self.t.Insert("172.16.0.0/12", "findgapmiddling", mark_used = False,
test_none = False)
gap = self.t.FindGapFrom("172.16.0.0/12", 16)
self.assertEqual(gap, "172.16.0.0/16")
node.used = True
gap = self.t.FindGapFrom("172.16.0.0/12", 16)
self.assertEqual(gap, None)
def test_tree_find_gap_from_complex(self):
for count in range(4,12):
total_route_set = []
for route in self.t.GenerateForPrefix(count):
total_route_set.append(route)
picks = random.sample(total_route_set, count/2)
for item in picks:
obj1 = self.t.Insert(item, "complex_find_gap", mark_used = False)
for item in total_route_set:
if item in picks:
gap = self.t.FindGapFrom(item, count)
self.assertEqual(gap, item, "Find gap from gave [%s] not expected \
[%s]" % (gap, item))
else:
gap = self.t.FindGapFrom(item, 24)
self.assertEqual(gap, None)
class TreeIteration(unittest.TestCase):
def setUp(self):
self.t = tree.Tree()
def test_tree_iterate_nodes(self):
compare_list = []
for item in self.t.GenerateForPrefix(3):
obj1 = self.t.Insert(item, "testIterateNodes")
compare_list.append(item)
for node in self.t.IterateNodes():
compare_list.remove(node)
self.assertEqual(compare_list, [])
def test_tree_only_supernets(self):
#self.t.debug = 1
#self.t.Insert('199.0.0.0/8', "walk prob root", mark_used = False)
#self.assertEqual(self.t.Lookup('199.0.0.0/8').GetData(), "walk prob root")
original_routes = ['199.4.32.0/19', '199.4.64.0/18', '199.4.128.0/24', '199.4.130.0/23',
'199.4.132.0/24', '199.4.134.0/23', '199.4.136.0/24', '199.4.139.0/24',
'199.4.140.0/24', '199.4.141.0/24']
for route in original_routes:
self.t.Insert(route, "walk problem", mark_used = True, propagate_used = True)
result = []
for f in self.t.IterateNodes(prefix='199.0.0.0/8', top_used=True):
result.append(f)
result2 = ['199.4.32.0/19', '199.4.64.0/18', '199.4.128.0/24', '199.4.130.0/23',
'199.4.132.0/24', '199.4.134.0/23', '199.4.136.0/24', '199.4.139.0/24',
'199.4.140.0/23']
self.assertEqual(result, result2)
class TreeSlowTests(unittest.TestCase):
def setUp(self):
self.t = tree.Tree()
def test_tree_slow_13_treeobj_find_gap_exhaust(self):
self.t.Insert('0.0.0.0/8', "find_gap_exhaust")
route = self.t.FindGap(8)
while route != None:
self.t.Insert(route, "find_gap_exhaust_extend")
route = self.t.FindGap(8)
def test_tree_slow_14_treeobj_find_gap_too_large(self):
self.t.Insert('0.0.0.0/8', "find_gap_exhaust")
route = self.t.FindGap(8)
while route != None:
self.t.Insert(route, "find_gap_exhaust_large")
route = self.t.FindGap(7)
class TreeComparisonTests(unittest.TestCase):
def setUp(self):
self.t = tree.Tree()
def test_compare_tree_1(self):
self.t2 = tree.Tree()
self.t.Insert('1.0.0.0/8', 'reason1')
self.t2.Insert('1.0.0.0/8', 'reason2')
self.assertEqual(self.t, self.t2)
def test_compare_tree_2(self):
self.t2 = tree.Tree()
self.t.Insert('192.168.0.0/23', 'reason1', mark_used=True)
self.t2.Insert('192.168.0.0/24', 'reason2', mark_used=True, propagate_used=True)
self.t2.Insert('192.168.1.0/24', 'reason3', mark_used=True, propagate_used=True)
#print "T2"
#for x in self.t2.IterateNodes():
#print "X T2", x
#print "T1"
#for y in self.t.IterateNodes():
#print "Y T", y
#print "ASSERT"
self.assertEqual(self.t, self.t2)
def test_compare_tree_3(self):
pass
if __name__ == '__main__':
unittest.main()
|
apache-2.0
| -4,469,209,220,088,208,400
| 34.709402
| 94
| 0.613787
| false
| 2.750132
| true
| false
| false
|
kmahyyg/learn_py3
|
antiscanhttp.py
|
1
|
2192
|
#!/usr/bin/env python3
# -*- coding : utf-8 -*-
# http://speedtest.tele2.net/10GB.zip
# https://docs.python.org/3/library/http.server.html
# http://blog.csdn.net/cteng/article/details/51584766
"""
Anti-HTTP-Scanner : Redirect all requests to 10GB speedtest file
Patrick Young 2017/10/8
usage: "antiscanhttp.py" [-h] [--port] [--ip] redirect_url
positional arguments:
redirect_url (such as http://speedtest.tele2.net/10GB.zip)
optional arguments:
-h,--help Show this help message and exit
--port,-p Port to listen on , Default 80
--ip,-i Host interface to listen on
redirect_url Recommend to use 'http://speedtest.tele2.net/10GB.zip'
"""
import socketserver
import http.server
import argparse
def redirect_handler(url):
class RedirectHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
def do_POST(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
def do_HEAD(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
def do_PUT(self):
self.send_response(301)
self.send_header('Location', url)
self.end_headers()
return RedirectHandler
def main():
parser = argparse.ArgumentParser(description='Anti HTTP Scanner redirector')
parser.add_argument('--port', '-p', action='store', type=int, default=80, help='Server listens on this port')
parser.add_argument('--ip', '-i', action='store', default='', help='Host Interface to listen on')
parser.add_argument('redirect_url', action='store',help='(such as http://speedtest.tele2.net/10GB.zip)')
userinput = parser.parse_args()
redirect_url = userinput.redirect_url
port = userinput.port
host = userinput.ip
redirect_handle = redirect_handler(redirect_url)
handler = socketserver.TCPServer((host, port), redirect_handle)
print('Server now is running on the port %s' % port)
handler.serve_forever()
if __name__ == "__main__":
main()
|
agpl-3.0
| 8,516,625,122,009,231,000
| 31.235294
| 113
| 0.649635
| false
| 3.564228
| false
| false
| false
|
brendanlong/dash-ts-tools
|
dash_initialization_segmenter.py
|
1
|
4159
|
#!/usr/bin/env python3
import argparse
import os
from ts import *
def write_ts(file_name, packets, force):
logging.info("Writing %s", file_name)
if not force and os.path.exists(file_name):
choice = input(
"Output file {} already exists. Overwrite it? "
"[y/N] ".format(file_name)).lower()
if choice != "y":
return
with open(file_name, "wb") as f:
for packet in packets:
f.write(packet.bytes)
def generate_initialization_segment(
segment_file_names, segment_template, out_file_name, force):
pat = None
pat_ts = None
pmt = None
pmt_ts = None
segment_ts = {}
pmt_pid = None
for segment_file_name in segment_file_names:
logging.info("Reading %s", segment_file_name)
current_segment_ts = []
segment_ts[segment_file_name] = current_segment_ts
for ts in read_ts(segment_file_name):
if ts.pid == ProgramAssociationTable.PID:
new_pat = ProgramAssociationTable(ts.payload)
if pat is None:
pat = new_pat
pat_ts = ts
programs = list(pat.programs.values())
if len(programs) != 1:
raise Exception(
"PAT has {} programs, but DASH only allows 1 "
"program.".format(len(pat.programs)))
if pmt_pid is not None and programs[0] != pmt_pid:
raise Exception("PAT has new PMT PID. This program has "
"not been tested to handled this case.")
pmt_pid = programs[0]
elif new_pat != pat:
raise Exception("Cannot generate initialization segment "
"for segment with multiple PAT's. {} != {"
"}".format(new_pat, pat))
elif ts.pid == pmt_pid:
new_pmt = ProgramMapTable(ts.payload)
if pmt is None:
pmt = new_pmt
pmt_ts = ts
elif new_pmt != pmt:
raise Exception("Cannot generate initialization segment "
"for segment with multiple PMT's. {} != {"
"}".format(new_pmt, pmt))
else:
current_segment_ts.append(ts)
logging.debug("Common PSI is:\nPAT: %s\nPMT: %s", pat, pmt)
write_ts(out_file_name, [pat_ts, pmt_ts], force)
for segment_file_name in segment_file_names:
path, file_name = os.path.split(segment_file_name)
name_part, _ = os.path.splitext(file_name)
segment_out_file_name = segment_template.format_map(
{"path": path, "name_part": name_part})
write_ts(segment_out_file_name, segment_ts[segment_file_name], force)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"media_segment", nargs="+",
help="The media segments to create an initialization segment for.")
parser.add_argument(
"--segment-template", "-s",
help="Template for segment index files. {name_part} will be replaced "
"with the file name of the media segment minus the suffix (.ts). "
"{path} will be replaced with the full path to the media segment.",
default="{path}/{name_part}.ts")
parser.add_argument(
"--out", "-o", required=True,
help="The file to write the initialization segment to.")
parser.add_argument(
"--force", "-f", action="store_true", default=False,
help="Overwrite output files without prompting.")
parser.add_argument(
"--verbose", "-v", action="store_true", default=False,
help="Enable verbose output.")
args = parser.parse_args()
logging.basicConfig(
format='%(levelname)s: %(message)s',
level=logging.DEBUG if args.verbose else logging.INFO)
generate_initialization_segment(
args.media_segment, args.segment_template, args.out, args.force)
|
bsd-2-clause
| -5,032,914,013,594,060,000
| 40.178218
| 80
| 0.5434
| false
| 4.19254
| false
| false
| false
|
MarcoVogt/basil
|
tests/test_RegisterHardwareLayer.py
|
1
|
9389
|
#
# ------------------------------------------------------------
# Copyright (c) All rights reserved
# SiLab, Institute of Physics, University of Bonn
# ------------------------------------------------------------
#
import unittest
from basil.dut import Dut
from basil.HL.RegisterHardwareLayer import RegisterHardwareLayer
import os
_test_init = {
'REG_TEST_INIT': 15,
'REG1': 120,
'REG_BYTE_ARRAY': [4, 3, 2, 1]
}
class test_RegisterHardwareLayer(RegisterHardwareLayer):
'''Register Hardware Layer.
Implementation of advanced register operations.
'''
_registers = {
'REG1': {'default': 12, 'descr': {'addr': 0, 'size': 15, 'offset': 0}},
'REG2': {'default': 1, 'descr': {'addr': 1, 'size': 1, 'offset': 7}},
'REG3': {'default': 2 ** 16 - 1, 'descr': {'addr': 2, 'size': 16, 'offset': 0}},
'REG4_RO': {'default': 0, 'descr': {'addr': 4, 'size': 8, 'properties': ['readonly']}},
'REG5_WO': {'default': 0, 'descr': {'addr': 5, 'size': 8, 'properties': ['writeonly']}},
'REG_TEST_INIT': {'descr': {'addr': 6, 'size': 8}},
'REG_BYTE_ARRAY': {'default': [1, 2, 3, 4], 'descr': {'addr': 16, 'size': 4, 'properties': ['bytearray']}}
}
class TestRegisterHardwareLayer(unittest.TestCase):
def setUp(self):
self.dut = Dut(os.path.join(os.path.dirname(__file__), 'test_RegisterHardwareLayer.yaml'))
self.dut.init()
def test_init_non_existing(self):
with self.assertRaises(KeyError):
self.dut.init({"test_register": {"NON_EXISTING": 1}})
def test_lazy_programming(self):
self.dut['test_register'].set_default()
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
self.dut['test_register'].REG5_WO = 255
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 255, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
self.dut['test_register'].REG5_WO # get value from write-only register, but this will write zero instead
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
def test_get_configuration(self):
self.dut.set_configuration(os.path.join(os.path.dirname(__file__), 'test_RegisterHardwareLayer_configuration.yaml'))
conf = self.dut['test_register'].get_configuration()
self.assertDictEqual({'REG1': 257, 'REG2': 1, 'REG3': 2, 'REG_TEST_INIT': 0, 'REG_BYTE_ARRAY': [1, 2, 3, 4]}, conf)
def test_set_configuration(self):
self.dut.set_configuration(os.path.join(os.path.dirname(__file__), 'test_RegisterHardwareLayer_configuration.yaml'))
self.assertDictEqual({0: 1, 1: 129, 2: 2, 3: 0, 5: 5, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
def test_set_configuration_non_existing(self):
with self.assertRaises(KeyError):
self.dut.set_configuration({"test_register": {"NON_EXISTING": 1}})
def test_read_only(self):
self.assertRaises(IOError, self.dut['test_register']._set, 'REG4_RO', value=0)
# def test_write_only(self):
# self.assertRaises(IOError, self.dut['test_register']._get, 'REG5_WO')
def test_write_only_lazy_programming(self):
self.dut['test_register'].set_default()
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
self.dut['test_register'].REG5_WO = 20
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 20, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
self.dut['test_register'].REG5_WO
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
self.assertIs(None, self.dut['test_register']._get('REG5_WO'))
def test_set_default(self):
self.dut['test_register'].set_default()
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
def test_set_attribute_add(self):
val = self.dut['test_register']._registers['REG1']['default']
self.dut['test_register'].REG1 = val # 12
mem = self.dut['dummy_tl'].mem.copy()
self.dut['test_register'].REG1 += 1 # 13
mem[0] = 13
self.assertDictEqual(mem, self.dut['dummy_tl'].mem)
def test_write_read_reg(self):
for reg in ['REG1', 'REG2', 'REG3']:
val = self.dut['test_register']._registers[reg]['default']
self.dut['test_register']._set(reg, val)
ret_val = self.dut['test_register']._get(reg)
self.assertEqual(ret_val, val)
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
def test_set_attribute_by_value(self):
self.dut['test_register'].set_default()
self.assertDictEqual({0: 12, 1: 128, 2: 255, 3: 255, 5: 0, 16: 1, 17: 2, 18: 3, 19: 4}, self.dut['dummy_tl'].mem)
self.dut['test_register'].REG2 = 0
mem = self.dut['dummy_tl'].mem.copy()
mem[1] = 0
self.assertDictEqual(mem, self.dut['dummy_tl'].mem)
def test_set_attribute_by_string(self):
mem = self.dut['dummy_tl'].mem.copy()
self.dut['test_register'].REG3 = '1010101010101010' # dfghfghdfghgfdghf
mem[2] = 170
mem[3] = 170
self.assertDictEqual(mem, self.dut['dummy_tl'].mem)
def test_get_attribute_by_string(self):
self.dut['test_register'].REG3 = '1010101010101010' # 43690
self.assertEqual(43690, self.dut['test_register'].REG3)
def test_set_attribute_too_long_string(self):
val = '11010101010101010' # 17 bit
self.assertRaises(ValueError, self.dut['test_register']._set, 'REG3', value=val)
def test_set_attribute_dict_access(self):
self.dut['test_register']['REG1'] = 27306 # 27306
self.assertEqual(27306, self.dut['test_register']['REG1'])
def test_set_attribute_too_big_val(self):
val = 2 ** 16 # max 2 ** 16 - 1
self.assertRaises(ValueError, self.dut['test_register']._set, 'REG3', value=val)
def test_set_by_function(self):
self.dut['test_register'].set_REG1(27308)
self.assertEqual(27308, self.dut['test_register']['REG1'])
def test_get_by_function(self):
self.dut['test_register']['REG1'] = 27305 # 27306
ret = self.dut['test_register'].get_REG1()
self.assertEqual(ret, self.dut['test_register']['REG1'])
def test_init_with_dict(self):
self.dut['test_register'].set_default()
self.dut.init({'test_register': _test_init})
conf = self.dut.get_configuration()
self.assertDictEqual({'test_register': {'REG1': 120, 'REG2': 1, 'REG3': 65535, 'REG_TEST_INIT': 15, 'REG_BYTE_ARRAY': [4, 3, 2, 1]}, 'dummy_tl': {}}, conf)
def test_get_dut_configuration(self):
self.dut['test_register'].set_default()
conf = self.dut.get_configuration()
self.assertDictEqual({'test_register': {'REG1': 12, 'REG2': 1, 'REG3': 65535, 'REG_TEST_INIT': 0, 'REG_BYTE_ARRAY': [1, 2, 3, 4]}, 'dummy_tl': {}}, conf)
def test_get_set_value(self):
for val in range(256):
self.dut['test_register'].set_value(val, 0, size=8, offset=0)
ret_val = self.dut['test_register'].get_value(0, size=8, offset=0)
self.assertEqual(ret_val, val)
def test_write_read_reg_with_bit_str(self):
val = '00110110' # 54
self.dut['test_register'].set_value(val, 0, size=8, offset=0)
ret_val = self.dut['test_register'].get_value(0, size=8, offset=0)
self.assertEqual(ret_val, int(val, base=2))
def test_write_read_reg_with_offset(self):
for offset in range(32):
val = 131
self.dut['test_register'].set_value(val, 0, size=8, offset=offset)
ret_val = self.dut['test_register'].get_value(0, size=8, offset=offset)
self.assertEqual(ret_val, val)
def test_write_read_reg_with_size(self):
for size in range(8, 33):
val = 131
self.dut['test_register'].set_value(val, 0, size=size, offset=7)
ret_val = self.dut['test_register'].get_value(0, size=size, offset=7)
self.assertEqual(ret_val, val)
def test_read_non_existing(self):
with self.assertRaises(KeyError):
self.dut['test_register'].NON_EXISTING
with self.assertRaises(KeyError):
self.dut['test_register']['NON_EXISTING']
with self.assertRaises(KeyError):
self.dut['test_register'].get_NON_EXISTING()
def test_write_non_existing(self):
with self.assertRaises(KeyError):
self.dut['test_register'].NON_EXISTING = 42
with self.assertRaises(KeyError):
self.dut['test_register']['NON_EXISTING'] = 42
with self.assertRaises(KeyError):
self.dut['test_register'].set_NON_EXISTING(42)
def test_wrong_size(self):
self.assertRaises(ValueError, self.dut['test_register'].set_value, 131, addr=0, size=7, offset=7)
if __name__ == '__main__':
unittest.main()
|
bsd-3-clause
| -6,639,450,954,130,615,000
| 45.180905
| 163
| 0.575248
| false
| 3.235355
| true
| false
| false
|
mistercrunch/panoramix
|
superset/reports/api.py
|
2
|
14710
|
# 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 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.
import logging
from typing import Any, Optional
from flask import g, request, Response
from flask_appbuilder.api import expose, permission_name, protect, rison, safe
from flask_appbuilder.hooks import before_request
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import ngettext
from marshmallow import ValidationError
from superset import is_feature_enabled
from superset.charts.filters import ChartFilter
from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod
from superset.dashboards.filters import DashboardAccessFilter
from superset.databases.filters import DatabaseFilter
from superset.models.reports import ReportSchedule
from superset.reports.commands.bulk_delete import BulkDeleteReportScheduleCommand
from superset.reports.commands.create import CreateReportScheduleCommand
from superset.reports.commands.delete import DeleteReportScheduleCommand
from superset.reports.commands.exceptions import (
ReportScheduleBulkDeleteFailedError,
ReportScheduleCreateFailedError,
ReportScheduleDeleteFailedError,
ReportScheduleForbiddenError,
ReportScheduleInvalidError,
ReportScheduleNotFoundError,
ReportScheduleUpdateFailedError,
)
from superset.reports.commands.update import UpdateReportScheduleCommand
from superset.reports.filters import ReportScheduleAllTextFilter
from superset.reports.schemas import (
get_delete_ids_schema,
openapi_spec_methods_override,
ReportSchedulePostSchema,
ReportSchedulePutSchema,
)
from superset.views.base_api import (
BaseSupersetModelRestApi,
RelatedFieldFilter,
statsd_metrics,
)
from superset.views.filters import FilterRelatedOwners
logger = logging.getLogger(__name__)
class ReportScheduleRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(ReportSchedule)
@before_request
def ensure_alert_reports_enabled(self) -> Optional[Response]:
if not is_feature_enabled("ALERT_REPORTS"):
return self.response_404()
return None
include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
}
class_permission_name = "ReportSchedule"
method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
resource_name = "report"
allow_browser_login = True
show_columns = [
"id",
"active",
"chart.id",
"chart.slice_name",
"context_markdown",
"crontab",
"dashboard.dashboard_title",
"dashboard.id",
"database.database_name",
"database.id",
"description",
"grace_period",
"last_eval_dttm",
"last_state",
"last_value",
"last_value_row_json",
"log_retention",
"name",
"owners.first_name",
"owners.id",
"owners.last_name",
"recipients.id",
"recipients.recipient_config_json",
"recipients.type",
"report_format",
"sql",
"type",
"validator_config_json",
"validator_type",
"working_timeout",
]
show_select_columns = show_columns + [
"chart.datasource_id",
"chart.datasource_type",
]
list_columns = [
"active",
"changed_by.first_name",
"changed_by.last_name",
"changed_on",
"changed_on_delta_humanized",
"created_by.first_name",
"created_by.last_name",
"created_on",
"crontab",
"crontab_humanized",
"id",
"last_eval_dttm",
"last_state",
"name",
"owners.first_name",
"owners.id",
"owners.last_name",
"recipients.id",
"recipients.type",
"type",
]
add_columns = [
"active",
"chart",
"context_markdown",
"crontab",
"dashboard",
"database",
"description",
"grace_period",
"log_retention",
"name",
"owners",
"recipients",
"report_format",
"sql",
"type",
"validator_config_json",
"validator_type",
"working_timeout",
]
edit_columns = add_columns
add_model_schema = ReportSchedulePostSchema()
edit_model_schema = ReportSchedulePutSchema()
order_columns = [
"active",
"created_by.first_name",
"changed_by.first_name",
"changed_on",
"changed_on_delta_humanized",
"created_on",
"crontab",
"last_eval_dttm",
"name",
"type",
"crontab_humanized",
]
search_columns = ["name", "active", "created_by", "type", "last_state"]
search_filters = {"name": [ReportScheduleAllTextFilter]}
allowed_rel_fields = {"owners", "chart", "dashboard", "database", "created_by"}
filter_rel_fields = {
"chart": [["id", ChartFilter, lambda: []]],
"dashboard": [["id", DashboardAccessFilter, lambda: []]],
"database": [["id", DatabaseFilter, lambda: []]],
}
text_field_rel_fields = {
"dashboard": "dashboard_title",
"chart": "slice_name",
"database": "database_name",
}
related_field_filters = {
"dashboard": "dashboard_title",
"chart": "slice_name",
"database": "database_name",
"owners": RelatedFieldFilter("first_name", FilterRelatedOwners),
}
apispec_parameter_schemas = {
"get_delete_ids_schema": get_delete_ids_schema,
}
openapi_spec_tag = "Report Schedules"
openapi_spec_methods = openapi_spec_methods_override
@expose("/<int:pk>", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@permission_name("delete")
def delete(self, pk: int) -> Response:
"""Delete a Report Schedule
---
delete:
description: >-
Delete a Report Schedule
parameters:
- in: path
schema:
type: integer
name: pk
description: The report schedule pk
responses:
200:
description: Item deleted
content:
application/json:
schema:
type: object
properties:
message:
type: string
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
try:
DeleteReportScheduleCommand(g.user, pk).run()
return self.response(200, message="OK")
except ReportScheduleNotFoundError:
return self.response_404()
except ReportScheduleForbiddenError:
return self.response_403()
except ReportScheduleDeleteFailedError as ex:
logger.error(
"Error deleting report schedule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
@expose("/", methods=["POST"])
@protect()
@safe
@statsd_metrics
@permission_name("post")
def post(self) -> Response:
"""Creates a new Report Schedule
---
post:
description: >-
Create a new Report Schedule
requestBody:
description: Report Schedule schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
responses:
201:
description: Report schedule added
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.post'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.add_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = CreateReportScheduleCommand(g.user, item).run()
return self.response(201, id=new_model.id, result=item)
except ReportScheduleNotFoundError as ex:
return self.response_400(message=str(ex))
except ReportScheduleInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ReportScheduleCreateFailedError as ex:
logger.error(
"Error creating report schedule %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
@expose("/<int:pk>", methods=["PUT"])
@protect()
@safe
@statsd_metrics
@permission_name("put")
def put(self, pk: int) -> Response: # pylint: disable=too-many-return-statements
"""Updates an Report Schedule
---
put:
description: >-
Updates a Report Schedule
parameters:
- in: path
schema:
type: integer
name: pk
description: The Report Schedule pk
requestBody:
description: Report Schedule schema
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
responses:
200:
description: Report Schedule changed
content:
application/json:
schema:
type: object
properties:
id:
type: number
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.put'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
500:
$ref: '#/components/responses/500'
"""
if not request.is_json:
return self.response_400(message="Request is not JSON")
try:
item = self.edit_model_schema.load(request.json)
# This validates custom Schema with custom validations
except ValidationError as error:
return self.response_400(message=error.messages)
try:
new_model = UpdateReportScheduleCommand(g.user, pk, item).run()
return self.response(200, id=new_model.id, result=item)
except ReportScheduleNotFoundError:
return self.response_404()
except ReportScheduleInvalidError as ex:
return self.response_422(message=ex.normalized_messages())
except ReportScheduleForbiddenError:
return self.response_403()
except ReportScheduleUpdateFailedError as ex:
logger.error(
"Error updating report %s: %s",
self.__class__.__name__,
str(ex),
exc_info=True,
)
return self.response_422(message=str(ex))
@expose("/", methods=["DELETE"])
@protect()
@safe
@statsd_metrics
@rison(get_delete_ids_schema)
def bulk_delete(self, **kwargs: Any) -> Response:
"""Delete bulk Report Schedule layers
---
delete:
description: >-
Deletes multiple report schedules in a bulk operation.
parameters:
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_delete_ids_schema'
responses:
200:
description: Report Schedule bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteReportScheduleCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
"Deleted %(num)d report schedule",
"Deleted %(num)d report schedules",
num=len(item_ids),
),
)
except ReportScheduleNotFoundError:
return self.response_404()
except ReportScheduleForbiddenError:
return self.response_403()
except ReportScheduleBulkDeleteFailedError as ex:
return self.response_422(message=str(ex))
|
apache-2.0
| -7,320,515,751,932,594,000
| 32.205418
| 85
| 0.560639
| false
| 4.497096
| false
| false
| false
|
adieu/django-invitation
|
invitation/models.py
|
1
|
6880
|
import os
import random
import datetime
from django.db import models
from django.conf import settings
from django.utils.http import int_to_base36
from django.utils.hashcompat import sha_constructor
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from registration.models import SHA1_RE
class InvitationKeyManager(models.Manager):
def get_key(self, invitation_key):
"""
Return InvitationKey, or None if it doesn't (or shouldn't) exist.
"""
try:
code = InvitationCode.objects.get(code=invitation_key)
if self.filter(key=invitation_key).count() < code.redeem_limit:
key = self.model(key=invitation_key, from_user=code.from_user)
return key
except InvitationCode.DoesNotExist:
pass
# Don't bother hitting database if invitation_key doesn't match pattern.
if not SHA1_RE.search(invitation_key):
return None
try:
key = self.get(key=invitation_key)
except self.model.DoesNotExist:
return None
return key
def is_key_valid(self, invitation_key):
"""
Check if an ``InvitationKey`` is valid or not, returning a boolean,
``True`` if the key is valid.
"""
invitation_key = self.get_key(invitation_key)
return invitation_key and invitation_key.is_usable()
def create_invitation(self, user):
"""
Create an ``InvitationKey`` and returns it.
The key for the ``InvitationKey`` will be a SHA1 hash, generated
from a combination of the ``User``'s username and a random salt.
"""
salt = sha_constructor(str(random.random())).hexdigest()[:5]
key = sha_constructor("%s%s%s" % (datetime.datetime.now(), salt, user.username)).hexdigest()
return self.create(from_user=user, key=key)
def remaining_invitations_for_user(self, user):
"""
Return the number of remaining invitations for a given ``User``.
"""
invitation_user, created = InvitationUser.objects.get_or_create(
inviter=user,
defaults={'invitations_remaining': settings.INVITATIONS_PER_USER})
return invitation_user.invitations_remaining
def delete_expired_keys(self):
for key in self.all():
if key.key_expired():
key.delete()
class InvitationKey(models.Model):
key = models.CharField(_('invitation key'), max_length=40)
date_invited = models.DateTimeField(_('date invited'), default=datetime.datetime.now)
from_user = models.ForeignKey(User, related_name='invitations_sent')
registrant = models.ForeignKey(User, null=True, blank=True, related_name='invitations_used')
objects = InvitationKeyManager()
def __unicode__(self):
return u"Invitation from %s on %s" % (self.from_user.username, self.date_invited)
def is_usable(self):
"""
Return whether this key is still valid for registering a new user.
"""
return self.registrant is None and not self.key_expired()
def key_expired(self):
"""
Determine whether this ``InvitationKey`` has expired, returning
a boolean -- ``True`` if the key has expired.
The date the key has been created is incremented by the number of days
specified in the setting ``ACCOUNT_INVITATION_DAYS`` (which should be
the number of days after invite during which a user is allowed to
create their account); if the result is less than or equal to the
current date, the key has expired and this method returns ``True``.
"""
expiration_date = datetime.timedelta(days=settings.ACCOUNT_INVITATION_DAYS)
return self.date_invited + expiration_date <= datetime.datetime.now()
key_expired.boolean = True
def mark_used(self, registrant):
"""
Note that this key has been used to register a new user.
"""
self.registrant = registrant
self.save()
def send_to(self, email):
"""
Send an invitation email to ``email``.
"""
current_site = Site.objects.get_current()
subject = render_to_string('invitation/invitation_email_subject.txt',
{ 'site': current_site,
'invitation_key': self })
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
message = render_to_string('invitation/invitation_email.txt',
{ 'invitation_key': self,
'expiration_days': settings.ACCOUNT_INVITATION_DAYS,
'site': current_site })
send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [email])
class InvitationCode(models.Model):
code = models.CharField(_('invitation code'), max_length=40)
date_created = models.DateTimeField(_('date created'), default=datetime.datetime.now)
from_user = models.ForeignKey(User, related_name='invitation_code_set')
redeem_limit = models.IntegerField()
def __unicode__(self):
return u"Invitation code %s from %s" % (self.code, self.from_user.username)
class InvitationRequest(models.Model):
email = models.EmailField()
invited = models.BooleanField(default=False)
def __unicode__(self):
return u"InvitationRequest from %s" % self.email
class InvitationUser(models.Model):
inviter = models.ForeignKey(User, unique=True)
invitations_remaining = models.IntegerField()
def __unicode__(self):
return u"InvitationUser for %s" % self.inviter.username
def user_post_save(sender, instance, created, **kwargs):
"""Create InvitationUser for user when User is created."""
if created:
invitation_user = InvitationUser()
invitation_user.inviter = instance
invitation_user.invitations_remaining = settings.INVITATIONS_PER_USER
invitation_user.save()
models.signals.post_save.connect(user_post_save, sender=User)
def invitation_key_post_save(sender, instance, created, **kwargs):
"""Decrement invitations_remaining when InvitationKey is created."""
if created:
invitation_user = InvitationUser.objects.get(inviter=instance.from_user)
remaining = invitation_user.invitations_remaining
invitation_user.invitations_remaining = remaining-1
invitation_user.save()
models.signals.post_save.connect(invitation_key_post_save, sender=InvitationKey)
|
bsd-3-clause
| -6,604,925,912,574,837,000
| 37.435754
| 100
| 0.636628
| false
| 4.075829
| false
| false
| false
|
drssoccer55/RLBot
|
src/main/python/rlbot/utils/structures/rigid_body_struct.py
|
1
|
1072
|
import ctypes
from rlbot.utils.structures.bot_input_struct import PlayerInput
from rlbot.utils.structures.game_data_struct import Vector3
from rlbot.utils.structures.start_match_structures import MAX_PLAYERS
class Quaternion(ctypes.Structure):
_fields_ = [("x", ctypes.c_float),
("y", ctypes.c_float),
("z", ctypes.c_float),
("w", ctypes.c_float)]
class RigidBodyState(ctypes.Structure):
_fields_ = [("frame", ctypes.c_int),
("location", Vector3),
("rotation", Quaternion),
("velocity", Vector3),
("angular_velocity", Vector3)]
class PlayerRigidBodyState(ctypes.Structure):
_fields_ = [("state", RigidBodyState),
("input", PlayerInput)]
class BallRigidBodyState(ctypes.Structure):
_fields_ = [("state", RigidBodyState)]
class RigidBodyTick(ctypes.Structure):
_fields_ = [("ball", BallRigidBodyState),
("players", PlayerRigidBodyState * MAX_PLAYERS),
("num_players", ctypes.c_int)]
|
mit
| -2,333,322,161,590,240,000
| 29.628571
| 69
| 0.609142
| false
| 3.658703
| false
| false
| false
|
jepler/linuxcnc-mirror
|
src/emc/usr_intf/pncconf/pncconf.py
|
1
|
292409
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# This is pncconf, a graphical configuration editor for LinuxCNC
# Chris Morley copyright 2009
# This is based from stepconf, a graphical configuration editor for linuxcnc
# Copyright 2007 Jeff Epler <jepler@unpythonic.net>
#
# 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, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import sys
import os
# this is for importing modules from lib/python/pncconf
BIN = os.path.dirname(__file__)
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
libdir = os.path.join(BASE, "lib", "python","pncconf")
sys.path.insert(0, libdir)
import errno
import time
import pickle
import shutil
import math
from optparse import Option, OptionParser
import textwrap
import locale
import copy
import fnmatch
import subprocess
import gobject
import gtk
import gtk.glade
import xml.dom.minidom
import xml.etree.ElementTree
import xml.etree.ElementPath
import traceback
from multifilebuilder import MultiFileBuilder
from touchy import preferences
from pncconf import pages
from pncconf import build_INI
from pncconf import build_HAL
from pncconf import tests
from pncconf import data
from pncconf import private_data
import cairo
import hal
#import mesatest
try:
LINUXCNCVERSION = os.environ['LINUXCNCVERSION']
except:
LINUXCNCVERSION = 'UNAVAILABLE'
def get_value(w):
try:
return w.get_value()
except AttributeError:
pass
oldlocale = locale.getlocale(locale.LC_NUMERIC)
try:
locale.setlocale(locale.LC_NUMERIC, "")
return locale.atof(w.get_text())
finally:
locale.setlocale(locale.LC_NUMERIC, oldlocale)
def makedirs(d):
try:
os.makedirs(d)
except os.error, detail:
if detail.errno != errno.EEXIST: raise
makedirs(os.path.expanduser("~/linuxcnc/configs"))
# otherwise, on hardy the user is shown spurious "[application] closed
# unexpectedly" messages but denied the ability to actually "report [the]
# problem"
def excepthook(exc_type, exc_obj, exc_tb):
try:
w = app.widgets.window1
except NameError:
w = None
lines = traceback.format_exception(exc_type, exc_obj, exc_tb)
m = gtk.MessageDialog(w,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
_("PNCconf encountered an error. The following "
"information may be useful in troubleshooting:\n\n")
+ "LinuxCNC Version: %s\n\n"% LINUXCNCVERSION + ''.join(lines))
m.show()
m.run()
m.destroy()
sys.excepthook = excepthook
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
LOCALEDIR = os.path.join(BASE, "share", "locale")
import gettext;
domain = "linuxcnc"
gettext.install(domain, localedir=LOCALEDIR, unicode=True)
locale.setlocale(locale.LC_ALL, '')
locale.bindtextdomain(domain, LOCALEDIR)
gettext.bindtextdomain(domain, LOCALEDIR)
def iceil(x):
if isinstance(x, (int, long)): return x
if isinstance(x, basestring): x = float(x)
return int(math.ceil(x))
prefs = preferences.preferences()
_DEBUGSTRING = ["NONE"]
debugstate = False
# a class for holding the glade widgets rather then searching for them each time
class Widgets:
def __init__(self, xml):
self._xml = xml
def __getattr__(self, attr):
r = self._xml.get_object(attr)
if r is None: raise AttributeError, "No widget %r" % attr
return r
def __getitem__(self, attr):
r = self._xml.get_object(attr)
if r is None: raise IndexError, "No widget %r" % attr
return r
class App:
def __init__(self, dbgstate=0):
print dbgstate
global debug
global dbg
global _PD
self.debugstate = dbgstate
dbg = self.dbg
if self.debugstate:
print 'PNCconf debug',dbgstate
global _DEBUGSTRING
_DEBUGSTRING = [dbgstate]
self.recursive_block = False
self.firmware_block = False
# Private data holds the array of pages to load, signals, and messages
_PD = self._p = private_data.Private_Data(self,BIN,BASE)
self.d = data.Data(self, _PD, BASE, LINUXCNCVERSION)
self.splash_screen()
#self.pbar.set_fraction(.2)
#while gtk.events_pending():
# gtk.main_iteration()
bar_size = 0
# build the glade files
self.builder = MultiFileBuilder()
self.builder.set_translation_domain(domain)
self.builder.add_from_file(os.path.join(self._p.DATADIR,'main_page.glade'))
self.builder.add_from_file(os.path.join(self._p.DATADIR,'dialogs.glade'))
self.builder.add_from_file(os.path.join(self._p.DATADIR,'help.glade'))
window = self.builder.get_object("window1")
notebook1 = self.builder.get_object("notebook1")
for name,y,z,a in (self._p.available_page):
if name == 'intro': continue
dbg("loading glade page REFERENCE:%s TITLE:%s INIT STATE: %s STATE:%s"% (name,y,z,a),mtype="glade")
if not z:
self.add_placeholder_page(name)
page = self.builder.get_object('label_%s'%name)
notebook1.append_page(page)
continue
self.builder.add_from_file(os.path.join(self._p.DATADIR, '%s.glade'%name))
page = self.builder.get_object(name)
notebook1.append_page(page)
self.pbar.set_fraction(bar_size)
while gtk.events_pending():
gtk.main_iteration()
bar_size += .0555
if not 'dev' in dbgstate:
notebook1.set_show_tabs(False)
self.widgets = Widgets(self.builder)
self.TESTS = tests.TESTS(self)
self.p = pages.Pages(self)
self.INI = build_INI.INI(self)
self.HAL = build_HAL.HAL(self)
self.builder.set_translation_domain(domain) # for locale translations
self.builder.connect_signals( self.p ) # register callbacks from Pages class
wiz_pic = gtk.gdk.pixbuf_new_from_file(self._p.WIZARD)
self.widgets.wizard_image.set_from_pixbuf(wiz_pic)
self.window.hide()
axisdiagram = os.path.join(self._p.HELPDIR,"axisdiagram1.png")
self.widgets.helppic0.set_from_file(axisdiagram)
axisdiagram = os.path.join(self._p.HELPDIR,"lathe_diagram.png")
self.widgets.helppic1.set_from_file(axisdiagram)
axisdiagram = os.path.join(self._p.HELPDIR,"HomeAxisTravel_V2.png")
self.widgets.helppic2.set_from_file(axisdiagram)
axisdiagram = os.path.join(self._p.HELPDIR,"HomeAxisTravel_V3.png")
self.widgets.helppic3.set_from_file(axisdiagram)
self.map_7i76 = gtk.gdk.pixbuf_new_from_file(os.path.join(self._p.HELPDIR,"7i76_map.png"))
self.widgets.map_7i76_image.set_from_pixbuf(self.map_7i76)
self.map_7i77 = gtk.gdk.pixbuf_new_from_file(os.path.join(self._p.HELPDIR,"7i77_map.png"))
self.widgets.map_7i77_image.set_from_pixbuf(self.map_7i77)
#self.widgets.openloopdialog.hide()
self.p.initialize()
window.show()
self.axis_under_test = False
self.jogminus = self.jogplus = 0
# set preferences if they exist
link = short = advanced = show_pages = False
filename = os.path.expanduser("~/.pncconf-preferences")
if os.path.exists(filename):
match = open(filename).read()
textbuffer = self.widgets.textoutput.get_buffer()
try :
textbuffer.set_text("%s\n\n"% filename)
textbuffer.insert_at_cursor(match)
except:
pass
version = 0.0
d = xml.dom.minidom.parse(open(filename, "r"))
for n in d.getElementsByTagName("property"):
name = n.getAttribute("name")
text = n.getAttribute('value')
if name == "version":
version = eval(text)
elif name == "always_shortcut":
short = eval(text)
elif name == "always_link":
link = eval(text)
elif name == "use_ini_substitution":
self.widgets.useinisubstitution.set_active(eval(text))
elif name == "show_advanced_pages":
show_pages = eval(text)
elif name == "machinename":
self.d._lastconfigname = text
elif name == "chooselastconfig":
self.d._chooselastconfig = eval(text)
elif name == "MESABLACKLIST":
if version == self.d._preference_version:
self._p.MESABLACKLIST = eval(text)
elif name == "EXTRA_MESA_FIRMWAREDATA":
self.d._customfirmwarefilename = text
rcfile = os.path.expanduser(self.d._customfirmwarefilename)
print rcfile
if os.path.exists(rcfile):
try:
execfile(rcfile)
except:
print _("**** PNCCONF ERROR: custom firmware loading error")
self._p.EXTRA_MESA_FIRMWAREDATA = []
if not self._p.EXTRA_MESA_FIRMWAREDATA == []:
print _("**** PNCCONF INFO: Found extra firmware in file")
# these are set from the hidden preference file
self.widgets.createsymlink.set_active(link)
self.widgets.createshortcut.set_active(short)
self.widgets.advancedconfig.set_active(show_pages)
tempfile = os.path.join(self._p.DISTDIR, "configurable_options/ladder/TEMP.clp")
if os.path.exists(tempfile):
os.remove(tempfile)
def add_placeholder_page(self,name):
string = '''
<?xml version="1.0"?>
<interface>
<requires lib="gtk+" version="2.16"/>
<!-- interface-naming-policy project-wide -->
<object class="GtkLabel" id="label_%s">
<property name="visible">True</property>
<property name="label" translatable="yes">%s</property>
</object>
</interface>
'''%(name,name)
self.builder.add_from_string(string)
# build functions
def makedirs(self, path):
makedirs(path)
def build_base(self):
base = os.path.expanduser("~/linuxcnc/configs/%s" % self.d.machinename)
ncfiles = os.path.expanduser("~/linuxcnc/nc_files")
if not os.path.exists(ncfiles):
self.makedirs(ncfiles)
examples = os.path.join(BASE, "share", "linuxcnc", "ncfiles")
if not os.path.exists(examples):
examples = os.path.join(BASE, "nc_files")
if os.path.exists(examples):
os.symlink(examples, os.path.join(ncfiles, "examples"))
self.makedirs(base)
return base
def copy(self, base, filename):
dest = os.path.join(base, filename)
if not os.path.exists(dest):
shutil.copy(os.path.join(self._p.DISTDIR, filename), dest)
def buid_config(self):
base = self.build_base()
self.d.save(base)
#self.write_readme(base)
self.INI.write_inifile(base)
self.HAL.write_halfile(base)
self.copy(base, "tool.tbl")
if self.warning_dialog(self._p.MESS_QUIT,False):
gtk.main_quit()
# helper functions
def get_discovery_meta(self):
self.widgets.boarddiscoverydialog.set_title(_("Discovery metadata update"))
#self.widgets.cardname_label.set_text('Boardname: %s'%name)
self.widgets.boarddiscoverydialog.show_all()
self.widgets.window1.set_sensitive(0)
result = self.widgets.boarddiscoverydialog.run()
self.widgets.boarddiscoverydialog.hide()
self.widgets.window1.set_sensitive(1)
if result == gtk.RESPONSE_OK:
n = self.widgets.discovery_name_entry.get_text()
itr = self.widgets.discovery_interface_combobox.get_active_iter()
d = self.widgets.discovery_interface_combobox.get_model().get_value(itr, 1)
a = self.widgets.discovery_address_entry.get_text()
print 'discovery:',n,d,a
return n,d,a
def discovery_interface_combobox_changed(self,w):
itr = w.get_active_iter()
d = w.get_model().get_value(itr, 1)
if d == '--addr':
self.widgets.discovery_address_entry.set_sensitive(True)
else:
self.widgets.discovery_address_entry.set_sensitive(False)
def get_board_meta(self, name):
name = name.lower()
meta = _PD.MESA_BOARD_META.get(name)
if meta:
return meta
else:
for key in _PD.MESA_BOARD_META:
if key in name:
return _PD.MESA_BOARD_META.get(key)
print 'boardname %s not found in hardware metadata array'% name
self.widgets.boardmetadialog.set_title(_("%s metadata update") % name)
self.widgets.cardname_label.set_text('Boardname: %s'%name)
self.widgets.boardmetadialog.show_all()
self.widgets.window1.set_sensitive(0)
result = self.widgets.boardmetadialog.run()
self.widgets.boardmetadialog.hide()
self.widgets.window1.set_sensitive(1)
if result == gtk.RESPONSE_OK:
itr = self.widgets.interface_combobox.get_active_iter()
d = self.widgets.interface_combobox.get_model().get_value(itr, 1)
ppc = int(self.widgets.ppc_combobox.get_active_text())
tp = int(self.widgets.noc_spinbutton.get_value())
_PD.MESA_BOARD_META[name] = {'DRIVER':d,'PINS_PER_CONNECTOR':ppc,'TOTAL_CONNECTORS':tp}
meta = _PD.MESA_BOARD_META.get(name)
if meta:
return meta
def splash_screen(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_SPLASHSCREEN)
self.window.set_title(_("Pncconf setup"))
self.window.set_border_width(10)
vbox = gtk.VBox(False, 5)
vbox.set_border_width(10)
self.window.add(vbox)
vbox.show()
align = gtk.Alignment(0.5, 0.5, 0, 0)
vbox.pack_start(align, False, False, 5)
align.show()
self.pbar = gtk.ProgressBar()
self.pbar.set_text(_("Pncconf is setting up"))
self.pbar.set_fraction(.1)
align.add(self.pbar)
self.pbar.show()
self.window.show()
while gtk.events_pending():
gtk.main_iteration()
def dbg(self,message,mtype='all'):
for hint in _DEBUGSTRING:
if "all" in hint or mtype in hint:
print(message)
if "step" in _DEBUGSTRING:
c = raw_input(_("\n**** Debug Pause! ****"))
return
def query_dialog(self,title, message):
def responseToDialog(entry, dialog, response):
dialog.response(response)
label = gtk.Label(message)
#label.modify_font(pango.FontDescription("sans 20"))
entry = gtk.Entry()
dialog = gtk.MessageDialog(self.widgets.window1,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK_CANCEL, title)
dialog.vbox.pack_start(label)
dialog.vbox.add(entry)
#allow the user to press enter to do ok
entry.connect("activate", responseToDialog, dialog, gtk.RESPONSE_OK)
dialog.show_all()
result = dialog.run()
text = entry.get_text()
dialog.destroy()
if result == gtk.RESPONSE_OK:
return text
else:
return None
def warning_dialog(self,message,is_ok_type):
if is_ok_type:
dialog = gtk.MessageDialog(self.widgets.window1,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK,message)
dialog.show_all()
result = dialog.run()
dialog.destroy()
return True
else:
dialog = gtk.MessageDialog(self.widgets.window1,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,message)
dialog.show_all()
result = dialog.run()
dialog.destroy()
if result == gtk.RESPONSE_YES:
return True
else:
return False
def show_help(self):
helpfilename = os.path.join(self._p.HELPDIR, "%s"% self.d.help)
textbuffer = self.widgets.helpview.get_buffer()
try :
infile = open(helpfilename, "r")
if infile:
string = infile.read()
infile.close()
textbuffer.set_text(string)
except:
text = _("Specific Help page is unavailable\n")
self.warning_dialog(text,True)
self.widgets.help_window.set_title(_("Help Pages") )
self.widgets.helpnotebook.set_current_page(0)
self.widgets.help_window.show_all()
if self.debugstate:
self.widgets.input_tab.set_visible(True)
else:
self.widgets.input_tab.set_visible(False)
self.widgets.help_window.present()
def print_page(self,print_dialog, context, n, imagename):
ctx = context.get_cairo_context()
gdkcr = gtk.gdk.CairoContext(ctx)
gdkcr.set_source_pixbuf(self[imagename], 0,0)
gdkcr.paint ()
def print_image(self,image_name):
print 'print image'
print_dialog = gtk.PrintOperation()
print_dialog.set_n_pages(1)
settings = gtk.PrintSettings()
settings.set_orientation(gtk.PAGE_ORIENTATION_LANDSCAPE)
print_dialog.set_print_settings(settings)
print_dialog.connect("draw-page", self.print_page, image_name)
res = print_dialog.run(gtk.PRINT_OPERATION_ACTION_PRINT_DIALOG, self.widgets.help_window)
if res == gtk.PRINT_OPERATION_RESULT_APPLY:
settings = print_dialog.get_print_settings()
# check for realtime kernel
def check_for_rt(self):
actual_kernel = os.uname()[2]
if hal.is_sim :
self.warning_dialog(self._p.MESS_NO_REALTIME,True)
if self.debugstate:
return True
else:
return False
elif hal.is_kernelspace and hal.kernel_version != actual_kernel:
self.warning_dialog(self._p.MESS_KERNEL_WRONG + '%s'%hal.kernel_version,True)
if self.debugstate:
return True
else:
return False
else:
return True
def add_external_folder_boardnames(self):
if os.path.exists(self._p.FIRMDIR):
self._p.MESA_BOARDNAMES = []
for root, dirs, files in os.walk(self._p.FIRMDIR):
folder = root.lstrip(self._p.FIRMDIR)
if folder in self._p.MESABLACKLIST:continue
if folder == "":continue
dbg("****folder added :%s"%folder,mtype='firmware')
self._p.MESA_BOARDNAMES.append(folder)
else:
#TODO what if there are no external firmware is this enough?
self.warning_dialog(_("You have no hostmot2 firmware downloaded in folder:\n%s\n\
PNCconf will use internal firmware data"%self._p.FIRMDIR),True)
for firmware in self._p.MESA_INTERNAL_FIRMWAREDATA:
if 'internal' in firmware[0].lower():
if firmware[0] in self._p.MESA_BOARDNAMES:
continue
self._p.MESA_BOARDNAMES.append(firmware[0])
if self.d.advanced_option:
self._p.MESA_BOARDNAMES.append('Discovery Option')
# add any extra firmware boardnames from .pncconf-preference file
if not self._p.EXTRA_MESA_FIRMWAREDATA == []:
for search, item in enumerate(self._p.EXTRA_MESA_FIRMWAREDATA):
d = self._p.EXTRA_MESA_FIRMWAREDATA[search]
if not d[_PD._BOARDTITLE] in self._p.MESA_BOARDNAMES:
self._p.MESA_BOARDNAMES.append(d[_PD._BOARDTITLE])
model = self.widgets.mesa_boardname_store
model.clear()
for search,item in enumerate(self._p.MESA_BOARDNAMES):
#print search,item
model.append((item,))
def fill_pintype_model(self):
# notused
self.d._notusedliststore = gtk.ListStore(str,int)
self.d._notusedliststore.append([_PD.pintype_notused[0],0])
self.d._ssrliststore = gtk.ListStore(str,int)
self.d._ssrliststore.append([_PD.pintype_ssr[0],0])
# gpio
self.d._gpioliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_gpio):
self.d._gpioliststore.append([text,0])
# stepper
self.d._stepperliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_stepper):
self.d._stepperliststore.append([text,number])
# encoder
self.d._encoderliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_encoder):
self.d._encoderliststore.append([text,number])
# mux encoder
self.d._muxencoderliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_muxencoder):
self.d._muxencoderliststore.append([text,number])
# resolver
self.d._resolverliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_resolver):
self.d._resolverliststore.append([text,number])
# 8i20 AMP
self.d._8i20liststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_8i20):
self.d._8i20liststore.append([text,number])
# potentiometer output
self.d._potliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_potentiometer):
self.d._potliststore.append([text,number])
# analog input
self.d._analoginliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_analog_in):
self.d._analoginliststore.append([text,number])
# pwm
self.d._pwmrelatedliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_pwm):
self.d._pwmrelatedliststore.append([text,number])
self.d._pwmcontrolliststore = gtk.ListStore(str,int)
self.d._pwmcontrolliststore.append([_PD.pintype_pwm[0],0])
self.d._pwmcontrolliststore.append([_PD.pintype_pdm[0],0])
self.d._pwmcontrolliststore.append([_PD.pintype_udm[0],0])
# pdm
self.d._pdmrelatedliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_pdm):
self.d._pdmrelatedliststore.append([text,number])
self.d._pdmcontrolliststore = gtk.ListStore(str,int)
self.d._pdmcontrolliststore.append([_PD.pintype_pwm[0],0])
self.d._pdmcontrolliststore.append([_PD.pintype_pdm[0],0])
self.d._pdmcontrolliststore.append([_PD.pintype_udm[0],0])
# udm
self.d._udmrelatedliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_udm):
self.d._udmrelatedliststore.append([text,number])
self.d._udmcontrolliststore = gtk.ListStore(str,int)
self.d._udmcontrolliststore.append([_PD.pintype_pwm[0],0])
self.d._udmcontrolliststore.append([_PD.pintype_pdm[0],0])
self.d._udmcontrolliststore.append([_PD.pintype_udm[0],0])
#tppwm
self.d._tppwmliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_tp_pwm):
self.d._tppwmliststore.append([text,number])
#sserial
self.d._sserialliststore = gtk.ListStore(str,int)
for number,text in enumerate(_PD.pintype_sserial):
self.d._sserialliststore.append([text,number])
# comboboxes with 3 levels
def fill_combobox_models2(self):
templist = [ ["_gpioisignaltree",_PD.human_input_names,1,'hal_input_names'],
["_steppersignaltree",_PD.human_stepper_names,1,'hal_stepper_names'],
["_encodersignaltree",_PD.human_encoder_input_names,1,'hal_encoder_input_names'],
["_muxencodersignaltree",_PD.human_encoder_input_names,1,'hal_encoder_input_names'],
["_pwmsignaltree",_PD.human_pwm_output_names,1,'hal_pwm_output_names'],]
for item in templist:
#print "\ntype",item[0]
count = 0
end = len(item[1])-1
# treestore(parentname,parentnum,signalname,signaltreename,signal index number)
self.d[item[0]]= gtk.TreeStore(str,int,str,str,int)
for i,parent in enumerate(item[1]):
############################
# if there are no children:
############################
if not isinstance(parent[1], list):
signame = parent[1]
index = _PD[item[3]].index(parent[1])
#print 'no children:', signame, index
# add parent and get reference for child
# This entry is selectable it has a signal attached to it
piter = self.d[item[0]].append(None, [parent[0], index,signame,item[3],0])
#print parent,parentnum,count,signame,item[3],i,signame,count
else:
# If list is empty it's a custome signal - with no signals yet
if len(parent[1]) == 0:
piter = self.d[item[0]].append(None, [parent[0], 0,'none',item[3],0])
else:
#print "parsing child",parent[1]
# add parent title
##########################
# if there are children:
# add an entry to first list that cannot be selected
# (well it always gives the unused signal - 0)
# because we need users to select from the next column
##########################
piter = self.d[item[0]].append(None, [parent[0],0,signame,item[3],0])
for j,child in enumerate(parent[1]):
#############################
# If grandchildren
#############################
if isinstance(child[1], list):
##########################
# if there are children:
# add an entry to second list that cannot be selected
# (well it always gives the unused signal - 0)
# because we need users to select from the next column
##########################
citer = self.d[item[0]].append(piter, [child[0], 0,signame,item[3],0])
#print 'add to CHILD list',child[0]
#print 'String:',child[1]
for k,grandchild in enumerate(child[1]):
#print 'raw grand: ', grandchild
#############################
# If GREAT children
#############################
#print grandchild[0],grandchild[1]
if isinstance(grandchild[1], list):
#print 'ERROR combo boxes can not have GREAT children yet add'
#print 'skipping'
continue
else:
#############################
# If No GREAT children
############################
humanName = grandchild[0]
sigName = grandchild[1]
index = _PD[item[3]].index(grandchild[1])
halNameArray = item[3]
#print 'adding to grandchild to childlist: ', humanName,index,sigName,halNameArray,index
self.d[item[0]].append(citer, [humanName, index,sigName,halNameArray,index])
####################
# No grandchildren
####################
else:
#print' add to child - no grandchild',child
humanName = child[0]
sigName = child[1]
index = _PD[item[3]].index(child[1])
halNameArray = item[3]
#print child[0],index,sigName,item[3],index
self.d[item[0]].append(piter, [humanName, index,sigName,halNameArray,index])
count +=item[2]
# combobox with 2 levels
def fill_combobox_models(self):
templist = [ ["_gpioosignaltree",_PD.human_output_names,1,'hal_output_names'],
["_resolversignaltree",_PD.human_resolver_input_names,1,'hal_resolver_input_names'],
["_tppwmsignaltree",_PD.human_tppwm_output_names,8,'hal_tppwm_output_names'],
["_8i20signaltree",_PD.human_8i20_input_names,1,'hal_8i20_input_names'],
["_potsignaltree",_PD.human_pot_output_names,2,'hal_pot_output_names'],
["_analoginsignaltree",_PD.human_analog_input_names,1,'hal_analog_input_names'],
["_sserialsignaltree",_PD.human_sserial_names,3,'hal_sserial_names']
]
for item in templist:
#print "\ntype",item[0]
count = 0
end = len(item[1])-1
# treestore(parentname,parentnum,signalname,signaltreename,signal index number)
self.d[item[0]]= gtk.TreeStore(str,int,str,str,int)
for i,parent in enumerate(item[1]):
############################
# if there are no children:
############################
if len(parent[1]) == 0:
# if combobox has a 'custom' signal choice then the index must be 0
if i == end and not item[0] =="_sserialsignaltree":parentnum = 0
else:parentnum = count
#print "length of human names:",len(parent[1])
# this adds the index number (parentnum) of the signal
try:
signame=_PD[item[3]][count]
except:
signame = 'none'
# add parent and get reference for child
piter = self.d[item[0]].append(None, [parent[0], parentnum,signame,item[3],count])
#print parent,parentnum,count,signame,item[3],i,signame,count
if count == 0: count = 1
else: count +=item[2]
##########################
# if there are children:
##########################
else:
#print "parsing child",signame
# add parent title
piter = self.d[item[0]].append(None, [parent[0],0,signame,item[3],count])
for j,child in enumerate(parent[1]):
#print len(child[1]), child[0]
#if item[0] =='_gpioisignaltree':
#print item[0], child[0],len(child[1])
#############################
# If grandchildren
#############################
if len(child[1]) > 1:
# add child and get reference
citer = self.d[item[0]].append(piter, [child[0], 0,signame,item[3],count])
#if item[0] =='_gpioisignaltree':
#print 'add to CHILD list',child[0]
#print 'Strig:',child[1]
for k,grandchild in enumerate(child[1]):
#print 'raw grand: ', grandchild
#############################
# If greatchildren
#############################
#print grandchild[0],grandchild[1]
if len(grandchild) > 1:
#print 'add to grandchild child list',grandchild[0]
index = _PD[item[3]].index(grandchild[1])
self.d[item[0]].append(citer, [grandchild[0],index,grandchild[1],item[3],index])
continue
else:
#############################
# If No greatchildren
#############################
try:
signame=_PD[item[3]][count]
except:
signame = 'none'
#print 'adding to grandchild to childlist: ', grandchild,signame,item[3],count
# add grandchild
self.d[item[0]].append(piter, [child,0,signame,item[3],count])
#count +=item[2]
####################
# No grandchildren
####################
else:
#print' add to child - no grandchild',child
signame=_PD[item[3]][count]
#print i,count,parent[0],child,signame,item[3], _PD[item[3]].index(signame),count
self.d[item[0]].append(piter, [child, count,signame,item[3],count])
count +=item[2]
self.fill_combobox_models2()
self.d._notusedsignaltree = gtk.TreeStore(str,int,str,str,int)
self.d._notusedsignaltree.append(None, [_PD.human_notused_names[0][0],0,'unused-unused','_notusedsignaltree',0])
# make a filter for sserial encoder as they can't be used for AXES
self.d._encodersignalfilter = self.d._encodersignaltree.filter_new()
self.d._enc_filter_list = ['Axis Encoder']
self.d._encodersignalfilter.set_visible_func(self.visible_cb, self.d._enc_filter_list)
# build filters for the 'controlling' sserial combbox
# We need to limit selections often
for channel in range(0,_PD._NUM_CHANNELS):
self.d['_sserial%d_filter_list'%channel] =[]
self.d['_sserial%d_signalfilter'%channel] = self.d._sserialsignaltree.filter_new()
self.d['_sserial%d_signalfilter'%channel].set_visible_func(self.filter_cb,self.d['_sserial%d_filter_list'%channel])
self.set_filter('_sserial%d'%channel,'ALL')
# Filter out any matching names in a list
def visible_cb(self, model, iter, data ):
#print model.get_value(iter, 0) ,data
return not model.get_value(iter, 0) in data
# filter out anything not in one of the lists, the list depending on a keyword
def set_filter(self,sserial,data):
keyword = data.upper()
if keyword == '7I77':
f_list = ['Unused','7i77']
elif keyword == '7I76':
f_list = ['Unused','7i76']
else:
f_list = ['Unused','7i73','7i69','8i20','7i64','7i71','7i70','7i84']
del self.d['%s_filter_list'%sserial][:]
for i in(f_list):
self.d['%s_filter_list'%sserial].append(i)
#print '\n',filterlist,self.d[filterlist]
self.d['%s_signalfilter'%sserial].refilter()
# Filter callback
def filter_cb(self, model, iter, data ):
#print model.get_value(iter, 0) ,data
for i in data:
if i in model.get_value(iter, 0):
return True
return False
def load_config(self):
filter = gtk.FileFilter()
filter.add_pattern("*.pncconf")
filter.set_name(_("LinuxCNC 'PNCconf' configuration files"))
dialog = gtk.FileChooserDialog(_("Modify Existing Configuration"),
self.widgets.window1, gtk.FILE_CHOOSER_ACTION_OPEN,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.add_filter(filter)
if not self.d._lastconfigname == "" and self.d._chooselastconfig:
dialog.set_filename(os.path.expanduser("~/linuxcnc/configs/%s.pncconf"% self.d._lastconfigname))
dialog.add_shortcut_folder(os.path.expanduser("~/linuxcnc/configs"))
dialog.set_current_folder(os.path.expanduser("~/linuxcnc/configs"))
dialog.show_all()
result = dialog.run()
if result == gtk.RESPONSE_OK:
filename = dialog.get_filename()
dialog.destroy()
self.d.load(filename, self)
self.d._mesa0_configured = False
self.d._mesa1_configured = False
try:
# check that the firmware is current enough by checking the length of a sub element and that the other is an integer.
for boardnum in(0,1):
i=j=None
i = len(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS])
j = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._HIFREQ]+100 # throws an error if not an integer.
if not i > 1:
print i,j,boardnum
raise UserWarning
except :
print i,j,boardnum
self.warning_dialog(_("It seems data in this file is from too old of a version of PNCConf to continue.\n."),True)
return True
else:
dialog.destroy()
return True
def mesa_firmware_search(self,boardtitle,*args):
#TODO if no firm packages set up for internal data?
#TODO don't do this if the firmware is already loaded
self.pbar.set_text("Loading external firmware")
self.pbar.set_fraction(0)
self.window.show()
while gtk.events_pending():
gtk.main_iteration()
firmlist = []
for root, dirs, files in os.walk(self._p.FIRMDIR):
folder = root.lstrip(self._p.FIRMDIR)
#dbg('Firmware folder:%s'% folder)
if folder in self._p.MESABLACKLIST:continue
if not folder == boardtitle:continue
for n,name in enumerate(files):
if name in self._p.MESABLACKLIST:continue
if ".xml" in name:
dbg('%s'% name)
temp = name.rstrip(".xml")
firmlist.append(temp)
dbg("\nXML list:%s"%firmlist,mtype="firmname")
for n,currentfirm in enumerate(firmlist):
self.pbar.set_fraction(n*1.0/len(firmlist))
while gtk.events_pending():
gtk.main_iteration()
# XMLs don't tell us the driver type so set to None (parse will guess)
firmdata = self.parse_xml(None,boardtitle, currentfirm,os.path.join(
self._p.FIRMDIR,boardtitle,currentfirm+".xml"))
self._p.MESA_FIRMWAREDATA.append(firmdata)
self.window.hide()
def parse_xml(self, driver, boardtitle, firmname, xml_path):
def search(elementlist):
for i in elementlist:
temp = root.find(i)
if temp is not None:
return temp.text
return temp
root = xml.etree.ElementTree.parse(xml_path)
watchdog = encoder = resolver = pwmgen = led = muxedqcount = 0
stepgen = tppwmgen = sserialports = sserialchannels = 0
numencoderpins = numpwmpins = 3; numstepperpins = 2; numttpwmpins = 0; numresolverpins = 10
text = search(('boardname','BOARDNAME'))
if text == None:
print 'Missing info: boardname'
return
boardname = text.lower()
#dbg("\nBoard and firmwarename: %s %s\n"%( boardname, firmname), "firmraw")
text = search(("IOPORTS","ioports")) ; #print numcnctrs
if text == None:
print 'Missing info: ioports'
return
numcnctrs = int(text)
text = search(("PORTWIDTH","portwidth"))
if text == None:
print 'Missing info: portwidth'
return
portwidth = int(text)
maxgpio = numcnctrs * portwidth ; #print maxgpio
placeholders = 24-portwidth
text = search(("CLOCKLOW","clocklow")) ; #print lowfreq
if text == None:
print 'Missing info: clocklow'
return
lowfreq = int(text)/1000000
text = search(("CLOCKHIGH","clockhigh")); #print hifreq
if text == None:
print 'Missing info: clockhigh'
return
hifreq = int(text)/1000000
modules = root.findall(".//modules")[0]
if driver == None:
meta = self.get_board_meta(boardname)
driver = meta.get('DRIVER')
for i,j in enumerate(modules):
k = modules[i].find("tagname").text
print k
if k in ("Watchdog","WatchDog","WATCHDOG"):
l = modules[i].find("numinstances").text;#print l,k
watchdog = int(l)
elif k in ("Encoder","QCOUNT"):
l = modules[i].find("numinstances").text;#print l,k
encoder = int(l)
elif k in ("ResolverMod","RESOLVERMOD"):
l = modules[i].find("numinstances").text;#print l,k
resolver = int(l)
elif k in ("PWMGen","PWMGEN","PWM"):
l = modules[i].find("numinstances").text;#print l,k
pwmgen = int(l)
elif k == "LED":
l = modules[i].find("numinstances").text;#print l,k
led = int(l)
elif k in ("MuxedQCount","MUXEDQCOUNT"):
l = modules[i].find("numinstances").text;#print l,k
muxedqcount = int(l)
elif k in ("StepGen","STEPGEN"):
l = modules[i].find("numinstances").text;#print l,k
stepgen = int(l)
elif k in ("TPPWM","TPPWM"):
l = modules[i].find("numinstances").text;#print l,k
tppwmgen = int(l)
elif k in ("SSerial","SSERIAL"):
l = modules[i].find("numinstances").text;#print l,k
sserialports = int(l)
elif k in ("None","NONE"):
l = modules[i].find("numinstances").text;#print l,k
elif k in ("ssr","SSR"):
l = modules[i].find("numinstances").text;#print l,k
elif k in ("IOPort","AddrX","MuxedQCountSel"):
continue
else:
print "**** WARNING: Pncconf parsing firmware: tagname (%s) not reconized"% k
discov_sserial = []
ssname = root.findall("SSERIALDEVICES/SSERIALFUNCTION")
for i in (ssname):
port = i.find("PORT").text
dev = i.find("DEVICE").text
chan = i.find("CHANNEL").text
discov_sserial.append((int(port),int(chan),dev))
print 'discovered sserial:', discov_sserial
pins = root.findall(".//pins")[0]
temppinlist = []
tempconlist = []
pinconvertenc = {"PHASE A":_PD.ENCA,"PHASE B":_PD.ENCB,"INDEX":_PD.ENCI,"INDEXMASK":_PD.ENCM,
"QUAD-A":_PD.ENCA,"QUAD-B":_PD.ENCB,"QUAD-IDX":_PD.ENCI,
"MUXED PHASE A":_PD.MXE0,"MUXED PHASE B":_PD.MXE1,"MUXED INDEX":_PD.MXEI,
"MUXED INDEX MASK":_PD.MXEM,"MUXED ENCODER SELECT 0":_PD.MXES,"MUXED ENCODER SELEC":_PD.MXES,
"MUXQ-A":_PD.MXE0,"MUXQ-B":_PD.MXE1,"MUXQ-IDX":_PD.MXEI,"MUXSEL0":_PD.MXES}
pinconvertresolver = {"RESOLVER POWER ENABLE":_PD.RESU,"RESOLVER SPIDI 0":_PD.RES0,
"RESOLVER SPIDI 1":_PD.RES1,"RESOLVER ADC CHANNEL 2":_PD.RES2,"RESOLVER ADC CHANNEL 1":_PD.RES3,
"RESOLVER ADC CHANNEL 0":_PD.RES4,"RESOLVER SPI CLK":_PD.RES5,"RESOLVER SPI CHIP SELECT":_PD.RESU,
"RESOLVER PDMM":_PD.RESU,"RESOLVER PDMP":_PD.RESU}
pinconvertstep = {"STEP":_PD.STEPA,"DIR":_PD.STEPB,"STEP/TABLE1":_PD.STEPA,"DIR/TABLE2":_PD.STEPB}
#"StepTable 2":STEPC,"StepTable 3":STEPD,"StepTable 4":STEPE,"StepTable 5":STEPF
pinconvertppwm = {"PWM/UP":_PD.PWMP,"DIR/DOWN":_PD.PWMD,"ENABLE":_PD.PWME,
"PWM":_PD.PWMP,"DIR":_PD.PWMD,"/ENABLE":_PD.PWME}
pinconverttppwm = {"PWM A":_PD.TPPWMA,"PWM B":_PD.TPPWMB,"PWM C":_PD.TPPWMC,
"PWM /A":_PD.TPPWMAN,"PWM /B":_PD.TPPWMBN,"PWM /C":_PD.TPPWMCN,
"FAULT":_PD.TPPWMF,"ENABLE":_PD.TPPWME}
pinconvertsserial = {"RXDATA0":_PD.RXDATA0,"TXDATA0":_PD.TXDATA0,"TXE0":_PD.TXEN0,"TXEN0":_PD.TXEN0,
"RXDATA1":_PD.RXDATA0,"TXDATA1":_PD.TXDATA0,"TXE1":_PD.TXEN0,"TXEN1":_PD.TXEN0,
"RXDATA2":_PD.RXDATA1,"TXDATA2":_PD.TXDATA1,"TXE2":_PD.TXEN1,"TXEN2":_PD.TXEN1,
"RXDATA3":_PD.RXDATA2,"TXDATA3":_PD.TXDATA2,"TXE3":_PD.TXEN2,"TXEN3":_PD.TXEN2,
"RXDATA4":_PD.RXDATA3,"TXDATA4":_PD.TXDATA3,"TXE4":_PD.TXEN3,"TXEN4":_PD.TXEN3,
"RXDATA5":_PD.RXDATA4,"TXDATA5":_PD.TXDATA4,"TXE5":_PD.TXEN4,"TXEN4":_PD.TXEN4,
"RXDATA6":_PD.RXDATA5,"TXDATA6":_PD.TXDATA5,"TXE6":_PD.TXEN5,"TXEN6":_PD.TXEN5,
"RXDATA7":_PD.RXDATA6,"TXDATA7":_PD.TXDATA6,"TXE7":_PD.TXEN6,"TXEN7":_PD.TXEN6,
"RXDATA8":_PD.RXDATA7,"TXDATA8":_PD.TXDATA7,"TXE8":_PD.TXEN7,"TXEN8":_PD.TXEN7}
pinconvertnone = {"NOT USED":_PD.GPIOI}
count = 0
fakecon = 0
for i,j in enumerate(pins):
instance_num = 9999
iocode = None
temppinunit = []
temp = pins[i].find("connector").text
if 'P' in temp:
tempcon = int(temp.strip("P"))
else:
tempcon = temp
tempfunc = pins[i].find("secondaryfunctionname").text
tempfunc = tempfunc.upper().strip() # normalise capitalization: Peters XMLs are different from linuxcncs
if "(IN)" in tempfunc:
tempfunc = tempfunc.rstrip(" (IN)")
elif "(OUT" in tempfunc:
tempfunc = tempfunc.rstrip(" (OUT)")
convertedname = "Not Converted"
# this converts the XML file componennt names to pncconf's names
try:
secmodname = pins[i].find("secondarymodulename")
modulename = secmodname.text.upper().strip()
dbg("secondary modulename: %s, %s."%( tempfunc,modulename), "firmraw")
if modulename in ("ENCODER","QCOUNT","MUXEDQCOUNT","MUXEDQCOUNTSEL"):
convertedname = pinconvertenc[tempfunc]
elif modulename in ("ResolverMod","RESOLVERMOD"):
convertedname = pinconvertresolver[tempfunc]
elif modulename in ("PWMGen","PWMGEN","PWM"):
convertedname = pinconvertppwm[tempfunc]
elif modulename in ("StepGen","STEPGEN"):
convertedname = pinconvertstep[tempfunc]
elif modulename in ("TPPWM","TPPWM"):
convertedname = pinconverttppwm[tempfunc]
elif modulename in ("SSerial","SSERIAL"):
temp = pins[i].find("foundsserialdevice")
if temp is not None:
founddevice = temp.text.upper()
else:
founddevice = None
#print tempfunc,founddevice
# this auto selects the sserial 7i76 mode 0 card for sserial 0 and 2
# as the 5i25/7i76 uses some of the sserial channels for it's pins.
if boardname in ("5i25","7i92"):
if "7i77_7i76" in firmname:
if tempfunc == "TXDATA1": convertedname = _PD.SS7I77M0
elif tempfunc == "TXDATA2": convertedname = _PD.SS7I77M1
elif tempfunc == "TXDATA4": convertedname = _PD.SS7I76M3
else: convertedname = pinconvertsserial[tempfunc]
#print "XML ",firmname, tempfunc,convertedname
elif "7i76x2" in firmname or "7i76x1" in firmname:
if tempfunc == "TXDATA1": convertedname = _PD.SS7I76M0
elif tempfunc == "TXDATA3": convertedname = _PD.SS7I76M2
else: convertedname = pinconvertsserial[tempfunc]
#print "XML ",firmname, tempfunc,convertedname
elif "7i77x2" in firmname or "7i77x1" in firmname:
if tempfunc == "TXDATA1": convertedname = _PD.SS7I77M0
elif tempfunc == "TXDATA2": convertedname = _PD.SS7I77M1
elif tempfunc == "TXDATA4": convertedname = _PD.SS7I77M3
elif tempfunc == "TXDATA5": convertedname = _PD.SS7I77M4
else: convertedname = pinconvertsserial[tempfunc]
#print "XML ",firmname, tempfunc,convertedname
elif founddevice == "7I77-0": convertedname = _PD.SS7I77M0
elif founddevice == "7I77-1": convertedname = _PD.SS7I77M1
elif founddevice == "7I77-3": convertedname = _PD.SS7I77M3
elif founddevice == "7I77-4": convertedname = _PD.SS7I77M4
elif founddevice == "7I76-0": convertedname = _PD.SS7I76M0
elif founddevice == "7I76-2": convertedname = _PD.SS7I76M2
elif founddevice == "7I76-3": convertedname = _PD.SS7I76M3
else: convertedname = pinconvertsserial[tempfunc]
else:
convertedname = pinconvertsserial[tempfunc]
elif modulename in ('SSR','SSR'):
if tempfunc == 'AC':
convertedname = _PD.NUSED
elif 'OUT-' in tempfunc:
convertedname = _PD.SSR0
# ssr outputs encode the HAL number in the XML name
# add it to 100 so it's not change from output
iocode = 100 + int(tempfunc[4:])
elif modulename in ("None","NONE"):
iocode = 0
#convertedname = pinconvertnone[tempfunc]
else:
print 'unknon module - setting to unusable',modulename, tempfunc
convertedname = _PD.NUSED
except:
iocode = 0
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted_lines = traceback.format_exc().splitlines()
print
print "****pncconf verbose XML parse debugging:",formatted_lines[0]
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print formatted_lines[-1]
if iocode == 0:
# must be GPIO pins if there is no secondary mudule name
# or if pinconvert fails eg. StepTable instance default to GPIO
temppinunit.append(_PD.GPIOI)
temppinunit.append(0) # 0 signals to pncconf that GPIO can changed to be input or output
elif iocode >= 100:
temppinunit.append(_PD.SSR0)
temppinunit.append(iocode)
else:
instance_num = int(pins[i].find("secondaryinstance").text)
# this is a workaround for the 7i77_7i776 firmware. it uses a mux encoder for the 7i76 but only uses half of it
# this is because of a limitation of hostmot2 - it can't have mux encoders and regular encoders
# so in pncconf we look for this and change it to a regular encoder.
if boardname == "5i25" and firmname == "7i77_7i76":
if modulename in ("MuxedQCount","MUXEDQCOUNT") and instance_num == 3:
instance_num = 6
encoder =-1
if convertedname == _PD.MXE0: convertedname = _PD.ENCA
elif convertedname == _PD.MXE1: convertedname = _PD.ENCB
elif convertedname == _PD.MXEI: convertedname = _PD.ENCI
temppinunit.append(convertedname)
if tempfunc in("MUXED ENCODER SELECT 0","MUXEDQCOUNTSEL") and instance_num == 6:
instance_num = 3
temppinunit.append(instance_num)
tempmod = pins[i].find("secondarymodulename").text
tempfunc = tempfunc.upper()# normalize capitalization
#dbg("secondary modulename, function: %s, %s."%( tempmod,tempfunc), "firmraw")
if tempmod in("Encoder","MuxedQCount") and tempfunc in ("MUXED INDEX MASK (IN)","INDEXMASK (IN)"):
numencoderpins = 4
if tempmod in("SSerial","SSERIAL") and tempfunc in ("TXDATA1","TXDATA2","TXDATA3",
"TXDATA4","TXDATA5","TXDATA6","TXDATA7","TXDATA8"):
sserialchannels +=1
#dbg("temp: %s, converted name: %s. num %d"%( tempfunc,convertedname,instance_num), "firmraw")
if not tempcon in tempconlist:
tempconlist.append(tempcon)
temppinlist.append(temppinunit)
# add NONE place holders for boards with less then 24 pins per connector.
if not placeholders == 0:
#print i,portwidth*numcnctrs
if i == (portwidth + count-1) or i == portwidth*numcnctrs-1:
#print "loop %d %d"% (i,portwidth + count-1)
count =+ portwidth
#print "count %d" % count
for k in range(0,placeholders):
#print "%d fill here with %d parts"% (k,placeholders)
temppinlist.append((_PD.NUSED,0))
if not sserialchannels == 0:
sserialchannels +=1
# 7i96 doesn't number the connectors with P numbers so we fake it
# TODO
# probably should move the connector numbers to board data rather then firmware
for j in tempconlist:
if not isinstance(j, (int, long)):
tempconlist = [i for i in range(1,len(tempconlist)+1)]
break
temp = [boardtitle,boardname,firmname,boardtitle,driver,encoder + muxedqcount,
numencoderpins,resolver,numresolverpins,pwmgen,numpwmpins,
tppwmgen,numttpwmpins,stepgen,numstepperpins,
sserialports,sserialchannels,discov_sserial,0,0,0,0,0,0,0,watchdog,maxgpio,
lowfreq,hifreq,tempconlist]
for i in temppinlist:
temp.append(i)
if "5i25" in boardname :
dbg("5i25 firmware:\n%s\n"%( temp), mtype="5i25")
print 'firm added:\n',temp
return temp
def discover_mesacards(self):
name, interface, address = self.get_discovery_meta()
if name is None: return
if not name:
name = '5i25'
if self.debugstate:
print 'try to discover board by reading help text input:',name
buf = self.widgets.textinput.get_buffer()
info = buf.get_text(buf.get_start_iter(),
buf.get_end_iter(),
True)
else:
info = self.call_mesaflash(name,interface,address)
print 'INFO:',info,'<-'
if info is None: return None
lines = info.splitlines()
try:
if 'ERROR' in lines[0]:
raise ValueError('Mesaflash Error')
except ValueError as err:
text = err.args
self.warning_dialog(text[0],True)
return
except:
self.warning_dialog('Unspecified Error with Mesaflash',True)
return
if 'No' in lines[0] and 'board found' in lines[0] :
text = _("No board was found\n")
self.warning_dialog(text,True)
print 'OOPS no board found!'
return None
return info
def call_mesaflash(self, devicename, interface, address):
if address == ' ':
address = None
textbuffer = self.widgets.textoutput.get_buffer()
print 'DEVICE NAME SPECIFIED',devicename, interface, address
# 7i43 needs it's firmware loaded before it can be 'discovered'
if '7i43' in devicename.lower():
halrun = os.popen("halrun -Is > /dev/null", "w")
halrun.write("echo\n")
load,read,write = self.hostmot2_command_string()
# do I/O load commands
for i in load:
halrun.write('%s\n'%i)
halrun.flush()
time.sleep(.001)
halrun.close()
if interface == '--addr' and address:
board_command = '--device %s %s %s' %(devicename, interface, address)
elif interface == '--epp':
board_command = '--device %s %s' %(devicename, interface)
else:
board_command = '--device %s' %(devicename)
#cmd ="""pkexec "sh -c 'mesaflash %s';'mesaflash %s --sserial';'mesaflash %s --readhmid' " """%(board_command, board_command, board_command)
cmd =""" mesaflash -%s;mesaflash %s --sserial;mesaflash %s --readhmid """%(board_command, board_command, board_command)
discover = subprocess.Popen([cmd], shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE )
output, error = discover.communicate()
if output == '':
text = _("Discovery is got an error\n\n Is mesaflash installed?\n\n %s"%error)
self.warning_dialog(text,True)
try :
textbuffer.set_text('Command:\n%s\n gave:\n%s'%(cmd,error))
self.widgets.helpnotebook.set_current_page(2)
except Exception as e :
print e
return None
try :
textbuffer.set_text(output)
self.widgets.helpnotebook.set_current_page(2)
self.widgets.help_window.show_all()
except:
text = _("Discovery is unavailable\n")
self.warning_dialog(text,True)
print 'cmd=',cmd
return output
def parse_discovery(self,info,boardnum=0):
DRIVER = BOARDNAME = ''
WATCHDOG = NUMCONS = NUMCONPINS = ENCODERS = MUXENCODERS = 0
RESOLVERS = NUMSSCHANNELS = SSERIALPORTS = 0
PWMGENS = LEDS = STEPGENS = TPPWMGEN = 0
NUMENCODERPINS = NUMPWMPINS = 3; NUMSTEPPERPINS = 2
NUMTPPWMPINS = 0;NUMRESOLVERPINS = 10
DOC = xml.dom.minidom.getDOMImplementation().createDocument(
None, 'hostmot2', None)
ELEMENT = DOC.documentElement
def add_element(ELEMENT,name):
n1 = DOC.createElement(name)
ELEMENT.appendChild(n1)
return n1
def add_text(root,title,value):
n = DOC.createElement(title)
root.appendChild(n)
nodeText = DOC.createTextNode( value )
n.appendChild(nodeText)
return n
info = info.upper()
lines = info.splitlines()
sserial=[]
ssflag = pinsflag = True
dev7i77flag = dev7i76flag = False
for l_num,i in enumerate(lines):
i = i.lstrip()
temp2 = i.split(" ")
#print i,temp2
if 'ETH' in i:
DRIVER = 'hm2_eth'
if 'PCI' in i:
DRIVER = 'hm2_pci'
if 'BOARDNAME' in i:
BOARDNAME = temp2[2].strip('MESA').lower()
add_text(ELEMENT,'BOARDNAME',BOARDNAME)
if 'DEVICE AT' in i:
if ssflag:
n1 = add_element(ELEMENT,'SSERIALDEVICES')
ssflag = False
for num,i in enumerate(temp2):
if i =="CHANNEL":
sserial.append((temp2[num+1].strip(':'),temp2[num+2]))
n2 = add_element(n1,'SSERIALFUNCTION')
add_text(n2,'PORT','0')
add_text(n2,'CHANNEL',temp2[num+1].strip(':'))
add_text(n2,'DEVICE',temp2[num+2])
if '7I77' in(temp2[num+2]):
dev7i77flag = True
elif '7I76' in(temp2[num+2]):
dev7i76flag = True
if 'SSLBP CHANNELS:' in i:
NUMSSCHANNELS = temp2[2]
if 'CLOCK LOW FREQUENCY: ' in i:
add_text(ELEMENT,'CLOCKLOW',str(int(float(temp2[3])*1000000)))
if 'CLOCK HIGH FREQUENCY:' in i:
add_text(ELEMENT,'CLOCKHIGH',str(int(float(temp2[3])*1000000)))
if 'NUMBER OF IO PORTS:' in i:
NUMCONS = temp2[4]
add_text(ELEMENT,'IOPORTS',NUMCONS)
if 'WIDTH OF ONE I/O PORT:' in i:
NUMCONPINS = temp2[5]
add_text(ELEMENT,'PORTWIDTH',NUMCONPINS)
if 'MODULES IN CONFIGURATION:' in i:
mod_ele = add_element(ELEMENT,'modules')
modflag = True
if 'MODULE: WATCHDOG' in i:
tline = lines[l_num+1].split(" ")
new = add_element(mod_ele,'module')
add_text(new,'tagname','WATCHDOG')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: QCOUNT' in i:
tline = lines[l_num+1].split(" ")
ENCODERS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','QCOUNT')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: MUXEDQCOUNTSEL' in i:
continue
if 'MODULE: MUXEDQCOUNT' in i:
tline = lines[l_num+1].split(" ")
MUXENCODERS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','MUXEDQCOUNT')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: SSERIAL' in i:
tline = lines[l_num+1].split(" ")
SSERIALPORTS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','SSERIAL')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: RESOLVERMOD' in i:
tline = lines[l_num+1].split(" ")
RESOLVER = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','RESOLVERMOD')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: PWM' in i:
tline = lines[l_num+1].split(" ")
PWMGENS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','PWMGEN')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: TPPWM' in i:
tline = lines[l_num+1].split(" ")
TPPWMGENS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','TPPWMGEN')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: STEPGEN' in i:
tline = lines[l_num+1].split(" ")
STEPGENS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','STEPGEN')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: LED' in i:
tline = lines[l_num+1].split(" ")
LEDS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','LED')
add_text(new,'numinstances',tline[4].lstrip())
if 'MODULE: SSR' in i:
tline = lines[l_num+1].split(" ")
LEDS = tline[4].lstrip()
new = add_element(mod_ele,'module')
add_text(new,'tagname','SSR')
add_text(new,'numinstances',tline[4].lstrip())
if 'IO CONNECTIONS FOR' in i:
if pinsflag:
n1 = add_element(ELEMENT,'pins')
pinsflag = False
CON = temp2[3]
print CON
for num in range(l_num+3,l_num+3+int(NUMCONPINS)):
CHAN = PINFNCTN = ''
pin_line = ' '.join(lines[num].split()).split()
PINNO = pin_line[0]
IO = pin_line[1]
SECFNCTN = pin_line[3]
n2 = add_element(n1,'pin')
add_text(n2,'index',IO)
add_text(n2,'connector',CON)
add_text(n2,'pinno',PINNO)
add_text(n2,'secondarymodulename',SECFNCTN)
if not SECFNCTN == 'NONE':
CHAN = pin_line[4]
PINFNCTN = pin_line[5]
if PINFNCTN in("TXDATA1","TXDATA2","TXDATA3",
"TXDATA4","TXDATA5","TXDATA6","TXDATA7","TXDATA8"):
num = int(PINFNCTN[6])-1
print num
for idnum,dev in sserial:
print idnum,dev,num
if int(idnum) == num:
NEW_FNCTN = '%s-%d'% (dev,num)
add_text(n2,'foundsserialdevice',NEW_FNCTN)
add_text(n2,'secondaryfunctionname',PINFNCTN)
add_text(n2,'secondaryinstance',CHAN)
else:
add_text(n2,'secondaryfunctionname','NOT USED')
print ' I/O ',IO, ' function ',SECFNCTN,' CHANNEL:',CHAN,'PINFUNCTION:',PINFNCTN
print 'Sserial CARDS FOUND:',sserial
print NUMCONS,NUMCONPINS,ENCODERS,MUXENCODERS,SSERIALPORTS,NUMSSCHANNELS
print RESOLVERS,PWMGENS,LEDS
firmname = "~/mesa%d_discovered.xml"%boardnum
filename = os.path.expanduser(firmname)
DOC.writexml(open(filename, "wb"), addindent=" ", newl="\n")
return DRIVER, BOARDNAME, firmname, filename
# update all the firmware/boardname arrays and comboboxes
def discovery_selection_update(self, info, bdnum):
driver, boardname, firmname, path = self.parse_discovery(info,boardnum=bdnum)
boardname = 'Discovered:%s'% boardname
firmdata = self.parse_xml( driver,boardname,firmname,path)
self._p.MESA_FIRMWAREDATA.append(firmdata)
self._p.MESA_INTERNAL_FIRMWAREDATA.append(firmdata)
self._p.MESA_BOARDNAMES.append(boardname)
# add firmname to combo box if it's not there
model = self.widgets["mesa%s_firmware"%bdnum].get_model()
flag = True
for search,item in enumerate(model):
if model[search][0] == firmname:
flag = False
break
if flag:
model.append((firmname,))
search = 0
model = self.widgets["mesa%s_firmware"%bdnum].get_model()
for search,item in enumerate(model):
if model[search][0] == firmname:
self.widgets["mesa%s_firmware"%bdnum].set_active(search)
break
# add boardtitle
model = self.widgets["mesa%s_boardtitle"%bdnum].get_model()
flag2 = True
for search,item in enumerate(model):
if model[search][0] == boardname:
flag2 = False
break
if flag2:
model.append((boardname,))
search = 0
model = self.widgets["mesa%s_boardtitle"%bdnum].get_model()
for search,item in enumerate(model):
#print model[search][0], boardname
if model[search][0] == boardname:
self.widgets["mesa%s_boardtitle"%bdnum].set_active(search)
break
# update if there was a change
if flag or flag2:
self.on_mesa_component_value_changed(None,0)
def add_device_rule(self):
text = []
sourcefile = "/tmp/"
if os.path.exists("/etc/udev/rules.d/50-LINUXCNC-general.rules"):
text.append( "General rule already exists\n")
else:
text.append("adding a general rule first\nso your device will be found\n")
filename = os.path.join(sourcefile, "LINUXCNCtempGeneral.rules")
file = open(filename, "w")
print >>file, ("# This is a rule for LinuxCNC's hal_input\n")
print >>file, ("""SUBSYSTEM="input", MODE="0660", GROUP="plugdev" """)
file.close()
p=os.popen("gksudo cp %sLINUXCNCtempGeneral.rules /etc/udev/rules.d/50-LINUXCNC-general.rules"% sourcefile )
time.sleep(.1)
p.flush()
p.close()
os.remove('%sLINUXCNCtempGeneral.rules'% sourcefile)
text.append(("disconect USB device please\n"))
if not self.warning_dialog("\n".join(text),False):return
os.popen('less /proc/bus/input/devices >> %sLINUXCNCnojoytemp.txt'% sourcefile)
text = ["Plug in USB device please"]
if not self.warning_dialog("\n".join(text),False):return
time.sleep(1)
os.popen('less /proc/bus/input/devices >> %sLINUXCNCjoytemp.txt'% sourcefile).read()
diff = os.popen (" less /proc/bus/input/devices | diff %sLINUXCNCnojoytemp.txt %sLINUXCNCjoytemp.txt "%(sourcefile, sourcefile) ).read()
self.widgets.help_window.set_title(_("USB device Info Search"))
os.remove('%sLINUXCNCnojoytemp.txt'% sourcefile)
os.remove('%sLINUXCNCjoytemp.txt'% sourcefile)
if diff =="":
text = ["No new USB device found"]
if not self.warning_dialog("\n".join(text),True):return
else:
textbuffer = self.widgets.textoutput.get_buffer()
try :
textbuffer.set_text(diff)
self.widgets.helpnotebook.set_current_page(2)
self.widgets.help_window.show_all()
except:
text = _("USB device page is unavailable\n")
self.warning_dialog(text,True)
linelist = diff.split("\n")
for i in linelist:
if "Name" in i:
temp = i.split("\"")
name = temp[1]
temp = name.split(" ")
self.widgets.usbdevicename.set_text(temp[0])
infolist = diff.split()
for i in infolist:
if "Vendor" in i:
temp = i.split("=")
vendor = temp[1]
if "Product" in i:
temp = i.split("=")
product = temp[1]
text =[ "Vendor = %s\n product = %s\n name = %s\nadding specific rule"%(vendor,product,name)]
if not self.warning_dialog("\n".join(text),False):return
tempname = sourcefile+"LINUXCNCtempspecific.rules"
file = open(tempname, "w")
print >>file, ("# This is a rule for LINUXCNC's hal_input\n")
print >>file, ("# For devicename=%s\n"% name)
print >>file, ("""SYSFS{idProduct}=="%s", SYSFS{idVendor}=="%s", MODE="0660", GROUP="plugdev" """%(product,vendor))
file.close()
# remove illegal filename characters
for i in ("(",")"):
temp = name.replace(i,"")
name = temp
newname = "50-LINUXCNC-%s.rules"% name.replace(" ","_")
os.popen("gksudo cp %s /etc/udev/rules.d/%s"% (tempname,newname) )
time.sleep(1)
os.remove('%sLINUXCNCtempspecific.rules'% sourcefile)
text = ["Please unplug and plug in your device again"]
if not self.warning_dialog("\n".join(text),True):return
def test_joystick(self):
halrun = subprocess.Popen("halrun -I ", shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE )
#print "requested devicename = ",self.widgets.usbdevicename.get_text()
halrun.stdin.write("loadusr hal_input -W -KRAL +%s\n"% self.widgets.usbdevicename.get_text())
halrun.stdin.write("loadusr halmeter -g 0 500\n")
time.sleep(1.5)
halrun.stdin.write("show pin\n")
self.warning_dialog("Close me When done.\n",True)
halrun.stdin.write("exit\n")
output = halrun.communicate()[0]
temp2 = output.split(" ")
temp=[]
for i in temp2:
if i =="": continue
temp.append(i)
buttonlist=""
for index,i in enumerate(temp):
if "bit" in i and "OUT" in temp[index+1]:
buttonlist = buttonlist + " Digital: %s"% ( temp[index+3] )
if "float" in i and "OUT" in temp[index+1]:
buttonlist = buttonlist + " Analog: %s"% ( temp[index+3] )
if buttonlist =="": return
textbuffer = self.widgets.textoutput.get_buffer()
try :
textbuffer.set_text(buttonlist)
self.widgets.helpnotebook.set_current_page(2)
self.widgets.help_window.show_all()
except:
text = _("Pin names are unavailable\n")
self.warning_dialog(text,True)
def search_for_device_rule(self):
flag = False
textbuffer = self.widgets.textoutput.get_buffer()
textbuffer.set_text("Searching for device rules in folder: /etc/udev/rules.d\n\n")
for entry in os.listdir("/etc/udev/rules.d"):
if fnmatch.fnmatch( entry,"50-LINUXCNC-*"):
temp = open("/etc/udev/rules.d/" + entry, "r").read()
templist = temp.split("\n")
for i in templist:
if "devicename=" in i:
flag = True
temp = i.split("=")
name = temp[1]
try:
textbuffer.insert_at_cursor( "File name: %s\n"% entry)
textbuffer.insert_at_cursor( "Device name: %s\n\n"% name)
self.widgets.helpnotebook.set_current_page(2)
self.widgets.help_window.show_all()
except:
self.show_try_errors()
text = _("Device names are unavailable\n")
self.warning_dialog(text,True)
if flag == False:
text = _("No Pncconf made device rules were found\n")
textbuffer.insert_at_cursor(text)
self.warning_dialog(text,True)
def read_touchy_preferences(self):
# This reads the Touchy preference file directly
tempdict = {"touchyabscolor":"abs_textcolor","touchyrelcolor":"rel_textcolor",
"touchydtgcolor":"dtg_textcolor","touchyerrcolor":"err_textcolor"}
for key,value in tempdict.iteritems():
data = prefs.getpref(value, 'default', str)
if data == "default":
self.widgets[key].set_active(False)
else:
self.widgets[key].set_active(True)
self.widgets[key+"button"].set_color(gtk.gdk.color_parse(data))
self.widgets.touchyforcemax.set_active(bool(prefs.getpref('window_force_max')))
def get_installed_themes(self):
data1 = self.d.gladevcptheme
data2 = prefs.getpref('gtk_theme', 'Follow System Theme', str)
data3 = self.d.gmcpytheme
model = self.widgets.themestore
model.clear()
model.append((_("Follow System Theme"),))
model2 = self.widgets.glade_themestore
model2.clear()
model2.append((_("Follow System Theme"),))
temp1 = temp2 = temp3 = 0
names = os.listdir(_PD.THEMEDIR)
names.sort()
for search,dirs in enumerate(names):
model.append((dirs,))
model2.append((dirs,))
if dirs == data1:
temp1 = search+1
if dirs == data2:
temp2 = search+1
if dirs == data3:
temp3 = search+1
self.widgets.gladevcptheme.set_active(temp1)
self.widgets.touchytheme.set_active(temp2)
self.widgets.gmcpy_theme.set_active(temp3)
def gladevcp_sanity_check(self):
if os.path.exists(os.path.expanduser("~/linuxcnc/configs/%s/gvcp-panel.ui" % self.d.machinename)):
if not self.warning_dialog(_("OK to replace existing glade panel ?\
\nIt will be renamed and added to 'backups' folder.\n Clicking 'existing custom program' will avoid this warning, but \
if you change related options later -such as spindle feedback- the HAL connection will not update"),False):
return True
def pyvcp_sanity_check(self):
if os.path.exists(os.path.expanduser("~/linuxcnc/configs/%s/pyvcp-panel.xml" % self.d.machinename)):
if not self.warning_dialog(_("OK to replace existing custom pyvcp panel?\
\nExisting pyvcp-panel.xml will be renamed and added to 'backups' folder\n\
Clicking 'existing custom program' will aviod this warning. "),False):
return True
# disallow some signal combinations
def do_exclusive_inputs(self, widget,portnum,pinname):
# If initializing the Pport pages we don't want the signal calls to register here.
# if we are working in here we don't want signal calls because of changes made in here
# GTK supports signal blocking but then you can't assign signal block name references in GLADE -slaps head
if self._p.prepare_block or self.recursive_block: return
if 'mesa' in pinname:
ptype = '%stype'%pinname
if not self.widgets[ptype].get_active_text() == _PD.pintype_gpio[0]: return
self.recursive_block = True
SIG = self._p
exclusive = {
SIG.HOME_X: (SIG.MAX_HOME_X, SIG.MIN_HOME_X, SIG.BOTH_HOME_X, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.HOME_Y: (SIG.MAX_HOME_Y, SIG.MIN_HOME_Y, SIG.BOTH_HOME_Y, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.HOME_Z: (SIG.MAX_HOME_Z, SIG.MIN_HOME_Z, SIG.BOTH_HOME_Z, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.HOME_A: (SIG.MAX_HOME_A, SIG.MIN_HOME_A, SIG.BOTH_HOME_A, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MAX_HOME_X: (SIG.HOME_X, SIG.MIN_HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MAX_HOME_Y: (SIG.HOME_Y, SIG.MIN_HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MAX_HOME_Z: (SIG.HOME_Z, SIG.MIN_HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MAX_HOME_A: (SIG.HOME_A, SIG.MIN_HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MIN_HOME_X: (SIG.HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MIN_HOME_Y: (SIG.HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MIN_HOME_Z: (SIG.HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MIN_HOME_A: (SIG.HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.BOTH_HOME_X: (SIG.HOME_X, SIG.MAX_HOME_X, SIG.MIN_HOME_X, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.BOTH_HOME_Y: (SIG.HOME_Y, SIG.MAX_HOME_Y, SIG.MIN_HOME_Y, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.BOTH_HOME_Z: (SIG.HOME_Z, SIG.MAX_HOME_Z, SIG.MIN_HOME_Z, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.BOTH_HOME_A: (SIG.HOME_A, SIG.MAX_HOME_A, SIG.MIN_HOME_A, SIG.ALL_LIMIT, SIG.ALL_HOME, SIG.ALL_LIMIT_HOME),
SIG.MIN_X: (SIG.BOTH_X, SIG.BOTH_HOME_X, SIG.MIN_HOME_X, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MIN_Y: (SIG.BOTH_Y, SIG.BOTH_HOME_Y, SIG.MIN_HOME_Y, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MIN_Z: (SIG.BOTH_Z, SIG.BOTH_HOME_Z, SIG.MIN_HOME_Z, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MIN_A: (SIG.BOTH_A, SIG.BOTH_HOME_A, SIG.MIN_HOME_A, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MAX_X: (SIG.BOTH_X, SIG.BOTH_HOME_X, SIG.MIN_HOME_X, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MAX_Y: (SIG.BOTH_Y, SIG.BOTH_HOME_Y, SIG.MIN_HOME_Y, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MAX_Z: (SIG.BOTH_Z, SIG.BOTH_HOME_Z, SIG.MIN_HOME_Z, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.MAX_A: (SIG.BOTH_A, SIG.BOTH_HOME_A, SIG.MIN_HOME_A, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.BOTH_X: (SIG.MIN_X, SIG.MAX_X, SIG.MIN_HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.BOTH_Y: (SIG.MIN_Y, SIG.MAX_Y, SIG.MIN_HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.BOTH_Z: (SIG.MIN_Z, SIG.MAX_Z, SIG.MIN_HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.BOTH_A: (SIG.MIN_A, SIG.MAX_A, SIG.MIN_HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A, SIG.ALL_LIMIT, SIG.ALL_LIMIT_HOME),
SIG.ALL_LIMIT: (
SIG.MIN_X, SIG.MAX_X, SIG.BOTH_X, SIG.MIN_HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X,
SIG.MIN_Y, SIG.MAX_Y, SIG.BOTH_Y, SIG.MIN_HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y,
SIG.MIN_Z, SIG.MAX_Z, SIG.BOTH_Z, SIG.MIN_HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z,
SIG.MIN_A, SIG.MAX_A, SIG.BOTH_A, SIG.MIN_HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A,
SIG.ALL_LIMIT_HOME),
SIG.ALL_HOME: (
SIG.HOME_X, SIG.MIN_HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X,
SIG.HOME_Y, SIG.MIN_HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y,
SIG.HOME_Z, SIG.MIN_HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z,
SIG.HOME_A, SIG.MIN_HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A,
SIG.ALL_LIMIT_HOME),
SIG.ALL_LIMIT_HOME: (
SIG.HOME_X, SIG.MIN_HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X,
SIG.HOME_Y, SIG.MIN_HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y,
SIG.HOME_Z, SIG.MIN_HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z,
SIG.HOME_A, SIG.MIN_HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A,
SIG.MIN_X, SIG.MAX_X, SIG.BOTH_X, SIG.MIN_HOME_X, SIG.MAX_HOME_X, SIG.BOTH_HOME_X,
SIG.MIN_Y, SIG.MAX_Y, SIG.BOTH_Y, SIG.MIN_HOME_Y, SIG.MAX_HOME_Y, SIG.BOTH_HOME_Y,
SIG.MIN_Z, SIG.MAX_Z, SIG.BOTH_Z, SIG.MIN_HOME_Z, SIG.MAX_HOME_Z, SIG.BOTH_HOME_Z,
SIG.MIN_A, SIG.MAX_A, SIG.BOTH_A, SIG.MIN_HOME_A, SIG.MAX_HOME_A, SIG.BOTH_HOME_A,
SIG.ALL_LIMIT, SIG.ALL_HOME),
}
model = self.widgets[pinname].get_model()
piter = self.widgets[pinname].get_active_iter()
try:
dummy, index,signame,sig_group = model.get(piter, 0,1,2,3)
except:
self.recursive_block = False
return
dbg('exclusive: current:%s %d %s %s'%(pinname,index,signame,sig_group),mtype='excl')
ex = exclusive.get(signame, ())
if self.d.number_mesa > 0:
dbg( 'looking for %s in mesa'%signame,mtype='excl')
# check mesa main board - only if the tab is shown and the ptype is GOIOI
for boardnum in range(0,int(self.d.number_mesa)):
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._NUMOFCNCTRS]) :
try:
if not self.widgets['mesa%dcon%dtable'%(boardnum,connector)].get_visible():continue
except:
break
break
for s in range(0,24):
p = "mesa%dc%dpin%d"% (boardnum,connector,s)
ptype = "mesa%dc%dpin%dtype"% (boardnum,connector,s)
#print p,self.widgets[ptype].get_active_text(),_PD.pintype_gpio[0]
try:
if not self.widgets[ptype].get_active_text() == _PD.pintype_gpio[0]: continue
if self.widgets[p] == widget:continue
except:
break
break
break
model = self.widgets[p].get_model()
piter = self.widgets[p].get_active_iter()
dummy, index,v1,sig_group = model.get(piter, 0,1,2,3)
#print 'check mesa signals',v1
if v1 in ex or v1 == signame:
dbg( 'found %s, at %s'%(signame,p),mtype='excl')
self.widgets[p].set_active(self._p.hal_input_names.index(SIG.UNUSED_INPUT))
self.d[p] = SIG.UNUSED_INPUT
port = 0
dbg( 'looking for %s in mesa sserial'%signame,mtype='excl')
for channel in range (0,self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._MAXSSERIALCHANNELS]):
if channel == _PD._NUM_CHANNELS: break # TODO may not have all channels worth of glade widgets
if not self.widgets['mesa%dsserial%d_%d'%(boardnum,port,channel)].get_visible():continue
#print "sserial data transfering"
for s in range (0,_PD._SSCOMBOLEN):
p = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, s)
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum, port, channel, s)
try:
if not self.widgets[ptype].get_active_text() == _PD.pintype_gpio[0]: continue
if self.widgets[p] == widget:continue
except:
break
break
model = self.widgets[p].get_model()
piter = self.widgets[p].get_active_iter()
dummy, index,v1,sig_group = model.get(piter, 0,1,2,3)
#print 'check mesa signals',v1
if v1 in ex or v1 == signame:
dbg( 'found %s, at %s'%(signame,p),mtype='excl')
self.widgets[p].set_active(self._p.hal_input_names.index(SIG.UNUSED_INPUT))
self.d[p] = SIG.UNUSED_INPUT
if self.d.number_pports >0:
# search pport1 for the illegal signals and change them to unused.
dbg( 'looking for %s in pport1'%signame,mtype='excl')
for pin1 in (2,3,4,5,6,7,8,9,10,11,12,13,15):
p = 'pp1_Ipin%d' % pin1
# pport2 may not be loaded yet
try:
if self.widgets[p] == widget:continue
except:
self.recursive_block = False
return
model = self.widgets[p].get_model()
piter = self.widgets[p].get_active_iter()
dummy, index,v1,sig_group = model.get(piter, 0,1,2,3)
#print 'check pport1 signals',v1
if v1 in ex or v1 == signame:
dbg( 'found %s, at %s'%(signame,p),mtype='excl')
self.widgets[p].set_active(self._p.hal_input_names.index(SIG.UNUSED_INPUT))
self.d[p] = SIG.UNUSED_INPUT
if self.d.number_pports >1:
# search pport2 for the illegal signals and change them to unused.
dbg( 'looking for %s in pport2'%signame,mtype='excl')
for pin1 in (2,3,4,5,6,7,8,9,10,11,12,13,15):
p2 = 'pp2_Ipin%d' % pin1
# pport2 may not be loaded yet
try:
if self.widgets[p2] == widget: continue
except:
self.recursive_block = False
return
model = self.widgets[p].get_model()
piter = self.widgets[p].get_active_iter()
dummy, index,v2,sig_group = model.get(piter, 0,1,2,3)
#print 'check pport2 signals',v1
if v2 in ex or v2 == signame:
dbg( 'found %s, at %s'%(signame,p2),mtype='excl')
self.widgets[p2].set_active(self._p.hal_input_names.index(SIG.UNUSED_INPUT))
self.d[p2] = SIG.UNUSED_INPUT
self.recursive_block = False
# MESA SIGNALS
# connect signals with pin designation data to mesa signal comboboxes and pintype comboboxes
# record the signal ID numbers so we can block the signals later in the mesa routines
# have to do it here manually (instead of autoconnect) because glade doesn't handle added
# user info (board/connector/pin number designations) and doesn't record the signal ID numbers
# none of this is done if mesa is not checked off in pncconf
# TODO we should check to see if signals are already present as each time user goes though this page
# the signals get added again causing multple calls to the functions.
def init_mesa_signals(self,boardnum):
cb = "mesa%d_discovery"% (boardnum)
i = "_mesa%dsignalhandler_discovery"% (boardnum)
self.d[i] = int(self.widgets[cb].connect("clicked", self.p['on_mesa%d_discovery_clicked'%boardnum]))
cb = "mesa%d_comp_update"% (boardnum)
i = "_mesa%dsignalhandler_comp_update"% (boardnum)
self.d[i] = int(self.widgets[cb].connect("clicked", self.on_mesa_component_value_changed,boardnum))
cb = "mesa%d_boardtitle"% (boardnum)
i = "_mesa%dsignalhandler_boardname_change"% (boardnum)
self.d[i] = int(self.widgets[cb].connect("changed", self.on_mesa_boardname_changed,boardnum))
cb = "mesa%d_firmware"% (boardnum)
i = "_mesa%dsignalhandler_firmware_change"% (boardnum)
self.d[i] = int(self.widgets[cb].connect("changed", self.on_mesa_firmware_changed,boardnum))
for connector in (1,2,3,4,5,6,7,8,9):
for pin in range(0,24):
cb = "mesa%dc%ipin%i"% (boardnum,connector,pin)
i = "_mesa%dsignalhandlerc%ipin%i"% (boardnum,connector,pin)
self.d[i] = int(self.widgets[cb].connect("changed",
self.on_general_pin_changed,"mesa",boardnum,connector,None,pin,False))
i = "_mesa%dactivatehandlerc%ipin%i"% (boardnum,connector,pin)
self.d[i] = int(self.widgets[cb].child.connect("activate",
self.on_general_pin_changed,"mesa",boardnum,connector,None,pin,True))
self.widgets[cb].connect('changed', self.do_exclusive_inputs,boardnum,cb)
cb = "mesa%dc%ipin%itype"% (boardnum,connector,pin)
i = "_mesa%dptypesignalhandlerc%ipin%i"% (boardnum,connector,pin)
self.d[i] = int(self.widgets[cb].connect("changed", self.on_mesa_pintype_changed,boardnum,connector,None,pin))
# SmartSerial signals
port = 0 #TODO we only support one serial port
for channel in range (0,self._p._NUM_CHANNELS):
for pin in range (0,self._p._SSCOMBOLEN):
cb = "mesa%dsserial%i_%ipin%i"% (boardnum,port,channel,pin)
i = "_mesa%dsignalhandlersserial%i_%ipin%i"% (boardnum,port,channel,pin)
self.d[i] = int(self.widgets[cb].connect("changed",
self.on_general_pin_changed,"sserial",boardnum,port,channel,pin,False))
i = "_mesa%dactivatehandlersserial%i_%ipin%i"% (boardnum,port,channel,pin)
self.d[i] = int(self.widgets[cb].child.connect("activate",
self.on_general_pin_changed,"sserial",boardnum,port,channel,pin,True))
self.widgets[cb].connect('changed', self.do_exclusive_inputs,boardnum,cb)
cb = "mesa%dsserial%i_%ipin%itype"% (boardnum,port,channel,pin)
i = "_mesa%dptypesignalhandlersserial%i_%ipin%i"% (boardnum,port,channel,pin)
self.d[i] = int(self.widgets[cb].connect("changed", self.on_mesa_pintype_changed,boardnum,port,channel,pin))
self.widgets["mesa%d_7i29_sanity_check"%boardnum].connect('clicked', self.daughter_board_sanity_check)
self.widgets["mesa%d_7i30_sanity_check"%boardnum].connect('clicked', self.daughter_board_sanity_check)
self.widgets["mesa%d_7i33_sanity_check"%boardnum].connect('clicked', self.daughter_board_sanity_check)
self.widgets["mesa%d_7i40_sanity_check"%boardnum].connect('clicked', self.daughter_board_sanity_check)
self.widgets["mesa%d_7i48_sanity_check"%boardnum].connect('clicked', self.daughter_board_sanity_check)
def init_mesa_options(self,boardnum):
#print 'init mesa%d options'%boardnum
i = self.widgets['mesa%d_boardtitle'%boardnum].get_active_text()
# check for installed firmware
#print i,self.d['mesa%d_boardtitle'%boardnum]
if 1==1:#if not self.d['_mesa%d_arrayloaded'%boardnum]:
#print boardnum,self._p.FIRMDIR,i
# add any extra firmware data from .pncconf-preference file
#if not customself._p.MESA_FIRMWAREDATA == []:
# for i,j in enumerate(customself._p.MESA_FIRMWAREDATA):
# self._p.MESA_FIRMWAREDATA.append(customself._p.MESA_FIRMWAREDATA[i])
# ok set up mesa info
dbg('Looking for firmware data %s'%self.d["mesa%d_firmware"% boardnum])
found = False
search = 0
model = self.widgets["mesa%d_firmware"% boardnum].get_model()
for search,item in enumerate(model):
dbg('%d,%s'%(search,model[search][0]))
if model[search][0] == self.d["mesa%d_firmware"% boardnum]:
self.widgets["mesa%d_firmware"% boardnum].set_active(search)
found = True
dbg('found firmware # %d'% search)
break
if not found:
dbg('firmware not found')
cur_firm = self.d['mesa%d_currentfirmwaredata'% boardnum][_PD._FIRMWARE]
dbg('looking for: %s'% cur_firm )
#self.widgets["mesa%d_firmware"% boardnum].set_active(0)
self._p.MESA_FIRMWAREDATA.append(self.d['mesa%d_currentfirmwaredata'% boardnum])
model.append((cur_firm,))
self.init_mesa_options(boardnum)
return
else:
self.widgets["mesa%d_pwm_frequency"% boardnum].set_value(self.d["mesa%d_pwm_frequency"% boardnum])
self.widgets["mesa%d_pdm_frequency"% boardnum].set_value(self.d["mesa%d_pdm_frequency"% boardnum])
self.widgets["mesa%d_3pwm_frequency"% boardnum].set_value(self.d["mesa%d_3pwm_frequency"% boardnum])
self.widgets["mesa%d_watchdog_timeout"% boardnum].set_value(self.d["mesa%d_watchdog_timeout"% boardnum])
self.widgets["mesa%d_numof_encodergens"% boardnum].set_value(self.d["mesa%d_numof_encodergens"% boardnum])
self.widgets["mesa%d_numof_pwmgens"% boardnum].set_value(self.d["mesa%d_numof_pwmgens"% boardnum])
self.widgets["mesa%d_numof_tppwmgens"% boardnum].set_value(self.d["mesa%d_numof_tppwmgens"% boardnum])
self.widgets["mesa%d_numof_stepgens"% boardnum].set_value(self.d["mesa%d_numof_stepgens"% boardnum])
self.widgets["mesa%d_numof_sserialports"% boardnum].set_value(self.d["mesa%d_numof_sserialports"% boardnum])
self.widgets["mesa%d_numof_sserialchannels"% boardnum].set_value(self.d["mesa%d_numof_sserialchannels"% boardnum])
if not self.widgets.createconfig.get_active() and not self.d['_mesa%d_configured'%boardnum]:
bt = self.d['mesa%d_boardtitle'%boardnum]
firm = self.d['mesa%d_firmware'%boardnum]
pgens = self.d['mesa%d_numof_pwmgens'%boardnum]
tpgens = self.d['mesa%d_numof_tppwmgens'%boardnum]
stepgens = self.d['mesa%d_numof_stepgens'%boardnum]
enc = self.d['mesa%d_numof_encodergens'%boardnum]
ssports = self.d['mesa%d_numof_sserialports'%boardnum]
sschannels = self.d['mesa%d_numof_sserialchannels'%boardnum]
self.set_mesa_options(boardnum,bt,firm,pgens,tpgens,stepgens,enc,ssports,sschannels)
elif not self.d._mesa0_configured:
self.widgets['mesa%dcon2table'%boardnum].hide()
self.widgets['mesa%dcon3table'%boardnum].hide()
self.widgets['mesa%dcon4table'%boardnum].hide()
self.widgets['mesa%dcon5table'%boardnum].hide()
def on_mesa_boardname_changed(self, widget,boardnum):
#print "**** INFO boardname %d changed"% boardnum
model = self.widgets["mesa%d_boardtitle"% boardnum].get_model()
title = self.widgets["mesa%d_boardtitle"% boardnum].get_active_text()
if title:
if 'Discovery Option' in title:
self.widgets["mesa%d_discovery"% boardnum].show()
else:
self.widgets["mesa%d_discovery"% boardnum].hide()
for i in(1,2,3,4,5,6,7,8,9):
self.widgets['mesa%dcon%dtable'%(boardnum,i)].hide()
self.widgets["mesa{}con{}tab".format(boardnum,i)].set_text('I/O\n Connector %d'%i)
for i in(0,1,2,3,4,5):
self.widgets["mesa%dsserial0_%d"%(boardnum,i)].hide()
if title == None: return
if 'Discovery Option' not in title:
meta = self.get_board_meta(title)
names = meta.get('TAB_NAMES')
tnums = meta.get('TAB_NUMS')
if names and tnums:
for index, tabnum in enumerate(tnums):
self.widgets["mesa{}con{}tab".format(boardnum,tabnum)].set_text(names[index])
#print 'title',title
self.fill_firmware(boardnum)
def fill_firmware(self,boardnum):
#print 'fill firmware'
self.firmware_block = True
title = self.widgets["mesa%d_boardtitle"% boardnum].get_active_text()
#print title
self._p.MESA_FIRMWAREDATA = []
if os.path.exists(os.path.join(self._p.FIRMDIR,title)):
self.mesa_firmware_search(title)
self.d['_mesa%d_arrayloaded'%boardnum] = True
for i in self._p.MESA_INTERNAL_FIRMWAREDATA:
self._p.MESA_FIRMWAREDATA.append(i)
model = self.widgets["mesa%d_firmware"% boardnum].get_model()
model.clear()
temp=[]
for search, item in enumerate(self._p.MESA_FIRMWAREDATA):
d = self._p.MESA_FIRMWAREDATA[search]
if not d[self._p._BOARDTITLE] == title:continue
temp.append(d[self._p._FIRMWARE])
temp.sort()
for i in temp:
#print i
model.append((i,))
self.widgets["mesa%d_firmware"% boardnum].set_active(0)
self.firmware_block = False
self.on_mesa_firmware_changed(None,boardnum)
#print "firmware-",self.widgets["mesa%d_firmware"% boardnum].get_active_text(),self.widgets["mesa%d_firmware"% boardnum].get_active()
#print "boardname-" + d[_PD._BOARDNAME]
def on_mesa_firmware_changed(self, widget,boardnum):
if self.firmware_block:
return
print "**** INFO firmware %d changed"% boardnum
model = self.widgets["mesa%d_boardtitle"% boardnum].get_model()
active = self.widgets["mesa%d_boardtitle"% boardnum].get_active()
if active < 0:
title = None
else: title = model[active][0]
firmware = self.widgets["mesa%d_firmware"% boardnum].get_active_text()
for search, item in enumerate(self._p.MESA_FIRMWAREDATA):
d = self._p.MESA_FIRMWAREDATA[search]
#print firmware,d[_PD._FIRMWARE],title,d[_PD._BOARDTITLE]
if not d[_PD._BOARDTITLE] == title:continue
if d[_PD._FIRMWARE] == firmware:
self.widgets["mesa%d_numof_encodergens"%boardnum].set_range(0,d[_PD._MAXENC])
self.widgets["mesa%d_numof_encodergens"% boardnum].set_value(d[_PD._MAXENC])
self.widgets["mesa%d_numof_pwmgens"% boardnum].set_range(0,d[_PD._MAXPWM])
self.widgets["mesa%d_numof_pwmgens"% boardnum].set_value(d[_PD._MAXPWM])
if d[_PD._MAXTPPWM]:
self.widgets["mesa%d_numof_tppwmgens"% boardnum].show()
self.widgets["mesa%d_numof_tpp_label"% boardnum].show()
self.widgets["mesa%d_3pwm_freq_label"% boardnum].show()
self.widgets["mesa%d_3pwm_freq_units"% boardnum].show()
self.widgets["mesa%d_3pwm_frequency"% boardnum].show()
else:
self.widgets["mesa%d_numof_tppwmgens"% boardnum].hide()
self.widgets["mesa%d_numof_tpp_label"% boardnum].hide()
self.widgets["mesa%d_3pwm_freq_label"% boardnum].hide()
self.widgets["mesa%d_3pwm_freq_units"% boardnum].hide()
self.widgets["mesa%d_3pwm_frequency"% boardnum].hide()
self.widgets["mesa%d_numof_tppwmgens"% boardnum].set_range(0,d[_PD._MAXTPPWM])
self.widgets["mesa%d_numof_tppwmgens"% boardnum].set_value(d[_PD._MAXTPPWM])
self.widgets["mesa%d_numof_stepgens"% boardnum].set_range(0,d[_PD._MAXSTEP])
self.widgets["mesa%d_numof_stepgens"% boardnum].set_value(d[_PD._MAXSTEP])
self.d["mesa%d_numof_resolvers"% boardnum] = (d[_PD._MAXRES]) # TODO fix this hack should be selectable
if d[_PD._MAXRES]:
self.widgets["mesa%d_numof_resolvers"% boardnum].show()
self.widgets["mesa%d_numof_resolvers"% boardnum].set_value(d[_PD._MAXRES]*6)
self.widgets["mesa%d_numof_resolvers"% boardnum].set_sensitive(False)
self.widgets["mesa%d_numof_resolvers_label"% boardnum].show()
self.widgets["mesa%d_pwm_frequency"% boardnum].set_value(24000)
else:
self.widgets["mesa%d_numof_resolvers"% boardnum].hide()
self.widgets["mesa%d_numof_resolvers_label"% boardnum].hide()
self.widgets["mesa%d_numof_resolvers"% boardnum].set_value(0)
if d[_PD._MAXSSERIALPORTS]:
self.widgets["mesa%d_numof_sserialports"% boardnum].show()
self.widgets["mesa%d_numof_sserialports_label"% boardnum].show()
self.widgets["mesa%d_numof_sserialchannels"% boardnum].show()
self.widgets["mesa%d_numof_sserialchannels_label"% boardnum].show()
else:
self.widgets["mesa%d_numof_sserialports"% boardnum].hide()
self.widgets["mesa%d_numof_sserialports_label"% boardnum].hide()
self.widgets["mesa%d_numof_sserialchannels"% boardnum].hide()
self.widgets["mesa%d_numof_sserialchannels_label"% boardnum].hide()
self.widgets["mesa%d_numof_sserialports"% boardnum].set_range(0,d[_PD._MAXSSERIALPORTS])
self.widgets["mesa%d_numof_sserialports"% boardnum].set_value(d[_PD._MAXSSERIALPORTS])
self.widgets["mesa%d_numof_sserialchannels"% boardnum].set_range(1,d[_PD._MAXSSERIALCHANNELS])
self.widgets["mesa%d_numof_sserialchannels"% boardnum].set_value(d[_PD._MAXSSERIALCHANNELS])
self.widgets["mesa%d_totalpins"% boardnum].set_text("%s"% d[_PD._MAXGPIO])
self.widgets["mesa%d_3pwm_frequency"% boardnum].set_sensitive(d[_PD._MAXTPPWM])
if d[_PD._MAXRES]:
self.widgets["mesa%d_pwm_frequency"% boardnum].set_sensitive(False)
else:
self.widgets["mesa%d_pwm_frequency"% boardnum].set_sensitive(d[_PD._MAXPWM])
self.widgets["mesa%d_pdm_frequency"% boardnum].set_sensitive(d[_PD._MAXPWM])
if 'eth' in d[_PD._HALDRIVER] or "7i43" in title or '7i90' in title:
self.widgets["mesa%d_card_addrs_hbox"% boardnum].show()
if '7i43' in title or '7i90' in title:
self.widgets["mesa%d_parportaddrs"% boardnum].show()
self.widgets["mesa%d_card_addrs"% boardnum].hide()
else:
self.widgets["mesa%d_parportaddrs"% boardnum].hide()
self.widgets["mesa%d_card_addrs"% boardnum].show()
self.widgets["mesa%d_parporttext"% boardnum].show()
else:
self.widgets["mesa%d_card_addrs_hbox"% boardnum].hide()
self.widgets["mesa%d_parporttext"% boardnum].hide()
break
# This method converts data from the GUI page to signal names for pncconf's mesa data variables
# It starts by checking pin type to set up the proper lists to search
# then depending on the pin type widget data is converted to signal names.
# if the signal name is not in the list add it to Human_names, signal_names
# and disc-saved signalname lists
# if encoder, pwm, or stepper pins the related pin are also set properly
# it does this by searching the current firmware array and finding what the
# other related pins numbers are then changing them to the appropriate signalname.
def mesa_data_transfer(self,boardnum):
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]) :
for pin in range(0,24):
p = 'mesa%dc%dpin%d' % (boardnum,connector,pin)
pinv = 'mesa%dc%dpin%dinv' % (boardnum,connector,pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum,connector,pin)
self.data_transfer(boardnum,connector,None,pin,p,pinv,ptype)
self.d["mesa%d_pwm_frequency"% boardnum] = self.widgets["mesa%d_pwm_frequency"% boardnum].get_value()
self.d["mesa%d_pdm_frequency"% boardnum] = self.widgets["mesa%d_pdm_frequency"% boardnum].get_value()
self.d["mesa%d_3pwm_frequency"% boardnum] = self.widgets["mesa%d_3pwm_frequency"% boardnum].get_value()
self.d["mesa%d_watchdog_timeout"% boardnum] = self.widgets["mesa%d_watchdog_timeout"% boardnum].get_value()
port = 0
for channel in range (0,self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._MAXSSERIALCHANNELS]):
if channel == _PD._NUM_CHANNELS: break # TODO may not have all channels worth of glade widgets
subboardname = self.d["mesa%dsserial%d_%dsubboard"% (boardnum, port, channel)]
#print "data transfer-channel ",channel," subboard name",subboardname
if subboardname == "none":
#print "no subboard for %s"% subboardname
continue
#print "sserial data transfering"
for pin in range (0,_PD._SSCOMBOLEN):
p = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)
pinv = 'mesa%dsserial%d_%dpin%dinv' % (boardnum, port, channel, pin)
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum, port, channel, pin)
self.data_transfer(boardnum,port,channel,pin,p,pinv,ptype)
#print "sserial data transfer",p
def data_transfer(self,boardnum,connector,channel,pin,p,pinv,ptype):
foundit = False
piter = self.widgets[p].get_active_iter()
ptiter = self.widgets[ptype].get_active_iter()
pintype = self.widgets[ptype].get_active_text()
selection = self.widgets[p].get_active_text()
signaltree = self.widgets[p].get_model()
#if "serial" in p:
# print "**** INFO mesa-data-transfer:",p," selection: ",selection," pintype: ",pintype
# print "**** INFO mesa-data-transfer:",ptiter,piter
# type NOTUSED
if pintype == _PD.NUSED:
self.d[p] = _PD.UNUSED_UNUSED
self.d[ptype] = _PD.NUSED
self.d[pinv] = False
return
# type GPIO input
if pintype == _PD.GPIOI:
ptypetree = self.d._gpioliststore
signaltocheck = _PD.hal_input_names
# type gpio output and open drain
elif pintype in (_PD.GPIOO,_PD.GPIOD):
ptypetree = self.d._gpioliststore
signaltocheck = _PD.hal_output_names
elif pintype == _PD.SSR0:
ptypetree = self.d._ssrliststore
signaltocheck = _PD.hal_output_names
#type encoder
elif pintype in (_PD.ENCA,_PD.ENCB,_PD.ENCI,_PD.ENCM):
ptypetree = self.d._encoderliststore
signaltocheck = _PD.hal_encoder_input_names
# resolvers
elif pintype in (_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5,_PD.RESU):
ptypetree = self.d._resolverliststore
signaltocheck = _PD.hal_resolver_input_names
# 8i20 amplifier card
elif pintype == _PD.AMP8I20:
ptypetree = self.d._8i20liststore
signaltocheck = _PD.hal_8i20_input_names
# potentiometer output
elif pintype in (_PD.POTO,_PD.POTE):
ptypetree = self.d._potliststore
signaltocheck = _PD.hal_pot_output_names
# analog in
elif pintype == (_PD.ANALOGIN):
ptypetree = self.d._analoginliststore
signaltocheck = _PD.hal_analog_input_names
#type mux encoder
elif pintype in (_PD.MXE0, _PD.MXE1, _PD.MXEI, _PD.MXEM, _PD.MXES):
ptypetree = self.d._muxencoderliststore
signaltocheck = _PD.hal_encoder_input_names
# type PWM gen
elif pintype in( _PD.PDMP,_PD.PDMD,_PD.PDME):
if pintype == _PD.PDMP:
ptypetree = self.d._pdmcontrolliststore
else:
ptypetree = self.d._pdmrelatedliststore
signaltocheck = _PD.hal_pwm_output_names
# PDM
elif pintype in( _PD.PWMP,_PD.PWMD,_PD.PWME):
if pintype == _PD.PWMP:
ptypetree = self.d._pwmcontrolliststore
else:
ptypetree = self.d._pwmrelatedliststore
signaltocheck = _PD.hal_pwm_output_names
# Up/Down mode
elif pintype in( _PD.UDMU,_PD.UDMD,_PD.UDME):
if pintype == _PD.UDMU:
ptypetree = self.d._udmcontrolliststore
else:
ptypetree = self.d._udmrelatedliststore
signaltocheck = _PD.hal_pwm_output_names
# type tp pwm
elif pintype in (_PD.TPPWMA,_PD.TPPWMB,_PD.TPPWMC,_PD.TPPWMAN,_PD.TPPWMBN,_PD.TPPWMCN,_PD.TPPWME,_PD.TPPWMF):
ptypetree = self.d._tppwmliststore
signaltocheck = _PD.hal_tppwm_output_names
# type step gen
elif pintype in (_PD.STEPA,_PD.STEPB):
ptypetree = self.d._stepperliststore
signaltocheck = _PD.hal_stepper_names
# type sserial
elif pintype in (_PD.RXDATA0,_PD.TXDATA0,_PD.TXEN0,_PD.RXDATA1,_PD.TXDATA1,_PD.TXEN1,_PD.RXDATA2,
_PD.TXDATA2,_PD.TXEN2,_PD.RXDATA3,_PD.TXDATA3,_PD.TXEN3,
_PD.RXDATA4,_PD.TXDATA4,_PD.TXEN4,_PD.RXDATA5,_PD.TXDATA5,_PD.TXEN5,_PD.RXDATA6,_PD.TXDATA6,
_PD.TXEN6,_PD.RXDATA7,_PD.TXDATA7,_PD.TXEN7,
_PD.SS7I76M0,_PD.SS7I76M2,_PD.SS7I76M3,_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4):
ptypetree = self.d._sserialliststore
signaltocheck = _PD.hal_sserial_names
# this suppresses errors because of unused and uninitialized sserial instances
elif pintype == None and "sserial" in ptype: return
else :
print "**** ERROR mesa-data-transfer: error unknown pin type:",pintype,"of ",ptype
return
# **Start widget to data Convertion**
# for encoder pins
if piter == None:
#print "callin pin changed !!!"
name ="mesa"
if "sserial" in p: name = "sserial"
self.on_general_pin_changed(None,name,boardnum,connector,channel,pin,True)
selection = self.widgets[p].get_active_text()
piter = self.widgets[p].get_active_iter()
if piter == None:
print "****ERROR PNCCONF: no custom name available"
return
#print "found signame -> ",selection," "
# ok we have a piter with a signal type now- lets convert it to a signalname
#if not "serial" in p:
# self.debug_iter(piter,p,"signal")
dummy, index = signaltree.get(piter,0,1)
#if not "serial" in p:
# print "signaltree: ",dummy
# self.debug_iter(ptiter,ptype,"ptype")
widgetptype, index2 = ptypetree.get(ptiter,0,1)
#if not "serial" in p:
# print "ptypetree: ",widgetptype
if pintype in (_PD.GPIOI,_PD.GPIOO,_PD.GPIOD,_PD.SSR0,_PD.MXE0,_PD.MXE1,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5,_PD.RESU,_PD.SS7I76M0,
_PD.SS7I76M2,_PD.SS7I76M3,_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4) or (index == 0):
index2 = 0
elif pintype in ( _PD.TXDATA0,_PD.RXDATA0,_PD.TXEN0,_PD.TXDATA1,_PD.RXDATA1,_PD.TXEN1,_PD.TXDATA2,_PD.RXDATA2,
_PD.TXEN2,_PD.TXDATA3,_PD.RXDATA3,_PD.TXEN3,_PD.TXDATA4,_PD.RXDATA4,_PD.TXEN4,
_PD.TXDATA5,_PD.RXDATA5,_PD.TXEN5,_PD.TXDATA6,_PD.RXDATA6,_PD.TXEN6,_PD.TXDATA7,_PD.RXDATA7,_PD.TXEN7 ):
index2 = 0
#print index,index2,signaltocheck[index+index2]
self.d[p] = signaltocheck[index+index2]
self.d[ptype] = widgetptype
self.d[pinv] = self.widgets[pinv].get_active()
#if "serial" in p:
# print "*** INFO PNCCONF mesa pin:",p,"signalname:",self.d[p],"pin type:",widgetptype
def on_mesa_pintype_changed(self, widget,boardnum,connector,channel,pin):
#print "mesa pintype changed:",boardnum,connector,channel,pin
if not channel == None:
port = connector
p = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum, port, channel, pin)
blocksignal = "_mesa%dsignalhandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
ptypeblocksignal = "_mesa%dptypesignalhandlersserial%i_%ipin%i"% (boardnum, port, channel, pin)
else:
p = 'mesa%dc%dpin%d' % (boardnum,connector,pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum,connector,pin)
blocksignal = "_mesa%dsignalhandlerc%ipin%i"% (boardnum,connector,pin)
ptypeblocksignal = "_mesa%dptypesignalhandlerc%ipin%i" % (boardnum, connector,pin)
modelcheck = self.widgets[p].get_model()
modelptcheck = self.widgets[ptype].get_model()
new = self.widgets[ptype].get_active_text()
#print "pintypechanged",p
# switch GPIO input to GPIO output
# here we switch the available signal names in the combobox
# we block signals so pinchanged method is not called
if modelcheck == self.d._gpioisignaltree and new in (_PD.GPIOO,_PD.GPIOD):
#print "switch GPIO input ",p," to output",new
self.widgets[p].handler_block(self.d[blocksignal])
self.widgets[p].set_model(self.d._gpioosignaltree)
self.widgets[p].set_active(0)
self.widgets[p].handler_unblock(self.d[blocksignal])
# switch GPIO output to input
elif modelcheck == self.d._gpioosignaltree:
if new == _PD.GPIOI:
#print "switch GPIO output ",p,"to input"
self.widgets[p].handler_block(self.d[blocksignal])
self.widgets[p].set_model(self.d._gpioisignaltree)
self.widgets[p].set_active(0)
self.widgets[p].handler_unblock(self.d[blocksignal])
# switch between pulse width, pulse density or up/down mode analog modes
# here we search the firmware for related pins (eg PWMP,PWMD,PWME ) and change them too.
# we block signals so we don't call this routine again.
elif modelptcheck in (self.d._pwmcontrolliststore, self.d._pdmcontrolliststore, self.d._udmcontrolliststore):
relatedpins = [_PD.PWMP,_PD.PWMD,_PD.PWME]
if new == _PD.PWMP:
display = 0
relatedliststore = self.d._pwmrelatedliststore
controlliststore = self.d._pwmcontrolliststore
elif new == _PD.PDMP:
display = 1
relatedliststore = self.d._pdmrelatedliststore
controlliststore = self.d._pdmcontrolliststore
elif new == _PD.UDMU:
display = 2
relatedliststore = self.d._udmrelatedliststore
controlliststore = self.d._udmcontrolliststore
else:print "**** WARNING PNCCONF: pintype error-PWM type not found";return
self.widgets[ptype].handler_block(self.d[ptypeblocksignal])
self.widgets[ptype].set_model(controlliststore)
self.widgets[ptype].set_active(display)
self.widgets[ptype].handler_unblock(self.d[ptypeblocksignal])
pinlist = self.list_related_pins(relatedpins, boardnum, connector, channel, pin, 1)
for i in (pinlist):
relatedptype = i[0]
if relatedptype == ptype :continue
if not channel == None:
ptypeblocksignal = "_mesa%dptypesignalhandlersserial%i_%ipin%i"% (i[1], i[2],i[3],i[4])
else:
ptypeblocksignal = "_mesa%dptypesignalhandlerc%ipin%i" % (i[1], i[2],i[4])
self.widgets[relatedptype].handler_block(self.d[ptypeblocksignal])
j = self.widgets[relatedptype].get_active()
self.widgets[relatedptype].set_model(relatedliststore)
self.widgets[relatedptype].set_active(j)
self.widgets[relatedptype].handler_unblock(self.d[ptypeblocksignal])
else: print "**** WARNING PNCCONF: pintype error in pintypechanged method new ",new," pinnumber ",p
def on_mesa_component_value_changed(self, widget,boardnum):
self.in_mesa_prepare = True
self.d["mesa%d_pwm_frequency"% boardnum] = self.widgets["mesa%d_pwm_frequency"% boardnum].get_value()
self.d["mesa%d_pdm_frequency"% boardnum] = self.widgets["mesa%d_pdm_frequency"% boardnum].get_value()
self.d["mesa%d_watchdog_timeout"% boardnum] = self.widgets["mesa%d_watchdog_timeout"% boardnum].get_value()
numofpwmgens = self.d["mesa%d_numof_pwmgens"% boardnum] = int(self.widgets["mesa%d_numof_pwmgens"% boardnum].get_value())
numoftppwmgens = self.d["mesa%d_numof_tppwmgens"% boardnum] = int(self.widgets["mesa%d_numof_tppwmgens"% boardnum].get_value())
numofstepgens = self.d["mesa%d_numof_stepgens"% boardnum] = int(self.widgets["mesa%d_numof_stepgens"% boardnum].get_value())
numofencoders = self.d["mesa%d_numof_encodergens"% boardnum] = int(self.widgets["mesa%d_numof_encodergens"% boardnum].get_value())
numofsserialports = self.d["mesa%d_numof_sserialports"% boardnum] = int(self.widgets["mesa%d_numof_sserialports"% boardnum].get_value())
numofsserialchannels = self.d["mesa%d_numof_sserialchannels"% boardnum] = \
int(self.widgets["mesa%d_numof_sserialchannels"% boardnum].get_value())
title = self.d["mesa%d_boardtitle"% boardnum] = self.widgets["mesa%d_boardtitle"% boardnum].get_active_text()
firmware = self.d["mesa%d_firmware"% boardnum] = self.widgets["mesa%d_firmware"% boardnum].get_active_text()
self.set_mesa_options(boardnum,title,firmware,numofpwmgens,numoftppwmgens,numofstepgens,numofencoders,numofsserialports,numofsserialchannels)
return True
# This method sets up the mesa GUI page and is used when changing component values / firmware or boards from config page.
# it changes the component comboboxes according to the firmware max and user requested amounts
# it adds signal names to the signal name combo boxes according to component type and in the
# case of GPIO options selected on the basic page such as limit/homing types.
# it will grey out I/O tabs according to the selected board type.
# it uses GTK signal blocking to block on_general_pin_change and on_mesa_pintype_changed methods.
# Since this method is for initialization, there is no need to check for changes and this speeds up
# the update.
# 'self._p.MESA_FIRMWAREDATA' holds all the firmware d.
# 'self.d.mesaX_currentfirmwaredata' hold the current selected firmware data (X is 0 or 1)
def set_mesa_options(self,boardnum,title,firmware,numofpwmgens,numoftppwmgens,numofstepgens,numofencoders,numofsserialports,numofsserialchannels):
_PD.prepare_block = True
self.p.set_buttons_sensitive(0,0)
self.pbar.set_text("Setting up Mesa tabs")
self.pbar.set_fraction(0)
self.window.show()
while gtk.events_pending():
gtk.main_iteration()
for search, item in enumerate(self._p.MESA_FIRMWAREDATA):
d = self._p.MESA_FIRMWAREDATA[search]
if not d[_PD._BOARDTITLE] == title:continue
if d[_PD._FIRMWARE] == firmware:
self.d["mesa%d_currentfirmwaredata"% boardnum] = self._p.MESA_FIRMWAREDATA[search]
break
dbg('current firmware:\n%r'%self._p.MESA_FIRMWAREDATA[search],mtype='curfirm')
self.widgets["mesa%dcon2table"% boardnum].hide()
self.widgets["mesa%dcon3table"% boardnum].hide()
self.widgets["mesa%dcon4table"% boardnum].hide()
self.widgets["mesa%dcon5table"% boardnum].hide()
self.widgets["mesa%dcon6table"% boardnum].hide()
self.widgets["mesa%dcon7table"% boardnum].hide()
self.widgets["mesa%dcon8table"% boardnum].hide()
self.widgets["mesa%dcon9table"% boardnum].hide()
self.widgets["mesa%dsserial0_0"% boardnum].hide()
self.widgets["mesa%dsserial0_1"% boardnum].hide()
self.widgets["mesa%dsserial0_2"% boardnum].hide()
self.widgets["mesa%dsserial0_3"% boardnum].hide()
self.widgets["mesa%dsserial0_4"% boardnum].hide()
currentboard = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME]
for i in self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]:
self.widgets["mesa%dcon%dtable"% (boardnum,i)].show()
# self.widgets["mesa%d"%boardnum].set_title("Mesa%d Configuration-Board: %s firmware: %s"% (boardnum,self.d["mesa%d_boardtitle"%boardnum],
# self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._FIRMWARE]))
temp = "/usr/share/doc/hostmot2-firmware-%s/%s.PIN"% (self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._DIRECTORY],
self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._FIRMWARE] )
filename = os.path.expanduser(temp)
if os.path.exists(filename):
match = open(filename).read()
textbuffer = self.widgets.textoutput.get_buffer()
try :
textbuffer.set_text("%s\n\n"% filename)
textbuffer.insert_at_cursor(match)
except:
pass
currentboard = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME]
meta = self.get_board_meta(currentboard)
ppc = meta.get('PINS_PER_CONNECTOR')
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]) :
for pin in range (0,24):
self.pbar.set_fraction((pin+1)/24.0)
while gtk.events_pending():
gtk.main_iteration()
firmptype,compnum = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._STARTOFDATA+pin+(concount*24)]
p = 'mesa%dc%dpin%d' % (boardnum, connector, pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum, connector , pin)
#print "**** INFO set-mesa-options DATA:",self.d[p],p,self.d[ptype]
#print "**** INFO set-mesa-options FIRM:",firmptype
#print "**** INFO set-mesa-options WIDGET:",self.widgets[p].get_active_text(),self.widgets[ptype].get_active_text()
complabel = 'mesa%dc%dpin%dnum' % (boardnum, connector , pin)
pinv = 'mesa%dc%dpin%dinv' % (boardnum, connector , pin)
blocksignal = "_mesa%dsignalhandlerc%ipin%i" % (boardnum, connector, pin)
ptypeblocksignal = "_mesa%dptypesignalhandlerc%ipin%i" % (boardnum, connector,pin)
actblocksignal = "_mesa%dactivatehandlerc%ipin%i" % (boardnum, connector, pin)
# kill all widget signals:
self.widgets[ptype].handler_block(self.d[ptypeblocksignal])
self.widgets[p].handler_block(self.d[blocksignal])
self.widgets[p].child.handler_block(self.d[actblocksignal])
self.firmware_to_widgets(boardnum,firmptype,p,ptype,pinv,complabel,compnum,concount,ppc,pin,numofencoders,
numofpwmgens,numoftppwmgens,numofstepgens,None,numofsserialports,numofsserialchannels,False)
self.d["mesa%d_numof_stepgens"% boardnum] = numofstepgens
self.d["mesa%d_numof_pwmgens"% boardnum] = numofpwmgens
self.d["mesa%d_numof_encodergens"% boardnum] = numofencoders
self.d["mesa%d_numof_sserialports"% boardnum] = numofsserialports
self.d["mesa%d_numof_sserialchannels"% boardnum] = numofsserialchannels
self.widgets["mesa%d_numof_stepgens"% boardnum].set_value(numofstepgens)
self.widgets["mesa%d_numof_encodergens"% boardnum].set_value(numofencoders)
self.widgets["mesa%d_numof_pwmgens"% boardnum].set_value(numofpwmgens)
self.in_mesa_prepare = False
self.d["_mesa%d_configured"% boardnum] = True
# unblock all the widget signals again
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]) :
for pin in range (0,24):
p = 'mesa%dc%dpin%d' % (boardnum, connector, pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum, connector , pin)
blocksignal = "_mesa%dsignalhandlerc%ipin%i" % (boardnum, connector, pin)
ptypeblocksignal = "_mesa%dptypesignalhandlerc%ipin%i" % (boardnum, connector,pin)
actblocksignal = "_mesa%dactivatehandlerc%ipin%i" % (boardnum, connector, pin)
self.widgets[ptype].handler_unblock(self.d[ptypeblocksignal])
self.widgets[p].handler_unblock(self.d[blocksignal])
self.widgets[p].child.handler_unblock(self.d[actblocksignal])
self.mesa_mainboard_data_to_widgets(boardnum)
self.window.hide()
self.p.set_buttons_sensitive(1,1)
_PD.prepare_block = False
def set_sserial_options(self,boardnum,port,channel):
numofsserialports = self.d["mesa%d_numof_sserialports"% boardnum]
numofsserialchannels = self.d["mesa%d_numof_sserialchannels"% boardnum]
subboardname = self.d["mesa%dsserial%d_%dsubboard"% (boardnum, port, channel)]
if subboardname == "none":return
self.pbar.set_text("Setting up Mesa Smart Serial tabs")
self.pbar.set_fraction(0)
self.window.show()
while gtk.events_pending():
gtk.main_iteration()
for subnum,temp in enumerate(self._p.MESA_DAUGHTERDATA):
#print self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBFIRMNAME],subboardname
if self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBFIRMNAME] == subboardname: break
#print "found subboard name:",self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBFIRMNAME],subboardname,subnum,"channel:",channel
for pin in range (0,self._p._SSCOMBOLEN):
self.pbar.set_fraction((pin+1)/60.0)
while gtk.events_pending():
gtk.main_iteration()
p = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum, port, channel, pin)
pinv = 'mesa%dsserial%d_%dpin%dinv' % (boardnum, port, channel, pin)
complabel = 'mesa%dsserial%d_%dpin%dnum' % (boardnum, port, channel, pin)
blocksignal = "_mesa%dsignalhandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
ptypeblocksignal = "_mesa%dptypesignalhandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
actblocksignal = "_mesa%dactivatehandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
firmptype,compnum = self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBSTARTOFDATA+pin]
#print "sserial set options",p
# kill all widget signals:
self.widgets[ptype].handler_block(self.d[ptypeblocksignal])
self.widgets[p].handler_block(self.d[blocksignal])
self.widgets[p].child.handler_block(self.d[actblocksignal])
ppc = 0
concount = 0
numofencoders = 10
numofpwmgens = 12
numoftppwmgens = 0
numofstepgens = 0
self.firmware_to_widgets(boardnum,firmptype,p,ptype,pinv,complabel,compnum,concount,ppc,pin,numofencoders,
numofpwmgens,numoftppwmgens,numofstepgens,subboardname,numofsserialports,numofsserialchannels,True)
# all this to unblock signals
for pin in range (0,self._p._SSCOMBOLEN):
firmptype,compnum = self._p.MESA_DAUGHTERDATA[0][self._p._SUBSTARTOFDATA+pin]
p = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum, port, channel, pin)
pinv = 'mesa%dsserial%d_%dpin%dinv' % (boardnum, port, channel, pin)
complabel = 'mesa%dsserial%d_%dpin%dnum' % (boardnum, port, channel, pin)
blocksignal = "_mesa%dsignalhandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
ptypeblocksignal = "_mesa%dptypesignalhandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
actblocksignal = "_mesa%dactivatehandlersserial%i_%ipin%i" % (boardnum, port, channel, pin)
# unblock all widget signals:
self.widgets[ptype].handler_unblock(self.d[ptypeblocksignal])
self.widgets[p].handler_unblock(self.d[blocksignal])
self.widgets[p].child.handler_unblock(self.d[actblocksignal])
# now that the widgets are set up as per firmware, change them as per the loaded data and add signals
for pin in range (0,self._p._SSCOMBOLEN):
firmptype,compnum = self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBSTARTOFDATA+pin]
p = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)
#print "INFO: data to widget smartserial- ",p, firmptype
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum, port, channel, pin)
pinv = 'mesa%dsserial%d_%dpin%dinv' % (boardnum, port, channel, pin)
self.data_to_widgets(boardnum,firmptype,compnum,p,ptype,pinv)
#print "sserial data-widget",p
self.widgets["mesa%d_numof_sserialports"% boardnum].set_value(numofsserialports)
self.widgets["mesa%d_numof_sserialchannels"% boardnum].set_value(numofsserialchannels)
self.window.hide()
def firmware_to_widgets(self,boardnum,firmptype,p,ptype,pinv,complabel,compnum,concount,ppc, pin,numofencoders,numofpwmgens,numoftppwmgens,
numofstepgens,subboardname,numofsserialports,numofsserialchannels,sserialflag):
currentboard = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME]
# *** convert widget[ptype] to component specified in firmwaredata ***
# if the board has less then 24 pins hide the extra comboboxes
if firmptype == _PD.NUSED:
self.widgets[p].hide()
self.widgets[ptype].hide()
self.widgets[pinv].hide()
self.widgets[complabel].hide()
self.widgets[ptype].set_model(self.d._notusedliststore)
self.widgets[ptype].set_active(0)
self.widgets[p].set_model(self.d._notusedsignaltree)
self.widgets[p].set_active(0)
return
else:
self.widgets[p].show()
self.widgets[ptype].show()
self.widgets[pinv].show()
self.widgets[complabel].show()
self.widgets[p].child.set_editable(True)
# ---SETUP GUI FOR ENCODER FAMILY COMPONENT---
# check that we are not converting more encoders that user requested
# if we are then we trick this routine into thinking the firware asked for GPIO:
# we can do that by changing the variable 'firmptype' to ask for GPIO
if firmptype in ( _PD.ENCA,_PD.ENCB,_PD.ENCI,_PD.ENCM ):
if numofencoders >= (compnum+1):
# if the combobox is not already displaying the right component:
# then we need to set up the comboboxes for this pin, otherwise skip it
if self.widgets[ptype].get_model():
widgetptype = self.widgets[ptype].get_active_text()
else: widgetptype = None
if not widgetptype == firmptype or not self.d["_mesa%d_configured"%boardnum]:
self.widgets[pinv].set_sensitive(0)
self.widgets[pinv].set_active(0)
self.widgets[ptype].set_model(self.d._encoderliststore)
# serial encoders are not for AXES - filter AXES selections out
if sserialflag:
self.widgets[p].set_model(self.d._encodersignalfilter)
else:
self.widgets[p].set_model(self.d._encodersignaltree)
# we only add every 4th human name so the user can only select
# the encoder's 'A' signal name. If its the other signals
# we can add them all because pncconf controls what the user sees
if firmptype == _PD.ENCA:
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_active(0)
self.widgets[p].set_sensitive(1)
self.widgets[ptype].set_sensitive(0)
self.widgets[ptype].set_active(0)
# pncconf control what the user sees with these ones:
elif firmptype in(_PD.ENCB,_PD.ENCI,_PD.ENCM):
self.widgets[complabel].set_text("")
self.widgets[p].set_active(0)
self.widgets[p].set_sensitive(0)
self.widgets[ptype].set_sensitive(0)
for i,j in enumerate((_PD.ENCB,_PD.ENCI,_PD.ENCM)):
if firmptype == j:break
self.widgets[ptype].set_active(i+1)
else:
# user requested this encoder component to be GPIO instead
# We cheat a little and tell the rest of the method that the firmware says
# it should be GPIO and compnum is changed to signify that the GPIO can be changed
# from input to output
# Right now only mainboard GPIO can be changed
# sserial I/O can not
firmptype = _PD.GPIOI
compnum = 0
# --- mux encoder ---
elif firmptype in (_PD.MXE0,_PD.MXE1,_PD.MXEI,_PD.MXEM,_PD.MXES):
#print "**** INFO: MUX ENCODER:",firmptype,compnum,numofencoders
if numofencoders >= (compnum*2+1) or (firmptype == _PD.MXES and numofencoders >= compnum*2+1) or \
(firmptype == _PD.MXEM and numofencoders >= compnum +1):
# if the combobox is not already displaying the right component:
# then we need to set up the comboboxes for this pin, otherwise skip it
self.widgets[pinv].set_sensitive(0)
self.widgets[pinv].set_active(0)
pmodel = self.widgets[p].set_model(self.d._muxencodersignaltree)
ptmodel = self.widgets[ptype].set_model(self.d._muxencoderliststore)
self.widgets[ptype].set_active(_PD.pintype_muxencoder.index(firmptype))
self.widgets[ptype].set_sensitive(0)
self.widgets[p].set_active(0)
if firmptype in(_PD.MXE0,_PD.MXE1):
temp = 0
if firmptype == _PD.MXE1: temp = 1
self.widgets[complabel].set_text("%d:"%(compnum *2 + temp))
self.widgets[p].set_sensitive(1)
self.widgets[ptype].show()
self.widgets[p].show()
elif firmptype == _PD.MXEM:
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_sensitive(0)
self.widgets[ptype].show()
self.widgets[p].hide()
else:
self.widgets[complabel].set_text("")
self.widgets[p].set_sensitive(0)
self.widgets[ptype].hide()
self.widgets[p].hide()
else:
firmptype = _PD.GPIOI
compnum = 0
# ---SETUP GUI FOR RESOLVER FAMILY COMPONENTS---
elif firmptype in (_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5,_PD.RESU):
if 0 == 0:
self.widgets[pinv].set_sensitive(0)
self.widgets[pinv].set_active(0)
self.widgets[p].set_model(self.d._resolversignaltree)
self.widgets[ptype].set_model(self.d._resolverliststore)
self.widgets[ptype].set_sensitive(0)
self.widgets[ptype].set_active(0)
if firmptype == _PD.RESU:
self.widgets[complabel].set_text("")
self.widgets[p].hide()
self.widgets[p].set_sensitive(0)
self.widgets[p].set_active(0)
self.widgets[ptype].set_active(6)
else:
temp = (_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5)
self.widgets[p].show()
for num,i in enumerate(temp):
if firmptype == i:break
self.widgets[complabel].set_text("%d:"% (compnum*6+num))
self.widgets[p].set_sensitive(1)
self.widgets[p].set_active(0)
self.widgets[ptype].set_active(num)
# ---SETUP 8i20 amp---
elif firmptype == _PD.AMP8I20:
self.widgets[ptype].set_model(self.d._8i20liststore)
self.widgets[p].set_model(self.d._8i20signaltree)
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_active(0)
self.widgets[p].set_sensitive(1)
self.widgets[pinv].set_sensitive(1)
self.widgets[pinv].set_active(0)
self.widgets[ptype].set_sensitive(0)
self.widgets[ptype].set_active(0)
# --- SETUP potentiometer output
elif firmptype in (_PD.POTO,_PD.POTE):
self.widgets[ptype].set_model(self.d._potliststore)
self.widgets[p].set_model(self.d._potsignaltree)
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_active(0)
self.widgets[pinv].set_sensitive(1)
self.widgets[pinv].set_active(0)
self.widgets[ptype].set_sensitive(0)
if firmptype == _PD.POTO:
self.widgets[ptype].set_active(0)
self.widgets[p].set_sensitive(1)
else:
self.widgets[ptype].set_active(1)
self.widgets[p].set_sensitive(0)
# --- SETUP analog input
elif firmptype == (_PD.ANALOGIN):
self.widgets[ptype].set_model(self.d._analoginliststore)
self.widgets[p].set_model(self.d._analoginsignaltree)
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_active(0)
self.widgets[pinv].set_sensitive(1)
self.widgets[pinv].set_active(0)
self.widgets[ptype].set_sensitive(0)
self.widgets[ptype].set_active(0)
self.widgets[p].set_sensitive(1)
# ---SETUP GUI FOR PWM FAMILY COMPONENT---
# the user has a choice of pulse width or pulse density modulation
elif firmptype in ( _PD.PWMP,_PD.PWMD,_PD.PWME,_PD.PDMP,_PD.PDMD,_PD.PDME ):
if numofpwmgens >= (compnum+1):
self.widgets[pinv].set_sensitive(1)
self.widgets[pinv].set_active(0)
self.widgets[p].set_model(self.d._pwmsignaltree)
# only add the -pulse signal names for the user to see
if firmptype in(_PD.PWMP,_PD.PDMP):
self.widgets[complabel].set_text("%d:"%compnum)
#print "firmptype = controlling"
self.widgets[ptype].set_model(self.d._pwmcontrolliststore)
self.widgets[ptype].set_sensitive(not sserialflag) # sserial pwm cannot be changed
self.widgets[p].set_sensitive(1)
self.widgets[p].set_active(0)
self.widgets[ptype].set_active(0)
# add them all here
elif firmptype in (_PD.PWMD,_PD.PWME,_PD.PDMD,_PD.PDME):
self.widgets[complabel].set_text("")
#print "firmptype = related"
if firmptype in (_PD.PWMD,_PD.PWME):
self.widgets[ptype].set_model(self.d._pwmrelatedliststore)
else:
self.widgets[ptype].set_model(self.d._pdmrelatedliststore)
self.widgets[p].set_sensitive(0)
self.widgets[p].set_active(0)
self.widgets[ptype].set_sensitive(0)
temp = 1
if firmptype in (_PD.PWME,_PD.PDME):
self.widgets[pinv].set_sensitive(0)
temp = 2
self.widgets[ptype].set_active(temp)
else:
firmptype = _PD.GPIOI
compnum = 0
# ---SETUP GUI FOR TP PWM FAMILY COMPONENT---
elif firmptype in ( _PD.TPPWMA,_PD.TPPWMB,_PD.TPPWMC,_PD.TPPWMAN,_PD.TPPWMBN,_PD.TPPWMCN,_PD.TPPWME,_PD.TPPWMF ):
if numoftppwmgens >= (compnum+1):
if not self.widgets[ptype].get_active_text() == firmptype or not self.d["_mesa%d_configured"%boardnum]:
self.widgets[p].set_model(self.d._tppwmsignaltree)
self.widgets[ptype].set_model(self.d._tppwmliststore)
self.widgets[pinv].set_sensitive(0)
self.widgets[pinv].set_active(0)
self.widgets[ptype].set_sensitive(0)
self.widgets[ptype].set_active(_PD.pintype_tp_pwm.index(firmptype))
self.widgets[p].set_active(0)
# only add the -a signal names for the user to change
if firmptype == _PD.TPPWMA:
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_sensitive(1)
# the rest the user can't change
else:
self.widgets[complabel].set_text("")
self.widgets[p].set_sensitive(0)
else:
firmptype = _PD.GPIOI
compnum = 0
# ---SETUP SMART SERIAL COMPONENTS---
# smart serial has port numbers (0-3) and channels (0-7).
# so the component number check is different from other components it checks the port number and channel number
elif firmptype in (_PD.TXDATA0,_PD.RXDATA0,_PD.TXEN0,_PD.TXDATA1,_PD.RXDATA1,_PD.TXEN1,
_PD.TXDATA2,_PD.RXDATA2,_PD.TXEN2,_PD.TXDATA3,_PD.RXDATA3,_PD.TXEN3,
_PD.TXDATA4,_PD.RXDATA4,_PD.TXEN4,_PD.TXDATA5,_PD.RXDATA5,_PD.TXEN5,
_PD.TXDATA6,_PD.RXDATA6,_PD.TXEN6,_PD.TXDATA7,_PD.RXDATA7,_PD.TXEN7,
_PD.SS7I76M0,_PD.SS7I76M2,_PD.SS7I76M3,_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4):
channelnum = 1
if firmptype in (_PD.TXDATA1,_PD.RXDATA1,_PD.TXEN1,_PD.SS7I77M1): channelnum = 2
if firmptype in (_PD.TXDATA2,_PD.RXDATA2,_PD.TXEN2,_PD.SS7I76M2): channelnum = 3
if firmptype in (_PD.TXDATA3,_PD.RXDATA3,_PD.TXEN3,_PD.SS7I76M3,_PD.SS7I77M3): channelnum = 4
if firmptype in (_PD.TXDATA4,_PD.RXDATA4,_PD.TXEN4,_PD.SS7I77M4): channelnum = 5
if firmptype in (_PD.TXDATA5,_PD.RXDATA5,_PD.TXEN5): channelnum = 6
if firmptype in (_PD.TXDATA6,_PD.RXDATA6,_PD.TXEN6): channelnum = 7
if firmptype in (_PD.TXDATA7,_PD.RXDATA7,_PD.TXEN7): channelnum = 8
# control combobox is the one the user can select from others are unsensitized
CONTROL = False
if firmptype in (_PD.TXDATA0,_PD.TXDATA1,_PD.TXDATA2,_PD.TXDATA3,_PD.TXDATA4,_PD.TXDATA5,
_PD.TXDATA6,_PD.TXDATA7,_PD.SS7I76M0,_PD.SS7I76M2,_PD.SS7I76M3,
_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4):
CONTROL = True
#print "**** INFO: SMART SERIAL ENCODER:",firmptype," compnum = ",compnum," channel = ",channelnum
#print "sserial channel:%d"% numofsserialchannels
if numofsserialports >= (compnum + 1) and numofsserialchannels >= (channelnum):
# if the combobox is not already displaying the right component:
# then we need to set up the comboboxes for this pin, otherwise skip it
#if compnum < _PD._NUM_CHANNELS: # TODO not all channels available
# self.widgets["mesa%dsserialtab%d"% (boardnum,compnum)].show()
self.widgets[pinv].set_sensitive(0)
self.widgets[pinv].set_active(0)
# Filter the selection that the user can choose.
# eg only show two modes for 7i77 and 7i76 or
# don't give those selections on regular sserial channels
if CONTROL:
self.widgets[p].set_model(self.d['_sserial%d_signalfilter'%(channelnum-1)])
if firmptype in (_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4):
self.set_filter('_sserial%d'% (channelnum-1),'7I77')
elif firmptype in (_PD.SS7I76M0,_PD.SS7I76M2,_PD.SS7I76M3):
self.set_filter('_sserial%d'% (channelnum-1),'7I76')
else:
self.set_filter('_sserial%d'% (channelnum-1),'ALL')
else:
self.widgets[p].set_model(self.d._sserialsignaltree)
self.widgets[ptype].set_model(self.d._sserialliststore)
self.widgets[ptype].set_active(_PD.pintype_sserial.index(firmptype))
self.widgets[ptype].set_sensitive(0)
self.widgets[p].set_active(0)
self.widgets[p].child.set_editable(False) # sserial cannot have custom names
# controlling combbox
if CONTROL:
self.widgets[complabel].set_text("%d:"% (channelnum -1))
if channelnum <= _PD._NUM_CHANNELS:#TODO not all channels available
self.widgets[p].set_sensitive(1)
else:
self.widgets[p].set_sensitive(0)
# This is a bit of a hack to make 7i77 and 7i76 firmware automatically choose
# the apropriate sserial component and allow the user to select different modes
# if the sserial ptype is 7i76 or 7i77 then the data must be set to 7i76/7i77 signal
# as that sserial instance can only be for the 7i76/7i77 I/O points
# 7i76:
if firmptype in (_PD.SS7I76M0,_PD.SS7I76M2,_PD.SS7I76M3):
if not self.d[p] in (_PD.I7I76_M0_T,_PD.I7I76_M2_T):
self.d[p] = _PD.I7I76_M0_T
self.d[ptype] = firmptype
self.widgets[p].set_sensitive(self.d.advanced_option)
# 7i77:
elif firmptype in (_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4):
if not self.d[p] in (_PD.I7I77_M3_T,_PD.I7I77_M0_T):
self.d[p] = _PD.I7I77_M0_T
if not firmptype in( _PD.SS7I77M1,_PD.SS7I77M4):
self.widgets[p].set_sensitive(self.d.advanced_option)
else:
self.widgets[p].set_sensitive(0)
self.d[ptype] = firmptype
else:
print 'found a sserial channel'
ssdevice = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._SSDEVICES]
for port,channel,device in (ssdevice):
print port,channel,device,channelnum
if port == 0 and channel+1 == channelnum:
print 'configure for: %s device'% device
if '7I64' in device:
if not '7i64' in self.d[p]:
self.d[p] = _PD.I7I64_T
elif '7I73' in device:
if not '7i73' in self.d[p]:
self.d[p] = _PD.I7I73_M0_T
else:
self.widgets[complabel].set_text("")
self.widgets[p].set_sensitive(0)
else:
firmptype = _PD.GPIOI
compnum = 0
# ---SETUP FOR STEPPER FAMILY COMPONENT---
elif firmptype in (_PD.STEPA,_PD.STEPB):
if numofstepgens >= (compnum+1):
self.widgets[ptype].set_model(self.d._stepperliststore)
self.widgets[p].set_model(self.d._steppersignaltree)
self.widgets[pinv].set_sensitive(1)
self.widgets[pinv].set_active(0)
self.widgets[ptype].set_sensitive(0)
self.widgets[ptype].set_active( _PD.pintype_stepper.index(firmptype) )
self.widgets[p].set_active(0)
#self.widgets[p].set_active(0)
if firmptype == _PD.STEPA:
self.widgets[complabel].set_text("%d:"%compnum)
self.widgets[p].set_sensitive(1)
elif firmptype == _PD.STEPB:
self.widgets[complabel].set_text("")
self.widgets[p].set_sensitive(0)
else:
firmptype = _PD.GPIOI
compnum = 0
# ---SETUP FOR GPIO FAMILY COMPONENT---
# first check to see if firmware says it should be in GPIO family
# (note this can be because firmware says it should be some other
# type but the user wants to deselect it so as to use it as GPIO
# this is done in the firmptype checks before this check.
# They will change firmptype variable to GPIOI)
# check if firmptype is in GPIO family
# check if widget is already configured
# we now set everything in a known state.
if firmptype in (_PD.GPIOI,_PD.GPIOO,_PD.GPIOD,_PD.SSR0):
if self.widgets[ptype].get_model():
widgettext = self.widgets[ptype].get_active_text()
else:
widgettext = None
if sserialflag:
if "7i77" in subboardname or "7i76" in subboardname or "7i84" in subboardname:
if pin <16:
self.widgets[complabel].set_text("%02d:"%(pin)) # sserial input
elif (pin >23 and pin < 40):
self.widgets[complabel].set_text("%02d:"%(pin-8)) # sserial input
elif pin >15 and pin < 24:
self.widgets[complabel].set_text("%02d:"%(pin-16)) #sserial output
elif pin >39:
self.widgets[complabel].set_text("%02d:"%(pin-32)) #sserial output
elif "7i70" in subboardname or "7i71" in subboardname:
self.widgets[complabel].set_text("%02d:"%(pin))
else:
if pin <24 :
self.widgets[complabel].set_text("%02d:"%(concount*24+pin)) # sserial input
else:
self.widgets[complabel].set_text("%02d:"%(concount*24+pin-24)) #sserial output
else:
if firmptype == _PD.SSR0:
self.widgets[complabel].set_text("%02d:"%(compnum - 100))
else:
self.widgets[complabel].set_text("%03d:"%(concount*ppc+pin))# mainboard GPIO
if compnum >= 100 and widgettext == firmptype:
return
elif not compnum >= 100 and (widgettext in (_PD.GPIOI,_PD.GPIOO,_PD.GPIOD)):
return
else:
#self.widgets[ptype].show()
#self.widgets[p].show()
self.widgets[p].set_sensitive(1)
self.widgets[pinv].set_sensitive(1)
self.widgets[ptype].set_sensitive(not compnum >= 100) # compnum = 100 means GPIO cannot be changed by user
if firmptype == _PD.SSR0:
self.widgets[ptype].set_model(self.d._ssrliststore)
else:
self.widgets[ptype].set_model(self.d._gpioliststore)
if firmptype == _PD.GPIOI:
# set pin treestore to gpioi signals
if not self.widgets[p].get_model() == self.d._gpioisignaltree:
self.widgets[p].set_model(self.d._gpioisignaltree)
# set ptype gpioi
self.widgets[ptype].set_active(0)
# set p unused signal
self.widgets[p].set_active(0)
# set pinv unset
self.widgets[pinv].set_active(False)
elif firmptype == _PD.SSR0:
if not self.widgets[p].get_model() == self.d._gpioosignaltree:
self.widgets[p].set_model(self.d._gpioosignaltree)
# set ptype gpioo
self.widgets[ptype].set_active(0)
# set p unused signal
self.widgets[p].set_active(0)
# set pinv unset
self.widgets[pinv].set_active(False)
else:
if not self.widgets[p].get_model() == self.d._gpioosignaltree:
self.widgets[p].set_model(self.d._gpioosignaltree)
# set ptype gpioo
self.widgets[ptype].set_active(1)
# set p unused signal
self.widgets[p].set_active(0)
# set pinv unset
self.widgets[pinv].set_active(False)
def find_sig_name_iter(self,model, signal_name):
for i, k in enumerate(model):
itr = model.get_iter(i)
title = model.get_value(itr,2)
#print 'first:',title
# check first set
if title == signal_name :return itr
cld_itr = model.iter_children(itr)
if cld_itr != None:
while cld_itr != None:
gcld_itr = model.iter_children(cld_itr)
if gcld_itr != None:
while gcld_itr != None:
title = model.get_value(gcld_itr,2)
#print title
# check third set
if title == signal_name :return gcld_itr
gcld_itr = model.iter_next(gcld_itr)
title = model.get_value(cld_itr,2)
#print title
# check second set
if title == signal_name :return cld_itr
cld_itr = model.iter_next(cld_itr)
# return first entry if no signal name is found
return model.get_iter_first()
def mesa_mainboard_data_to_widgets(self,boardnum):
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]) :
for pin in range (0,24):
firmptype,compnum = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._STARTOFDATA+pin+(concount*24)]
p = 'mesa%dc%dpin%d' % (boardnum, connector, pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum, connector , pin)
pinv = 'mesa%dc%dpin%dinv' % (boardnum, connector , pin)
self.data_to_widgets(boardnum,firmptype,compnum,p,ptype,pinv)
# by now the widgets should be right according to the firmware (and user deselected components)
# now we apply the data - setting signalnames and possible changing the pintype choice (eg pwm to pdm)
# We need to only set the 'controlling' signalname the pinchanged method will be called
# immediately and set the 'related' pins (if there are related pins)
def data_to_widgets(self,boardnum,firmptype,compnum,p,ptype,pinv):
debug = False
datap = self.d[p]
dataptype = self.d[ptype]
datapinv = self.d[pinv]
widgetp = self.widgets[p].get_active_text()
widgetptype = self.widgets[ptype].get_active_text()
#print "**** INFO set-data-options DATA:",p,datap,dataptype
#print "**** INFO set-data-options WIDGET:",p,widgetp,widgetptype
# ignore related pins
if widgetptype in (_PD.ENCB,_PD.ENCI,_PD.ENCM,
_PD.MXEI,_PD.MXEM,_PD.MXES,
_PD.RESU,
_PD.STEPB,_PD.STEPC,_PD.STEPD,_PD.STEPE,_PD.STEPF,
_PD.PDMD,_PD.PDME,_PD.PWMD,_PD.PWME,_PD.UDMD,_PD.UDME,
_PD.TPPWMB,_PD.TPPWMC,_PD.TPPWMAN,_PD.TPPWMBN,_PD.TPPWMCN,_PD.TPPWME,_PD.TPPWMF,
_PD.NUSED,_PD.POTD,_PD.POTE,
_PD.RXDATA0,_PD.TXEN0,_PD.RXDATA1,_PD.TXEN1,_PD.RXDATA2,_PD.TXEN2,_PD.RXDATA3,_PD.TXEN3,
_PD.RXDATA4,_PD.TXEN4,_PD.RXDATA5,_PD.TXEN5,_PD.RXDATA6,_PD.TXEN6,_PD.RXDATA7,_PD.TXEN7
):
self.widgets[pinv].set_active(datapinv)
return
# TODO fix this for cmboboxes withgrandchildren
# we are searching through human names - why not just search the model?
# type GPIO
# if compnum = 100 then it means that the GPIO type can not
# be changed from what the firmware designates it as.
if widgetptype in (_PD.GPIOI,_PD.GPIOO,_PD.GPIOD,_PD.SSR0):
#print "data ptype index:",_PD.pintype_gpio.index(dataptype)
#self.debug_iter(0,p,"data to widget")
#self.debug_iter(0,ptype,"data to widget")
# signal names for GPIO INPUT
#print "compnum = ",compnum
if compnum >= 100: dataptype = widgetptype
self.widgets[pinv].set_active(self.d[pinv])
if widgetptype == _PD.SSR0:
self.widgets[ptype].set_active(0)
else:
try:
self.widgets[ptype].set_active( _PD.pintype_gpio.index(dataptype) )
except:
self.widgets[ptype].set_active( _PD.pintype_gpio.index(widgetptype) )
# if GPIOI or dataptype not in GPIO family force it GPIOI
if dataptype == _PD.GPIOI or dataptype not in(_PD.GPIOO,_PD.GPIOI,_PD.GPIOD,_PD.SSR0):
human = _PD.human_input_names
signal = _PD.hal_input_names
tree = self.d._gpioisignaltree
# signal names for GPIO OUTPUT and OPEN DRAIN OUTPUT
elif dataptype in (_PD.GPIOO,_PD.GPIOD,_PD.SSR0):
human = _PD.human_output_names
signal = _PD.hal_output_names
tree = self.d._gpioosignaltree
self.widgets[p].set_model(tree)
itr = self.find_sig_name_iter(tree, datap)
self.widgets[p].set_active_iter(itr)
# type encoder / mux encoder
# we find the data's signal index
# then we search through the combobox's actual model's 4th array index
# this contains the comboxbox's signal's index number
# when they match then that is the row to show in the combobox
# this is different because the sserial combobox's model
# can be filtered and that screws with the relationship of
# signalname array vrs model row
elif widgetptype == _PD.ENCA or widgetptype in(_PD.MXE0,_PD.MXE1):
#print "ENC ->dataptype:",self.d[ptype]," dataptype:",self.d[p],signalindex
pinmodel = self.widgets[p].get_model()
itr = self.find_sig_name_iter(pinmodel, datap)
self.widgets[p].set_active_iter(itr)
# type resolver
elif widgetptype in(_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5,_PD.RESU):
try:
signalindex = _PD.hal_resolver_input_names.index(datap)
except:
if debug: print "**** INFO: PNCCONF warning no resolver signal named: %s\n found for pin %s"% (datap ,p)
signalindex = 0
#print "dataptype:",self.d[ptype]," dataptype:",self.d[p],signalindex
count = 0
temp = (0) # set unused resolver
if signalindex > 0:
for row,parent in enumerate(_PD.human_resolver_input_names):
if row == 0: continue
if len(parent[1]) == 0:
count +=1
#print row,count,"parent-",parent[0]
if count == signalindex:
#print "match",row
temp = (row)
break
continue
for column,child in enumerate(parent[1]):
count +=1
#print row,column,count,parent[0],child
if count == signalindex:
#print "match",row
temp = (row,column)
break
if count >= signalindex:break
#print "temp",temp
treeiter = self.d._resolversignaltree.get_iter(temp)
self.widgets[p].set_active_iter(treeiter)
# Type 8i20 AMP
elif widgetptype == _PD.AMP8I20:
try:
signalindex = _PD.hal_8i20_input_names.index(datap)
except:
if debug: print "**** INFO: PNCCONF warning no 8i20 signal named: %s\n found for pin %s"% (datap ,p)
signalindex = 0
#print "dataptype:",self.d[ptype]," dataptype:",self.d[p],signalindex
count = 0
temp = (0) # set unused 8i20 amp
if signalindex > 0:
for row,parent in enumerate(_PD.human_8i20_input_names):
if row == 0: continue
if len(parent[1]) == 0:
count +=1
#print row,count,"parent-",parent[0]
if count == signalindex:
#print "match",row
temp = (row)
break
continue
for column,child in enumerate(parent[1]):
count +=1
#print row,column,count,parent[0],child
if count == signalindex:
#print "match",row
temp = (row,column)
break
if count >= signalindex:break
#print "temp",temp
treeiter = self.d._8i20signaltree.get_iter(temp)
self.widgets[p].set_active_iter(treeiter)
# Type potentiometer (7i76"s spindle control)
elif widgetptype in (_PD.POTO,_PD.POTE):
self.widgets[pinv].set_active(self.d[pinv])
try:
signalindex = _PD.hal_pot_output_names.index(datap)
except:
if debug: print "**** INFO: PNCCONF warning no potentiometer signal named: %s\n found for pin %s"% (datap ,p)
signalindex = 0
#print "dataptype:",self.d[ptype]," dataptype:",self.d[p],signalindex
count = -1
temp = (0) # set unused potentiometer
if signalindex > 0:
for row,parent in enumerate(_PD.human_pot_output_names):
if row == 0: continue
if len(parent[1]) == 0:
count +=2
#print row,count,"parent-",parent[0]
if count == signalindex:
#print "match",row
temp = (row)
break
continue
for column,child in enumerate(parent[1]):
count +=2
#print row,column,count,parent[0],child
if count == signalindex:
#print "match",row
temp = (row,column)
break
if count >= signalindex:break
#print "temp",temp
treeiter = self.d._potsignaltree.get_iter(temp)
self.widgets[p].set_active_iter(treeiter)
# Type analog in
elif widgetptype == _PD.ANALOGIN:
try:
signalindex = _PD.hal_analog_input_names.index(datap)
except:
if debug: print "**** INFO: PNCCONF warning no analog in signal named: %s\n found for pin %s"% (datap ,p)
signalindex = 0
#print "dataptype:",self.d[ptype]," dataptype:",self.d[p],signalindex
count = 0
temp = (0) # set unused 8i20 amp
if signalindex > 0:
for row,parent in enumerate(_PD.human_analog_input_names):
if row == 0: continue
if len(parent[1]) == 0:
count +=1
#print row,count,"parent-",parent[0]
if count == signalindex:
#print "match",row
temp = (row)
break
continue
for column,child in enumerate(parent[1]):
count +=1
#print row,column,count,parent[0],child
if count == signalindex:
#print "match",row
temp = (row,column)
break
if count >= signalindex:break
#print "temp",temp
treeiter = self.d._analoginsignaltree.get_iter(temp)
self.widgets[p].set_active_iter(treeiter)
# type PWM gen
elif widgetptype in (_PD.PDMP,_PD.PWMP,_PD.UDMU):
self.widgets[pinv].set_active(datapinv)
if self.widgets["mesa%d_numof_resolvers"% boardnum].get_value(): dataptype = _PD.UDMU # hack resolver board needs UDMU
if dataptype == _PD.PDMP:
#print "pdm"
self.widgets[ptype].set_model(self.d._pdmcontrolliststore)
self.widgets[ptype].set_active(1)
elif dataptype == _PD.PWMP:
#print "pwm",self.d._pwmcontrolliststore
self.widgets[ptype].set_model(self.d._pwmcontrolliststore)
self.widgets[ptype].set_active(0)
elif dataptype == _PD.UDMU:
#print "udm",self.d._udmcontrolliststore
self.widgets[ptype].set_model(self.d._udmcontrolliststore)
self.widgets[ptype].set_active(2)
itr = self.find_sig_name_iter(self.d._pwmsignaltree, datap)
self.widgets[p].set_active_iter(itr)
# type tp 3 pwm for direct brushless motor control
elif widgetptype == _PD.TPPWMA:
#print "3 pwm"
count = -7
try:
signalindex = _PD.hal_tppwm_output_names.index(datap)
except:
if debug: print "**** INFO: PNCCONF warning no THREE PWM signal named: %s\n found for pin %s"% (datap ,p)
signalindex = 0
#print "3 PWw ,dataptype:",self.d[ptype]," dataptype:",self.d[p],signalindex
temp = (0) # set unused stepper
if signalindex > 0:
for row,parent in enumerate(_PD.human_tppwm_output_names):
if row == 0:continue
if len(parent[1]) == 0:
count += 8
#print row,count,parent[0]
if count == signalindex:
#print "match",row
temp = (row)
break
continue
for column,child in enumerate(parent[1]):
count +=8
#print row,column,count,parent[0],child
if count == signalindex:
#print "match",row
temp = (row,column)
break
if count >= signalindex:break
treeiter = self.d._tppwmsignaltree.get_iter(temp)
self.widgets[p].set_active_iter(treeiter)
# type step gen
elif widgetptype == _PD.STEPA:
#print "stepper", dataptype
self.widgets[ptype].set_active(0)
self.widgets[p].set_active(0)
self.widgets[pinv].set_active(datapinv)
itr = self.find_sig_name_iter(self.d._steppersignaltree, datap)
self.widgets[p].set_active_iter(itr)
# type smartserial
# we do things differently here
# we find the data's signal index
# then we search through the combobox's model's 4th array index
# this contains the comboxbox's signal's index number
# when they match then that is the row to show in the combobox
# this is different because the sserial combobox's model
# can be filtered and that screws with the relationship of
# signalname array vrs model row
elif widgetptype in( _PD.TXDATA0,_PD.SS7I76M0,_PD.SS7I77M0,_PD.SS7I77M3,_PD.TXDATA1,
_PD.TXDATA2,_PD.TXDATA3,_PD.TXDATA4,_PD.TXDATA5,_PD.TXDATA6,_PD.TXDATA7,
_PD.SS7I76M2,_PD.SS7I76M3,_PD.SS7I77M1,_PD.SS7I77M4):
#print "SMART SERIAL", dataptype,widgetptype
self.widgets[pinv].set_active(datapinv)
try:
signalindex = _PD.hal_sserial_names.index(self.d[p])
except:
if debug: print "**** INFO: PNCCONF warning no SMART SERIAL signal named: %s\n found for pin %s"% (datap ,p)
signalindex = 0
pinmodel = self.widgets[p].get_model()
for row,parent in enumerate(pinmodel):
#print row,parent[0],parent[2],parent[3],parent[4]
if parent[4] == signalindex:
#print 'FOUND',parent[2],parent[4]
treeiter = pinmodel.get_iter(row)
self.widgets[p].set_active_iter(treeiter)
else:
print "**** WARNING: PNCCONF data to widget: ptype not recognized/match:",dataptype,widgetptype
# This is for when a user picks a signal name or creates a custom signal (by pressing enter)
# if searches for the 'related pins' of a component so it can update them too
# it also handles adding and updating custom signal names
# it is used for mesa boards and parport boards according to boardtype
def on_general_pin_changed(self, widget, boardtype, boardnum, connector, channel, pin, custom):
self.p.set_buttons_sensitive(0,0)
if boardtype == "sserial":
p = 'mesa%dsserial%d_%dpin%d' % (boardnum,connector,channel,pin)
ptype = 'mesa%dsserial%d_%dpin%dtype' % (boardnum,connector,channel,pin)
widgetptype = self.widgets[ptype].get_active_text()
#print "pinchanged-",p
elif boardtype == "mesa":
p = 'mesa%dc%dpin%d' % (boardnum,connector,pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum,connector,pin)
widgetptype = self.widgets[ptype].get_active_text()
elif boardtype == "parport":
p = '%s_%s%d' % (boardnum,connector, pin)
#print p
if "I" in p: widgetptype = _PD.GPIOI
else: widgetptype = _PD.GPIOO
pinchanged = self.widgets[p].get_active_text()
piter = self.widgets[p].get_active_iter()
signaltree = self.widgets[p].get_model()
try:
basetree = signaltree.get_model()
except:
basetree = signaltree
#print "generalpin changed",p
#print "*** INFO ",boardtype,"-pin-changed: pin:",p,"custom:",custom
#print "*** INFO ",boardtype,"-pin-changed: ptype:",widgetptype,"pinchaanged:",pinchanged
if piter == None and not custom:
#print "*** INFO ",boardtype,"-pin-changed: no iter and not custom"
self.p.set_buttons_sensitive(1,1)
return
if widgetptype in (_PD.ENCB,_PD.ENCI,_PD.ENCM,
_PD.MXEI,_PD.MXEM,_PD.MXES,
_PD.RESU,
_PD.STEPB,_PD.STEPC,_PD.STEPD,_PD.STEPE,_PD.STEPF,
_PD.PDMD,_PD.PDME,_PD.PWMD,_PD.PWME,_PD.UDMD,_PD.UDME,
_PD.TPPWMB,_PD.TPPWMC,_PD.TPPWMAN,_PD.TPPWMBN,_PD.TPPWMCN,_PD.TPPWME,_PD.TPPWMF,
_PD.RXDATA0,_PD.TXEN0,_PD.RXDATA1,_PD.TXEN1,_PD.RXDATA2,_PD.TXEN2,_PD.RXDATA3,_PD.TXEN3,
_PD.POTE,_PD.POTD, _PD.SSR0):
self.p.set_buttons_sensitive(1,1)
return
# for GPIO output
if widgetptype in (_PD.GPIOO,_PD.GPIOD):
#print"ptype GPIOO\n"
halsignallist = 'hal_output_names'
humansignallist = _PD.human_output_names
addsignalto = self.d.haloutputsignames
relatedsearch = ["dummy"]
relatedending = [""]
customindex = len(humansignallist)-1
# for GPIO input
elif widgetptype == _PD.GPIOI:
#print"ptype GPIOI\n"
halsignallist = 'hal_input_names'
humansignallist = _PD.human_input_names
addsignalto = self.d.halinputsignames
relatedsearch = ["dummy"]
relatedending = [""]
customindex = len(humansignallist)-1
# for stepgen pins
elif widgetptype == _PD.STEPA:
#print"ptype step\n"
halsignallist = 'hal_stepper_names'
humansignallist = _PD.human_stepper_names
addsignalto = self.d.halsteppersignames
relatedsearch = [_PD.STEPA,_PD.STEPB,_PD.STEPC,_PD.STEPD,_PD.STEPE,_PD.STEPF]
relatedending = ["-step","-dir","-c","-d","-e","-f"]
customindex = len(humansignallist)-1
# for encoder pins
elif widgetptype == _PD.ENCA:
#print"\nptype encoder"
halsignallist = 'hal_encoder_input_names'
humansignallist = _PD.human_encoder_input_names
addsignalto = self.d.halencoderinputsignames
relatedsearch = [_PD.ENCA,_PD.ENCB,_PD.ENCI,_PD.ENCM]
relatedending = ["-a","-b","-i","-m"]
customindex = len(humansignallist)-1
# for mux encoder pins
elif widgetptype in(_PD.MXE0,_PD.MXE1):
#print"\nptype encoder"
halsignallist = 'hal_encoder_input_names'
humansignallist = _PD.human_encoder_input_names
addsignalto = self.d.halencoderinputsignames
relatedsearch = ["dummy","dummy","dummy","dummy",]
relatedending = ["-a","-b","-i","-m"]
customindex = len(humansignallist)-1
# resolvers
elif widgetptype in (_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5):
halsignallist = 'hal_resolver_input_names'
humansignallist = _PD.human_resolver_input_names
addsignalto = self.d.halresolversignames
relatedsearch = ["dummy"]
relatedending = [""]
customindex = len(humansignallist)-1
# 8i20 amplifier
elif widgetptype == _PD.AMP8I20:
halsignallist = 'hal_8i20_input_names'
humansignallist = _PD.human_8i20_input_names
addsignalto = self.d.hal8i20signames
relatedsearch = ["dummy"]
relatedending = [""]
customindex = len(humansignallist)-1
# potentiometer output
elif widgetptype == _PD.POTO:
halsignallist = 'hal_pot_output_names'
humansignallist = _PD.human_pot_output_names
addsignalto = self.d.halpotsignames
relatedsearch = [_PD.POTO,_PD.POTE]
relatedending = ["-output","-enable"]
customindex = 2
# analog input
elif widgetptype == _PD.ANALOGIN:
halsignallist = 'hal_analog_input_names'
humansignallist = _PD.human_analog_input_names
addsignalto = self.d.halanaloginsignames
relatedsearch = ["dummy"]
relatedending = [""]
customindex = len(humansignallist)-1
# for PWM,PDM,UDM pins
elif widgetptype in(_PD.PWMP,_PD.PDMP,_PD.UDMU):
#print"ptype pwmp\n"
halsignallist = 'hal_pwm_output_names'
humansignallist = _PD.human_pwm_output_names
addsignalto = self.d.halpwmoutputsignames
relatedsearch = [_PD.PWMP,_PD.PWMD,_PD.PWME]
relatedending = ["-pulse","-dir","-enable"]
customindex = len(humansignallist)-1
elif widgetptype == _PD.TPPWMA:
#print"ptype pdmp\n"
halsignallist = 'hal_tppwm_output_names'
humansignallist = _PD.human_tppwm_output_names
addsignalto = self.d.haltppwmoutputsignames
relatedsearch = [_PD.TPPWMA,_PD.TPPWMB,_PD.TPPWMC,_PD.TPPWMAN,_PD.TPPWMBN,_PD.TPPWMCN,_PD.TPPWME,_PD.TPPWMF]
relatedending = ["-a","-b","c","-anot","-bnot","cnot","-enable","-fault"]
customindex = len(humansignallist)-1
elif widgetptype in (_PD.TXDATA0,_PD.TXDATA1,_PD.TXDATA2,_PD.TXDATA3,_PD.TXDATA4,_PD.TXDATA5,_PD.SS7I76M0,_PD.SS7I76M3,
_PD.SS7I76M2,_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4):
portnum = 0 #TODO support more ports
for count,temp in enumerate(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]) :
if connector == temp:
firmptype,portnum = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._STARTOFDATA+pin+(count*24)]
if widgetptype in (_PD.TXDATA0,_PD.SS7I76M0,_PD.SS7I77M0): channelnum = 0
elif widgetptype in (_PD.TXDATA1,_PD.SS7I77M1): channelnum = 1
elif widgetptype in (_PD.TXDATA2,_PD.SS7I76M2): channelnum = 2
elif widgetptype in (_PD.TXDATA3,_PD.SS7I77M3,_PD.SS7I76M3): channelnum = 3
elif widgetptype in (_PD.TXDATA4,_PD.SS7I77M4): channelnum = 4
elif widgetptype in (_PD.TXDATA5): channelnum = 5
BASE = "mesa%dsserial0_%d"% (boardnum,channelnum)
if self.widgets[p].get_active_text() == _("Unused Channel"):
self.widgets[BASE].hide()
self.d[BASE+"subboard"] = "none"
self.p.set_buttons_sensitive(1,1)
return
else:
self.widgets[BASE].show()
# TODO we should search for these names rather then use hard coded logic
# so as to make adding cards easier
temp = self.widgets[p].get_active_text()
table = BASE+"table2"
self.widgets[table].show()
table = BASE+"table3"
self.widgets[table].show()
if "7i76" in temp:
if 'Mode 2' in temp:
ssfirmname = "7i76-m2"
else:
ssfirmname = "7i76-m0"
self.d[BASE+"subboard"] = ssfirmname
self.widgets[BASE+'_tablabel'].set_text("7I76 I/O\n (SS# %d)"% channelnum)
elif "7i64" in temp:
self.d[BASE+"subboard"] = "7i64"
self.widgets[BASE+'_tablabel'].set_text("7I64 I/O\n (SS# %d)"% channelnum)
elif "7i69" in temp:
self.d[BASE+"subboard"] = "7i69"
self.widgets[table].hide()
self.widgets[BASE+'_tablabel'].set_text("7I69 I/O\n (SS# %d)"% channelnum)
elif "7i70" in temp:
self.d[BASE+"subboard"] = "7i70"
self.widgets[table].hide()
self.widgets[BASE+'_tablabel'].set_text("7I70 I/O\n (SS# %d)"% channelnum)
elif "7i71" in temp:
self.d[BASE+"subboard"] = "7i71"
self.widgets[table].hide()
self.widgets[BASE+'_tablabel'].set_text("7I71 I/O\n (SS# %d)"% channelnum)
elif "7i73" in temp:
self.d[BASE+"subboard"] = "7i73-m1"
self.widgets[BASE+'_tablabel'].set_text("7I73 I/O\n (SS# %d)"% channelnum)
elif "7i77" in temp:
print 'ssname',temp,'sschannel#',channelnum
if 'Mode 3' in temp:
ssfirmname = "7i77-m3"
else:
ssfirmname = "7i77-m0"
self.d[BASE+"subboard"] = ssfirmname
if channelnum in(0,3):
self.widgets[BASE+'_tablabel'].set_text("7I77 I/O\n (SS# %d)"% channelnum)
self.widgets[table].hide()
elif channelnum in(1,4):
self.widgets[BASE+'_tablabel'].set_text("7I77 PWM\n (SS# %d)"% channelnum)
table = BASE+"table2"
self.widgets[table].hide()
table = BASE+"table1"
self.widgets[table].hide()
elif "7i84" in temp:
print 'ssname',temp,'sschannel#',channelnum
if 'Mode 3' in temp:
ssfirmname = "7i84-m3"
else:
ssfirmname = "7i84-m0"
self.d[BASE+"subboard"] = ssfirmname
self.widgets[table].hide()
self.widgets[BASE+'_tablabel'].set_text("7I84 I/O\n (SS# %d)"%channelnum)
elif "8i20" in temp:
self.d[BASE+"subboard"] = "8i20"
self.widgets[table].hide()
table = BASE+"table2"
self.widgets[table].hide()
self.widgets[BASE+'_tablabel'].set_text("8I20\n (SS# %d)"% channelnum)
else:
self.d[BASE+"subboard"] = "none"
self.widgets[table].hide()
table = BASE+"table2"
self.widgets[table].hide()
table = BASE+"table1"
self.widgets[table].hide()
self.p.set_buttons_sensitive(1,1)
return
# set sserial tab names to corresond to connector numbers so users have a clue
# first we have to find the daughter board in pncconf's internal list
# TODO here we search the list- this should be done for the table names see above todo
subfirmname = self.d[BASE+"subboard"]
for subnum,temp in enumerate(self._p.MESA_DAUGHTERDATA):
if self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBFIRMNAME] == subfirmname: break
subconlist = self._p.MESA_DAUGHTERDATA[subnum][self._p._SUBCONLIST]
# now search the connector list and write it to the tab names
for tabnum in range(0,3):
conname = subconlist[tabnum]
tab = BASE+"tab%d"% tabnum
self.widgets[tab].set_text(conname)
#print p,temp," set at",self.d[BASE+"subboard"]
self.set_sserial_options(boardnum,portnum,channelnum)
self.p.set_buttons_sensitive(1,1)
return
self.p.set_buttons_sensitive(1,1)
return
else:
print"**** INFO: pncconf on_general_pin_changed: pintype not found:%s\n"% widgetptype
self.p.set_buttons_sensitive(1,1)
return
# *** change the related pin's signal names ***
# see if the piter is none - if it is a custom names has been entered
# else find the signal name index number if the index is zero set the piter to unused signal
# this is a work around for thye combo box allowing the parent to be shown and selected in the
# child column haven\t figured out how to stop that #TODO
# either way we have to search the current firmware array for the pin numbers of the related
# pins so we can change them to the related signal name
# all signal names have related signal (eg encoders have A and B phase and index and index mask)
# except 'unused' signal it is a special case as there is no related signal names with it.
if piter == None or custom:
#print "*** INFO ",boardtype,"-pin-changed: PITER:",piter," length:",len(signaltree)
if pinchanged in (addsignalto):return
for i in (humansignallist):
if pinchanged == i[0]:return
if pinchanged in i[1]:return
length = len(signaltree)
index = len(_PD[halsignallist]) - len(relatedsearch)
customiter = signaltree.get_iter((length-1,))
childiter = signaltree.iter_nth_child(customiter, 0)
n = 0
while childiter:
dummy, index = signaltree.get(childiter, 0, 1)
n+=1
childiter = signaltree.iter_nth_child(customiter, n)
index += len(relatedsearch)
else:
dummy, index = signaltree.get(piter, 0, 1)
if index == 0:
piter = signaltree.get_iter_first()
#print "*** INFO ",boardtype,"-pin-changed: index",index
# This finds the pin type and component number of the pin that has changed
pinlist = []
# this components have no related pins - fake the list
if widgetptype in(_PD.GPIOI,_PD.GPIOO,_PD.GPIOD,_PD.SSR0,_PD.MXE0,_PD.MXE1,_PD.RES0,_PD.RES1,
_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5,_PD.AMP8I20,_PD.ANALOGIN):
pinlist = [["%s"%p,boardnum,connector,channel,pin]]
else:
pinlist = self.list_related_pins(relatedsearch, boardnum, connector, channel, pin, 0)
#print pinlist
# Now we have a list of pins that need to be updated
# first check if the name is a custom name if it is
# add the legalized custom name to ;
# addsignalto -> for recording custom names for next time loaded
# signalsto check -> for making signal names (we add different endings for different signalnames
# signaltree -> for display in the gui - itis automatically added to all comboboxes that uses this treesort
# then go through the pinlist:
# block signals
# display the proper text depending if custom or not
# then unblock signals
if custom:
legal_name = pinchanged.replace(" ","_")
addsignalto.append ((legal_name))
print "add: "+legal_name+" to human list",humansignallist[customindex][1]
humansignallist[customindex][1].append ((legal_name))
endoftree = len(basetree)-1
customiter = basetree.get_iter((endoftree,))
newiter = basetree.append(customiter, [legal_name,index,legal_name,halsignallist,index])
#print 'new signal:',legal_name,index,legal_name,halsignallist,endoftree,index
for offset,i in enumerate(relatedsearch):
with_endings = legal_name + relatedending[offset]
#print "new signal:",with_endings
_PD[halsignallist].append ((with_endings))
for data in(pinlist):
if boardtype == "mesa":
blocksignal1 = "_mesa%dsignalhandlerc%ipin%i" % (data[1], data[2], data[4])
blocksignal2 = "_mesa%dactivatehandlerc%ipin%i" % (data[1], data[2], data[4])
if boardtype == "sserial":
blocksignal1 = "_mesa%dsignalhandlersserial%i_%ipin%i" % (data[1], data[2], data[3], data[4])
blocksignal2 = "_mesa%dactivatehandlersserial%i_%ipin%i" % (data[1], data[2], data[3],data[4])
elif boardtype =="parport":
blocksignal1 = "_%s_%s%dsignalhandler" % (data[1], data[2], data[4])
blocksignal2 = "_%s_%s%dactivatehandler" % (data[1], data[2], data[4])
self.widgets[data[0]].handler_block(self.d[blocksignal1])
self.widgets[data[0]].child.handler_block(self.d[blocksignal2])
if custom:
if basetree == signaltree:
temp = newiter
else:
temp = signaltree.convert_child_iter_to_iter(newiter)
self.widgets[data[0]].set_active_iter(temp)
else:
self.widgets[data[0]].set_active_iter(piter)
self.widgets[data[0]].child.handler_unblock(self.d[blocksignal2])
self.widgets[data[0]].handler_unblock(self.d[blocksignal1])
#self.debug_iter(0,p,"pin changed")
#if boardtype == "mesa": self.debug_iter(0,ptype,"pin changed")
self.p.set_buttons_sensitive(1,1)
def pport_push_data(self,port,direction,pin,pinv,signaltree,signaltocheck):
p = '%s_%s%d' % (port, direction, pin)
piter = self.widgets[p].get_active_iter()
selection = self.widgets[p].get_active_text()
# **Start widget to data Convertion**
if piter == None:# means new custom signal name and user never pushed enter
#print "callin pin changed !!!"
self.on_general_pin_changed( None,"parport", port, direction, None, pin, True)
selection = self.widgets[p].get_active_text()
piter = self.widgets[p].get_active_iter()
#print "found signame -> ",selection," "
# ok we have a piter with a signal type now- lets convert it to a signalname
#print "**** INFO parport-data-transfer piter:",piter
#self.debug_iter(piter,p,"signal")
dummy, index = signaltree.get(piter,0,1)
#print "signaltree: ",dummy
return p, signaltocheck[index], self.widgets[pinv].get_active()
def set_pport_combo(self,pinname):
#print pinname
# signal names for GPIO INPUT
datap = self.d[pinname]
if '_Ipin' in pinname:
human = self._p.human_input_names
signal = self._p.hal_input_names
tree = self.d._gpioisignaltree
# signal names for GPIO OUTPUT and OPEN DRAIN OUTPUT
elif 'Opin'in pinname:
human = self._p.human_output_names
signal =self._p.hal_output_names
tree = self.d._gpioosignaltree
#self.w[pinname].set_model(tree)
# an error probably means the signal name cannot be found
# set it as unused rather then error
itr = self.find_sig_name_iter(tree, datap)
self.widgets[pinname].set_active_iter(itr)
return
try:
signalindex = signal.index(datap)
except:
signalindex = 0
print "**** INFO: PNCCONF warning no GPIO signal named: %s\n found for pin %s"% (datap , p)
#print "gpio temp ptype:",pinname,datap,signalindex
count = 0
temp = (0) # set unused gpio if no match
if signalindex > 0:
for row,parent in enumerate(human):
#print row,parent
if len(parent[1]) == 0:continue
for column,child in enumerate(parent[1]):
count +=1
#print row,column,count,parent[0],child
if count == signalindex:
#print "match",row,column
break
if count >= signalindex:break
temp = (row,column)
treeiter = tree.get_iter(temp)
self.widgets[pinname].set_active_iter(treeiter)
def signal_sanity_check(self, *args):
warnings = []
do_warning = False
do_error = False
for i in self.d.available_axes:
tppwm = pwm = amp_8i20 = False
step = self.findsignal(i+"-stepgen-step")
step2 = self.findsignal(i+"2-stepgen-step")
enc = self.findsignal(i+"-encoder-a")
resolver = self.findsignal(i+"-resolver")
if self.findsignal("%s-8i20"% i): amp_8i20 = pwm =True
if self.findsignal(i+"-pwm-pulse"): pwm = True
if self.findsignal(i+"-tppwm-a"): tppwm = pwm = True
#print "signal sanity check: axis",i,"\n pwm = ",pwm,"\n 3pwm =",tppwm,"\n encoder =",enc,"\n step=",step
if i == 's':
if step and pwm:
warnings.append(_("You can not have both steppers and pwm signals for spindle control\n") )
do_error = True
continue
if not step and not pwm:
warnings.append(_("You forgot to designate a stepper or pwm signal for axis %s\n")% i)
do_error = True
if pwm and not (enc or resolver):
warnings.append(_("You forgot to designate an encoder /resolver signal for axis %s servo\n")% i)
do_error = True
if enc and not pwm and not step:
warnings.append(_("You forgot to designate a pwm signal or stepper signal for axis %s\n")% i)
do_error = True
if step and pwm:
warnings.append(_("You can not have both steppers and pwm signals for axis %s\n")% i)
do_error = True
if step2 and not step:
warnings.append(_("If using a tandem axis stepper, you must select a master stepgen for axis %s\n")% i)
do_error = True
if self.d.frontend == _PD._TOUCHY:# TOUCHY GUI
abort = self.findsignal("abort")
cycle = self.findsignal("cycle-start")
single = self.findsignal("single-step")
mpg = self.findsignal("select-mpg-a")
if not cycle:
warnings.append(_("Touchy require an external cycle start signal\n"))
do_warning = True
if not abort:
warnings.append(_("Touchy require an external abort signal\n"))
do_warning = True
if not single:
warnings.append(_("Touchy require an external single-step signal\n"))
do_warning = True
if not mpg:
warnings.append(_("Touchy require an external multi handwheel MPG encoder signal on the mesa page\n"))
do_warning = True
if not self.d.externalmpg:
warnings.append(_("Touchy require 'external mpg jogging' to be selected on the external control page\n"))
do_warning = True
if self.d.multimpg:
warnings.append(_("Touchy require the external mpg to be in 'shared mpg' mode on the external controls page\n"))
do_warning = True
if self.d.incrselect:
warnings.append(_("Touchy require selectable increments to be unchecked on the external controls page\n"))
do_warning = True
if do_warning or do_error:
self.warning_dialog("\n".join(warnings),True)
if do_error: return True
return False
def daughter_board_sanity_check(self,widget):
warnings = []
do_warning = False
for boardnum in range(0,int(self.d.number_mesa)):
if widget == self.widgets["mesa%d_7i29_sanity_check"%boardnum]:
warnings.append(_("The 7i29 daughter board requires PWM type generators and a PWM base frequency of 20 khz\n"))
do_warning = True
if widget == self.widgets["mesa%d_7i30_sanity_check"%boardnum]:
warnings.append(_("The 7i30 daughter board requires PWM type generators and a PWM base frequency of 20 khz\n"))
do_warning = True
if widget == self.widgets["mesa%d_7i33_sanity_check"%boardnum]:
warnings.append(_("The 7i33 daughter board requires PDM type generators and a PDM base frequency of 6 Mhz\n"))
do_warning = True
if widget == self.widgets["mesa%d_7i40_sanity_check"%boardnum]:
warnings.append(_("The 7i40 daughter board requires PWM type generators and a PWM base frequency of 50 khz\n"))
do_warning = True
if widget == self.widgets["mesa%d_7i48_sanity_check"%boardnum]:
warnings.append(_("The 7i48 daughter board requires UDM type generators and a PWM base frequency of 24 khz\n"))
do_warning = True
if do_warning:
self.warning_dialog("\n".join(warnings),True)
def axis_prepare(self, axis):
d = self.d
w = self.widgets
def set_text_from_text(n): w[axis + n].set_text("%s" % d[axis + n])
def set_text(n): w[axis + n].set_text(locale.format("%.4f", (d[axis + n])))
def set_value(n): w[axis + n].set_value(d[axis + n])
def set_active(n): w[axis + n].set_active(d[axis + n])
stepdriven = encoder = pwmgen = resolver = tppwm = digital_at_speed = amp_8i20 = False
spindlepot = sserial_scaling = False
vfd_spindle = self.d.serial_vfd and (self.d.mitsub_vfd or self.d.gs2_vfd)
if self.findsignal("%s-8i20"% axis):amp_8i20 = True
if self.findsignal("spindle-at-speed"): digital_at_speed = True
if self.findsignal(axis+"-stepgen-step"): stepdriven = True
if self.findsignal(axis+"-encoder-a"): encoder = True
if self.findsignal(axis+"-resolver"): encoder = resolver = True
temp = self.findsignal(axis+"-pwm-pulse")
if temp:
pwmgen = True
pinname = self.make_pinname(temp)
if "analog" in pinname: sserial_scaling = True
if self.findsignal(axis+"-tppwm-a"): pwmgen = tppwm = True
if self.findsignal(axis+"-pot-output"): spindlepot = sserial_scaling = True
model = w[axis+"drivertype"].get_model()
model.clear()
for i in _PD.alldrivertypes:
model.append((i[1],))
model.append((_("Custom"),))
w["steprev"].set_text("%s" % d[axis+"steprev"])
w["microstep"].set_text("%s" % d[axis +"microstep"])
# P setting needs to default to different values based on
# stepper vrs servo configs. But we still want to allow user setting it.
# If the value is None then we should set a default value, if not then
# that means it's been set to something already...hopefully right.
# TODO this should be smarter - after going thru a config once it
# always uses the value set here - if it is set to a default value
# if should keep checking that the value is still right.
# but thats a bigger change then we want now.
# We check fo None and 'None' because when None is saved
# it's saved as a string
if not d[axis + "P"] == None and not d[axis + "P"] == 'None':
set_value("P")
elif stepdriven == True:
w[axis + "P"].set_value(1/(d.servoperiod/1000000000))
else:
w[axis + "P"].set_value(50)
set_value("I")
set_value("D")
set_value("FF0")
set_value("FF1")
set_value("FF2")
set_value("bias")
set_value("deadband")
set_value("steptime")
set_value("stepspace")
set_value("dirhold")
set_value("dirsetup")
set_value("outputscale")
set_value("3pwmscale")
set_value("3pwmdeadtime")
set_active("invertmotor")
set_active("invertencoder")
set_value("maxoutput")
if amp_8i20:
w[axis + "bldc_option"].set_active(True)
else:
set_active("bldc_option")
set_active("bldc_no_feedback")
set_active("bldc_absolute_feedback")
set_active("bldc_incremental_feedback")
set_active("bldc_use_hall")
set_active("bldc_use_encoder" )
set_active("bldc_use_index")
set_active("bldc_fanuc_alignment")
set_active("bldc_digital_output")
set_active("bldc_six_outputs")
set_active("bldc_emulated_feedback")
set_active("bldc_output_hall")
set_active("bldc_output_fanuc")
set_active("bldc_force_trapz")
set_active("bldc_reverse")
set_value("bldc_scale")
set_value("bldc_poles")
set_value("bldc_lead_angle")
set_value("bldc_inital_value")
set_value("bldc_encoder_offset")
set_value("bldc_drive_offset")
set_value("bldc_pattern_out")
set_value("bldc_pattern_in")
set_value("8i20maxcurrent")
w["encoderline"].set_value((d[axis+"encodercounts"]/4))
set_value("stepscale")
set_value("encoderscale")
w[axis+"maxvel"].set_value(d[axis+"maxvel"]*60)
set_value("maxacc")
if not axis == "s" or axis == "s" and (encoder and (pwmgen or tppwm or stepdriven or sserial_scaling)):
w[axis + "servo_info"].show()
else:
w[axis + "servo_info"].hide()
if stepdriven or not (pwmgen or spindlepot):
w[axis + "output_info"].hide()
else:
w[axis + "output_info"].show()
w[axis + "invertencoder"].set_sensitive(encoder)
w[axis + "encoderscale"].set_sensitive(encoder)
w[axis + "stepscale"].set_sensitive(stepdriven)
if stepdriven:
w[axis + "stepper_info"].show()
else:
w[axis + "stepper_info"].hide()
if pwmgen or sserial_scaling:
w[axis + "outputscale"].show()
w[axis + "outputscalelabel"].show()
else:
w[axis + "outputscale"].hide()
w[axis + "outputscalelabel"].hide()
if amp_8i20 or pwmgen and d.advanced_option == True:
w[axis + "bldcframe"].show()
else: w[axis + "bldcframe"].hide()
if tppwm:
w[axis + "3pwmdeadtime"].show()
w[axis + "3pwmscale"].show()
w[axis + "3pwmdeadtimelabel"].show()
w[axis + "3pwmscalelabel"].show()
else:
w[axis + "3pwmdeadtime"].hide()
w[axis + "3pwmscale"].hide()
w[axis + "3pwmdeadtimelabel"].hide()
w[axis + "3pwmscalelabel"].hide()
w[axis + "drivertype"].set_active(self.drivertype_toindex(axis))
if w[axis + "drivertype"].get_active_text() == _("Custom"):
w[axis + "steptime"].set_value(d[axis + "steptime"])
w[axis + "stepspace"].set_value(d[axis + "stepspace"])
w[axis + "dirhold"].set_value(d[axis + "dirhold"])
w[axis + "dirsetup"].set_value(d[axis + "dirsetup"])
gobject.idle_add(lambda: self.motor_encoder_sanity_check(None,axis))
if axis == "s":
unit = "rev"
pitchunit =_("Gearbox Reduction Ratio")
elif axis == "a":
unit = "degree"
pitchunit = _("Reduction Ratio")
elif d.units ==_PD._METRIC:
unit = "mm"
pitchunit =_("Leadscrew Pitch")
else:
unit = "inch"
pitchunit =_("Leadscrew TPI")
if axis == "s" or axis =="a":
w["labelmotor_pitch"].set_text(pitchunit)
w["labelencoder_pitch"].set_text(pitchunit)
w["motor_screwunits"].set_text(_("("+unit+" / rev)"))
w["encoder_screwunits"].set_text(_("("+unit+" / rev)"))
w[axis + "velunits"].set_text(_(unit+" / min"))
w[axis + "accunits"].set_text(_(unit+" / sec²"))
w["accdistunits"].set_text(unit)
if stepdriven:
w[ "resolutionunits1"].set_text(_(unit+" / Step"))
w["scaleunits"].set_text(_("Steps / "+unit))
else:
w["resolutionunits1"].set_text(_(unit+" / encoder pulse"))
w["scaleunits"].set_text(_("Encoder pulses / "+unit))
if not axis =="s":
w[axis + "homevelunits"].set_text(_(unit+" / min"))
w[axis + "homelatchvelunits"].set_text(_(unit+" / min"))
w[axis + "homefinalvelunits"].set_text(_(unit+" / min"))
w[axis + "minfollowunits"].set_text(unit)
w[axis + "maxfollowunits"].set_text(unit)
if resolver:
w[axis + "encoderscale_label"].set_text(_("Resolver Scale:"))
if axis == 's':
if vfd_spindle:
w.serial_vfd_info.show()
else:
w.serial_vfd_info.hide()
set_value("outputscale2")
w.ssingleinputencoder.set_sensitive(encoder)
w["sinvertencoder"].set_sensitive(encoder)
w["ssingleinputencoder"].show()
w["saxistest"].set_sensitive(pwmgen or spindlepot)
w["sstepper_info"].set_sensitive(stepdriven)
w["smaxvel"].set_sensitive(stepdriven)
w["smaxacc"].set_sensitive(stepdriven)
w["suseatspeed"].set_sensitive(not digital_at_speed and encoder)
if encoder or resolver:
if (self.d.pyvcp and self.d.pyvcphaltype == 1 and self.d.pyvcpconnect == 1) or (self.d.gladevcp
and self.d.spindlespeedbar):
w["sfiltergain"].set_sensitive(True)
set_active("useatspeed")
w.snearrange_button.set_active(d.susenearrange)
w["snearscale"].set_value(d["snearscale"]*100)
w["snearrange"].set_value(d["snearrange"])
set_value("filtergain")
set_active("singleinputencoder")
set_value("outputmaxvoltage")
set_active("usenegativevoltage")
set_active("useoutputrange2")
self.useoutputrange2_toggled()
else:
if sserial_scaling:
w[axis + "outputminlimit"].show()
w[axis + "outputminlimitlabel"].show()
w[axis + "outputmaxlimit"].show()
w[axis + "outputmaxlimitlabel"].show()
else:
w[axis + "outputminlimit"].hide()
w[axis + "outputminlimitlabel"].hide()
w[axis + "outputmaxlimit"].hide()
w[axis + "outputmaxlimitlabel"].hide()
set_value("outputminlimit")
set_value("outputmaxlimit")
set_text("encodercounts")
w[axis+"maxferror"].set_sensitive(True)
w[axis+"minferror"].set_sensitive(True)
set_value("maxferror")
set_value("minferror")
set_text_from_text("compfilename")
set_active("comptype")
set_active("usebacklash")
set_value("backlash")
set_active("usecomp")
set_text("homepos")
set_text("minlim")
set_text("maxlim")
set_text("homesw")
w[axis+"homesearchvel"].set_text("%d" % (d[axis+"homesearchvel"]*60))
w[axis+"homelatchvel"].set_text("%d" % (d[axis+"homelatchvel"]*60))
w[axis+"homefinalvel"].set_text("%d" % (d[axis+"homefinalvel"]*60))
w[axis+"homesequence"].set_text("%d" % abs(d[axis+"homesequence"]))
set_active("searchdir")
set_active("latchdir")
set_active("usehomeindex")
thisaxishome = set(("all-home", "home-" + axis, "min-home-" + axis,"max-home-" + axis, "both-home-" + axis))
homes = False
for i in thisaxishome:
test = self.findsignal(i)
if test: homes = True
w[axis + "homesw"].set_sensitive(homes)
w[axis + "homesearchvel"].set_sensitive(homes)
w[axis + "searchdir"].set_sensitive(homes)
w[axis + "latchdir"].set_sensitive(homes)
w[axis + "usehomeindex"].set_sensitive(encoder and homes)
w[axis + "homefinalvel"].set_sensitive(homes)
w[axis + "homelatchvel"].set_sensitive(homes)
i = d[axis + "usecomp"]
w[axis + "comptype"].set_sensitive(i)
w[axis + "compfilename"].set_sensitive(i)
i = d[axis + "usebacklash"]
w[axis + "backlash"].set_sensitive(i)
self.p.set_buttons_sensitive(1,0)
self.motor_encoder_sanity_check(None,axis)
def driver_changed(self, axis):
d = self.d
w = self.widgets
v = w[axis + "drivertype"].get_active()
if v < len(_PD.alldrivertypes):
d = _PD.alldrivertypes[v]
w[axis + "steptime"].set_value(d[2])
w[axis + "stepspace"].set_value(d[3])
w[axis + "dirhold"].set_value(d[4])
w[axis + "dirsetup"].set_value(d[5])
w[axis + "steptime"].set_sensitive(0)
w[axis + "stepspace"].set_sensitive(0)
w[axis + "dirhold"].set_sensitive(0)
w[axis + "dirsetup"].set_sensitive(0)
else:
w[axis + "steptime"].set_sensitive(1)
w[axis + "stepspace"].set_sensitive(1)
w[axis + "dirhold"].set_sensitive(1)
w[axis + "dirsetup"].set_sensitive(1)
def drivertype_toindex(self, axis, what=None):
if what is None: what = self.d[axis + "drivertype"]
for i, d in enumerate(_PD.alldrivertypes):
if d[0] == what: return i
return len(_PD.alldrivertypes)
def drivertype_toid(self, axis, what=None):
if not isinstance(what, int): what = self.drivertype_toindex(axis, what)
if what < len(_PD.alldrivertypes): return _PD.alldrivertypes[what][0]
return "custom"
def drivertype_fromindex(self, axis):
i = self.widgets[axis + "drivertype"].get_active()
if i < len(_PD.alldrivertypes): return _PD.alldrivertypes[i][1]
return _("Custom")
def comp_toggle(self, axis):
i = self.widgets[axis + "usecomp"].get_active()
self.widgets[axis + "compfilename"].set_sensitive(i)
self.widgets[axis + "comptype"].set_sensitive(i)
if i:
self.widgets[axis + "backlash"].set_sensitive(0)
self.widgets[axis + "usebacklash"].set_active(0)
def bldc_toggled(self, axis):
i = self.widgets[axis + "bldc_option"].get_active()
self.widgets[axis + "bldcoptionbox"].set_sensitive(i)
def useatspeed_toggled(self):
i = self.widgets.suseatspeed.get_active()
self.widgets.snearscale.set_sensitive(self.widgets.snearscale_button.get_active() and i)
self.widgets.snearrange.set_sensitive(self.widgets.snearrange_button.get_active() and i)
def useoutputrange2_toggled(self):
i = self.widgets.suseoutputrange2.get_active()
self.widgets.soutputscale2.set_sensitive(i)
def bldc_update(self,Widgets,axis):
w = self.widgets
i = False
if w[axis+"bldc_incremental_feedback"].get_active():
i = True
w[axis+"bldc_pattern_in"].set_sensitive(i and w[axis+"bldc_use_hall"].get_active() )
w[axis+"bldc_inital_value"].set_sensitive(i and w[axis+"bldc_use_encoder"].get_active() and not w[axis+"bldc_use_hall"].get_active() )
w[axis+"bldc_use_hall"].set_sensitive(i)
w[axis+"bldc_use_encoder"].set_sensitive(i)
w[axis+"bldc_use_index"].set_sensitive(i)
w[axis+"bldc_fanuc_alignment"].set_sensitive(i)
i = False
if w[axis+"bldc_emulated_feedback"].get_active():
i = True
w[axis+"bldc_output_hall"].set_sensitive(i)
w[axis+"bldc_output_fanuc"].set_sensitive(i)
w[axis+"bldc_pattern_out"].set_sensitive(i and w[axis+"bldc_output_hall"].get_active() )
def backlash_toggle(self, axis):
i = self.widgets[axis + "usebacklash"].get_active()
self.widgets[axis + "backlash"].set_sensitive(i)
if i:
self.widgets[axis + "compfilename"].set_sensitive(0)
self.widgets[axis + "comptype"].set_sensitive(0)
self.widgets[axis + "usecomp"].set_active(0)
def axis_done(self, axis):
d = self.d
w = self.widgets
def get_text(n): d[axis + n] = get_value(w[axis + n])
def get_pagevalue(n): d[axis + n] = get_value(w[axis + n])
def get_active(n): d[axis + n] = w[axis + n].get_active()
stepdrive = self.findsignal(axis+"-stepgen-step")
encoder = self.findsignal(axis+"-encoder-a")
resolver = self.findsignal(axis+"-resolver")
get_pagevalue("P")
get_pagevalue("I")
get_pagevalue("D")
get_pagevalue("FF0")
get_pagevalue("FF1")
get_pagevalue("FF2")
get_pagevalue("bias")
get_pagevalue("deadband")
if stepdrive:
d[axis + "maxoutput"] = (get_value(w[axis + "maxvel"])/60) *1.25 # TODO should be X2 if using backlash comp ?
if axis == "s":
d[axis + "maxoutput"] = (get_value(w[axis +"outputscale"]))
else:
get_pagevalue("maxoutput")
get_pagevalue("steptime")
get_pagevalue("stepspace")
get_pagevalue("dirhold")
get_pagevalue("dirsetup")
get_pagevalue("outputscale")
get_pagevalue("3pwmscale")
get_pagevalue("3pwmdeadtime")
get_active("bldc_option")
get_active("bldc_reverse")
get_pagevalue("bldc_scale")
get_pagevalue("bldc_poles")
get_pagevalue("bldc_encoder_offset")
get_pagevalue("bldc_drive_offset")
get_pagevalue("bldc_pattern_out")
get_pagevalue("bldc_pattern_in")
get_pagevalue("bldc_lead_angle")
get_pagevalue("bldc_inital_value")
get_pagevalue("8i20maxcurrent")
get_active("bldc_no_feedback")
get_active("bldc_absolute_feedback")
get_active("bldc_incremental_feedback")
get_active("bldc_use_hall")
get_active("bldc_use_encoder" )
get_active("bldc_use_index")
get_active("bldc_fanuc_alignment")
get_active("bldc_digital_output")
get_active("bldc_six_outputs")
get_active("bldc_emulated_feedback")
get_active("bldc_output_hall")
get_active("bldc_output_fanuc")
get_active("bldc_force_trapz")
if w[axis + "bldc_option"].get_active():
self.configure_bldc(axis)
d[axis + "encodercounts"] = int(float(w["encoderline"].get_text())*4)
if stepdrive: get_pagevalue("stepscale")
if encoder: get_pagevalue("encoderscale")
if resolver: get_pagevalue("encoderscale")
get_active("invertmotor")
get_active("invertencoder")
d[axis + "maxvel"] = (get_value(w[axis + "maxvel"])/60)
get_pagevalue("maxacc")
d[axis + "drivertype"] = self.drivertype_toid(axis, w[axis + "drivertype"].get_active())
if not axis == "s":
get_pagevalue("outputminlimit")
get_pagevalue("outputmaxlimit")
get_pagevalue("maxferror")
get_pagevalue("minferror")
get_text("homepos")
get_text("minlim")
get_text("maxlim")
get_text("homesw")
d[axis + "homesearchvel"] = (get_value(w[axis + "homesearchvel"])/60)
d[axis + "homelatchvel"] = (get_value(w[axis + "homelatchvel"])/60)
d[axis + "homefinalvel"] = (get_value(w[axis + "homefinalvel"])/60)
d[axis+"homesequence"] = (abs(get_value(w[axis+"homesequence"])))
get_active("searchdir")
get_active("latchdir")
get_active("usehomeindex")
d[axis + "compfilename"] = w[axis + "compfilename"].get_text()
get_active("comptype")
d[axis + "backlash"]= w[axis + "backlash"].get_value()
get_active("usecomp")
get_active("usebacklash")
else:
get_active("useatspeed")
d.susenearrange = w.snearrange_button.get_active()
get_pagevalue("nearscale")
d["snearscale"] = w["snearscale"].get_value()/100
d["snearrange"] = w["snearrange"].get_value()
get_pagevalue("filtergain")
get_active("singleinputencoder")
get_pagevalue("outputscale2")
self.d.gsincrvalue0 = self.d.soutputscale
self.d.gsincrvalue1 = self.d.soutputscale2
get_active("useoutputrange2")
self.d.scaleselect = self.d.suseoutputrange2
get_active("usenegativevoltage")
get_pagevalue("outputmaxvoltage")
def configure_bldc(self,axis):
d = self.d
string = ""
# Inputs
if d[axis + "bldc_no_feedback"]: string = string + "n"
elif d[axis +"bldc_absolute_feedback"]: string = string + "a"
elif d[axis + "bldc_incremental_feedback"]:
if d[axis + "bldc_use_hall"]: string = string + "h"
if d[axis + "bldc_use_encoder" ]: string = string + "q"
if d[axis + "bldc_use_index"]: string = string + "i"
if d[axis + "bldc_fanuc_alignment"]: string = string + "f"
# Outputs
if d[axis + "bldc_digital_output"]: string = string + "B"
if d[axis + "bldc_six_outputs"]: string = string + "6"
if d[axis + "bldc_emulated_feedback"]:
if d[axis + "bldc_output_hall"]: string = string + "H"
if d[axis + "bldc_output_fanuc"]: string = string +"F"
if d[axis + "bldc_force_trapz"]: string = string + "T"
#print "axis ",axis,"bldc config ",string
d[axis+"bldc_config"] = string
def calculate_spindle_scale(self):
def get(n): return get_value(self.widgets[n])
stepdrive = bool(self.findsignal("s-stepgen-step"))
encoder = bool(self.findsignal("s-encoder-a"))
resolver = bool(self.findsignal("s-resolver"))
twoscales = self.widgets.suseoutputrange2.get_active()
data_list=[ "steprev","microstep","motor_pulleydriver","motor_pulleydriven","motor_gear1driver","motor_gear1driven",
"motor_gear2driver","motor_gear2driven","motor_max"]
templist1 = ["encoderline","steprev","microstep","motor_gear1driven","motor_gear1driver","motor_gear2driven","motor_gear2driver",
"motor_pulleydriven","motor_pulleydriver","motor_max"]
checkbutton_list = ["cbmicrosteps","cbmotor_gear1","cbmotor_gear2","cbmotor_pulley","rbvoltage_5"
]
self.widgets.spindle_cbmicrosteps.set_sensitive(stepdrive)
self.widgets.spindle_microstep.set_sensitive(stepdrive)
self.widgets.spindle_steprev.set_sensitive(stepdrive)
self.widgets.label_steps_per_rev.set_sensitive(stepdrive)
self.widgets.spindle_motor_max.set_sensitive(not stepdrive)
self.widgets.label_motor_at_max_volt.set_sensitive(not stepdrive)
self.widgets.label_volt_at_max_rpm.set_sensitive(not stepdrive)
self.widgets.spindle_rbvoltage_10.set_sensitive(not stepdrive)
self.widgets.spindle_rbvoltage_5.set_sensitive(not stepdrive)
self.widgets.spindle_cbnegative_rot.set_sensitive(not stepdrive)
# pre set data
for i in data_list:
self.widgets['spindle_'+i].set_value(self.d['s'+i])
for i in checkbutton_list:
self.widgets['spindle_'+i].set_active(self.d['s'+i])
self.widgets.spindle_encoderline.set_value(self.widgets.sencoderscale.get_value()/4)
self.widgets.spindle_cbmotor_gear2.set_active(twoscales)
self.widgets.spindle_cbnegative_rot.set_active(self.widgets.susenegativevoltage.get_active())
# temparally add signals
for i in templist1:
self.d[i] = self.widgets['spindle_'+i].connect("value-changed", self.update_spindle_calculation)
for i in checkbutton_list:
self.d[i] = self.widgets['spindle_'+i].connect("toggled", self.update_spindle_calculation)
self.update_spindle_calculation(None)
# run dialog
self.widgets.spindle_scaledialog.set_title(_("Spindle Scale Calculation"))
self.widgets.spindle_scaledialog.show_all()
result = self.widgets.spindle_scaledialog.run()
self.widgets.spindle_scaledialog.hide()
# remove signals
for i in templist1:
self.widgets['spindle_'+i].disconnect(self.d[i])
for i in checkbutton_list:
self.widgets['spindle_'+i].disconnect(self.d[i])
if not result: return
# record data values
for i in data_list:
self.d['s'+i] = get('spindle_'+i)
for i in checkbutton_list:
self.d['s'+i] = self.widgets['spindle_'+i].get_active()
# set the widgets on the spindle page as per calculations
self.widgets.susenegativevoltage.set_active(self.widgets.spindle_cbnegative_rot.get_active())
if self.widgets.spindle_rbvoltage_5.get_active():
self.widgets.soutputmaxvoltage.set_value(5)
else:
self.widgets.soutputmaxvoltage.set_value(10)
self.widgets.soutputscale.set_value(self.temp_max_motor_speed1)
self.widgets.soutputscale2.set_value(self.temp_max_motor_speed2)
self.widgets.smaxoutput.set_value(self.temp_max_motor_speed1)
self.widgets.sencoderscale.set_value(self.widgets.spindle_encoderline.get_value()*4)
self.widgets.suseoutputrange2.set_active(self.widgets.spindle_cbmotor_gear2.get_active())
if stepdrive:
motor_steps = get_value(self.widgets.spindle_steprev)
if self.widgets.spindle_cbmicrosteps.get_active():
microstepfactor = get_value(self.widgets.spindle_microstep)
else:
microstepfactor = 1
self.widgets.sstepscale.set_value(motor_steps * microstepfactor)
if encoder or resolver:
self.widgets.sencoderscale.set_value(get("spindle_encoderline")*4)
def update_spindle_calculation(self,widget):
w= self.widgets
def get(n): return get_value(w[n])
motor_pulley_ratio = gear1_ratio = gear2_ratio = 1
motor_rpm = get("spindle_motor_max")
volts_at_max_rpm = 5
if self.widgets.spindle_rbvoltage_10.get_active():
volts_at_max_rpm = 10
if w["spindle_cbmotor_pulley"].get_active():
w["spindle_motor_pulleydriver"].set_sensitive(True)
w["spindle_motor_pulleydriven"].set_sensitive(True)
motor_pulley_ratio = (get("spindle_motor_pulleydriver") / get("spindle_motor_pulleydriven"))
else:
w["spindle_motor_pulleydriver"].set_sensitive(False)
w["spindle_motor_pulleydriven"].set_sensitive(False)
motor_pulley_ratio = 1
if w["spindle_cbmotor_gear1"].get_active():
w["spindle_motor_gear1driver"].set_sensitive(True)
w["spindle_motor_gear1driven"].set_sensitive(True)
gear1_ratio = (get("spindle_motor_gear1driver") / get("spindle_motor_gear1driven"))
else:
w["spindle_motor_gear1driver"].set_sensitive(False)
w["spindle_motor_gear1driven"].set_sensitive(False)
gear1_ratio = 1
i = w["spindle_cbmotor_gear2"].get_active()
w["spindle_motor_gear2driver"].set_sensitive(i)
w["spindle_motor_gear2driven"].set_sensitive(i)
w["label_rpm_at_max_motor2"].set_sensitive(i)
w["label_gear2_max_speed"].set_sensitive(i)
if i:
gear2_ratio = (get("spindle_motor_gear2driver") / get("spindle_motor_gear2driven"))
else:
gear2_ratio = 1
w["spindle_microstep"].set_sensitive(w["spindle_cbmicrosteps"].get_active())
self.temp_max_motor_speed1 = (motor_pulley_ratio * gear1_ratio * motor_rpm)
self.temp_max_motor_speed2 = (motor_pulley_ratio * gear2_ratio * motor_rpm)
w["label_motor_at_max_volt"].set_markup(" <b>MOTOR</b> RPM at %d Volt Command"% volts_at_max_rpm)
w["label_volt_at_max_rpm"].set_text(" Voltage for %d Motor RPM:"% motor_rpm)
w["label_rpm_at_max_motor1"].set_text("Spindle RPM at %d Motor RPM -gear 1:"% motor_rpm)
w["label_rpm_at_max_motor2"].set_text("Spindle RPM at %d Motor RPM -gear 2:"% motor_rpm)
w["label_gear1_max_speed"].set_text("%d" % (motor_pulley_ratio * gear1_ratio * motor_rpm))
w["label_gear2_max_speed"].set_text("%d" % (motor_pulley_ratio * gear2_ratio * motor_rpm))
def calculate_scale(self,axis):
def get(n): return get_value(self.widgets[n])
stepdrive = self.findsignal(axis+"-stepgen-step")
encoder = self.findsignal(axis+"-encoder-a")
resolver = self.findsignal(axis+"-resolver")
data_list=[ "steprev","microstep","motor_pulleydriver","motor_pulleydriven","motor_wormdriver","motor_wormdriven",
"encoder_pulleydriver","encoder_pulleydriven","encoder_wormdriver","encoder_wormdriven","motor_leadscrew",
"encoder_leadscrew","motor_leadscrew_tpi","encoder_leadscrew_tpi",
]
templist1 = ["encoderline","encoder_leadscrew","encoder_leadscrew_tpi","encoder_wormdriven",
"encoder_wormdriver","encoder_pulleydriven","encoder_pulleydriver","steprev","motor_leadscrew","motor_leadscrew_tpi",
"microstep","motor_wormdriven","motor_wormdriver","motor_pulleydriven","motor_pulleydriver"
]
checkbutton_list = [ "cbencoder_pitch","cbencoder_tpi","cbencoder_worm","cbencoder_pulley","cbmotor_pitch",
"cbmotor_tpi","cbmicrosteps","cbmotor_worm","cbmotor_pulley"
]
# pre set data
for i in data_list:
self.widgets[i].set_value(self.d[axis+i])
for i in checkbutton_list:
self.widgets[i].set_active(self.d[axis+i])
# temparally add signals
for i in templist1:
self.d[i] = self.widgets[i].connect("value-changed", self.update_scale_calculation,axis)
for i in checkbutton_list:
self.d[i] = self.widgets[i].connect("toggled", self.update_scale_calculation,axis)
# pre calculate
self.update_scale_calculation(self.widgets,axis)
# run dialog
self.widgets.scaledialog.set_title(_("Axis Scale Calculation"))
self.widgets.scaledialog.show_all()
result = self.widgets.scaledialog.run()
self.widgets.scaledialog.hide()
# remove signals
for i in templist1:
self.widgets[i].disconnect(self.d[i])
for i in checkbutton_list:
self.widgets[i].disconnect(self.d[i])
if not result: return
# record data values
for i in data_list:
self.d[axis+i] = self.widgets[i].get_value()
for i in checkbutton_list:
self.d[axis+i] = self.widgets[i].get_active()
# set the calculations result
if encoder or resolver:
self.widgets[axis+"encoderscale"].set_value(get("calcencoder_scale"))
if stepdrive:
self.widgets[axis+"stepscale"].set_value(get("calcmotor_scale"))
def update_scale_calculation(self,widget,axis):
w = self.widgets
d = self.d
def get(n): return get_value(w[n])
stepdrive = self.findsignal(axis+"-stepgen-step")
encoder = self.findsignal(axis+"-encoder-a")
resolver = self.findsignal(axis+"-resolver")
motor_pulley_ratio = encoder_pulley_ratio = 1
motor_worm_ratio = encoder_worm_ratio = 1
encoder_scale = motor_scale = 0
microstepfactor = motor_pitch = encoder_pitch = motor_steps = 1
if axis == "a": rotary_scale = 360
else: rotary_scale = 1
try:
if stepdrive:
# stepmotor scale
w["calcmotor_scale"].set_sensitive(True)
w["stepscaleframe"].set_sensitive(True)
if w["cbmotor_pulley"].get_active():
w["motor_pulleydriver"].set_sensitive(True)
w["motor_pulleydriven"].set_sensitive(True)
motor_pulley_ratio = (get("motor_pulleydriven") / get("motor_pulleydriver"))
else:
w["motor_pulleydriver"].set_sensitive(False)
w["motor_pulleydriven"].set_sensitive(False)
if w["cbmotor_worm"].get_active():
w["motor_wormdriver"].set_sensitive(True)
w["motor_wormdriven"].set_sensitive(True)
motor_worm_ratio = (get("motor_wormdriver") / get("motor_wormdriven"))
else:
w["motor_wormdriver"].set_sensitive(False)
w["motor_wormdriven"].set_sensitive(False)
if w["cbmicrosteps"].get_active():
w["microstep"].set_sensitive(True)
microstepfactor = get("microstep")
else:
w["microstep"].set_sensitive(False)
if w["cbmotor_pitch"].get_active():
w["motor_leadscrew"].set_sensitive(True)
w["cbmotor_tpi"].set_active(False)
if self.d.units == _PD._METRIC:
motor_pitch = 1./ get("motor_leadscrew")
else:
motor_pitch = 1./ (get("motor_leadscrew")* .03937008)
else: w["motor_leadscrew"].set_sensitive(False)
if w["cbmotor_tpi"].get_active():
w["motor_leadscrew_tpi"].set_sensitive(True)
w["cbmotor_pitch"].set_active(False)
if self.d.units == _PD._METRIC:
motor_pitch = (get("motor_leadscrew_tpi")* .03937008)
else:
motor_pitch = get("motor_leadscrew_tpi")
else: w["motor_leadscrew_tpi"].set_sensitive(False)
motor_steps = get("steprev")
motor_scale = (motor_steps * microstepfactor * motor_pulley_ratio * motor_worm_ratio * motor_pitch) / rotary_scale
w["calcmotor_scale"].set_text(locale.format("%.4f", (motor_scale)))
else:
w["calcmotor_scale"].set_sensitive(False)
w["stepscaleframe"].set_sensitive(False)
# encoder scale
if encoder or resolver:
w["calcencoder_scale"].set_sensitive(True)
w["encoderscaleframe"].set_sensitive(True)
if w["cbencoder_pulley"].get_active():
w["encoder_pulleydriver"].set_sensitive(True)
w["encoder_pulleydriven"].set_sensitive(True)
encoder_pulley_ratio = (get("encoder_pulleydriven") / get("encoder_pulleydriver"))
else:
w["encoder_pulleydriver"].set_sensitive(False)
w["encoder_pulleydriven"].set_sensitive(False)
if w["cbencoder_worm"].get_active():
w["encoder_wormdriver"].set_sensitive(True)
w["encoder_wormdriven"].set_sensitive(True)
encoder_worm_ratio = (get("encoder_wormdriver") / get("encoder_wormdriven"))
else:
w["encoder_wormdriver"].set_sensitive(False)
w["encoder_wormdriven"].set_sensitive(False)
if w["cbencoder_pitch"].get_active():
w["encoder_leadscrew"].set_sensitive(True)
w["cbencoder_tpi"].set_active(False)
if self.d.units == _PD._METRIC:
encoder_pitch = 1./ get("encoder_leadscrew")
else:
encoder_pitch = 1./ (get("encoder_leadscrew")*.03937008)
else: w["encoder_leadscrew"].set_sensitive(False)
if w["cbencoder_tpi"].get_active():
w["encoder_leadscrew_tpi"].set_sensitive(True)
w["cbencoder_pitch"].set_active(False)
if self.d.units == _PD._METRIC:
encoder_pitch = (get("encoder_leadscrew_tpi")*.03937008)
else:
encoder_pitch = get("encoder_leadscrew_tpi")
else: w["encoder_leadscrew_tpi"].set_sensitive(False)
encoder_cpr = get_value(w[("encoderline")]) * 4
encoder_scale = (encoder_pulley_ratio * encoder_worm_ratio * encoder_pitch * encoder_cpr) / rotary_scale
w["calcencoder_scale"].set_text(locale.format("%.4f", (encoder_scale)))
else:
w["calcencoder_scale"].set_sensitive(False)
w["encoderscaleframe"].set_sensitive(False)
#new stuff
if stepdrive: scale = motor_scale
else: scale = encoder_scale
maxvps = (get_value(w[axis+"maxvel"]))/60
pps = (scale * (maxvps))/1000
if pps == 0: raise ValueError
pps = abs(pps)
w["khz"].set_text("%.1f" % pps)
acctime = (maxvps) / get_value(w[axis+"maxacc"])
accdist = acctime * .5 * (maxvps)
if encoder or resolver:
maxrpm = int(maxvps * 60 * (scale/encoder_cpr))
else:
maxrpm = int(maxvps * 60 * (scale/(microstepfactor * motor_steps)))
w["acctime"].set_text("%.4f" % acctime)
w["accdist"].set_text("%.4f" % accdist)
w["chartresolution"].set_text("%.7f" % (1.0 / scale))
w["calscale"].set_text(str(scale))
w["maxrpm"].set_text("%d" % maxrpm)
except (ValueError, ZeroDivisionError):
w["calcmotor_scale"].set_text("200")
w["calcencoder_scale"].set_text("1000")
w["chartresolution"].set_text("")
w["acctime"].set_text("")
if not axis == 's':
w["accdist"].set_text("")
w["khz"].set_text("")
w["calscale"].set_text("")
def motor_encoder_sanity_check(self,widgets,axis):
stepdrive = encoder = bad = resolver = pot = False
if self.findsignal(axis+"-stepgen-step"): stepdrive = True
if self.findsignal(axis+"-encoder-a"): encoder = True
if self.findsignal(axis+"-resolver"): resolver = True
if self.findsignal(axis+"-pot-outpot"): pot = True
if encoder or resolver:
if self.widgets[axis+"encoderscale"].get_value() < 1:
self.widgets[axis+"encoderscale"].modify_bg(gtk.STATE_NORMAL, self.widgets[axis+"encoderscale"].get_colormap().alloc_color("red"))
dbg('encoder resolver scale bad %f'%self.widgets[axis+"encoderscale"].get_value())
bad = True
if stepdrive:
if self.widgets[axis+"stepscale"].get_value() < 1:
self.widgets[axis+"stepscale"].modify_bg(gtk.STATE_NORMAL, self.widgets[axis+"stepscale"].get_colormap().alloc_color("red"))
dbg('step scale bad')
bad = True
if not (encoder or resolver) and not stepdrive and not axis == "s":
dbg('encoder %s resolver %s stepper %s axis %s'%(encoder,resolver,stepdrive,axis))
bad = True
if self.widgets[axis+"maxvel"] < 1:
dbg('max vel low')
bad = True
if self.widgets[axis+"maxacc"] < 1:
dbg('max accl low')
bad = True
if bad:
dbg('motor %s_encoder sanity check -bad'%axis)
self.p.set_buttons_sensitive(1,0)
self.widgets[axis + "axistune"].set_sensitive(0)
self.widgets[axis + "axistest"].set_sensitive(0)
else:
dbg('motor %s_encoder sanity check - good'%axis)
self.widgets[axis+"encoderscale"].modify_bg(gtk.STATE_NORMAL, self.origbg)
self.widgets[axis+"stepscale"].modify_bg(gtk.STATE_NORMAL, self.origbg)
self.p.set_buttons_sensitive(1,1)
self.widgets[axis + "axistune"].set_sensitive(1)
self.widgets[axis + "axistest"].set_sensitive(1)
def update_gladevcp(self):
i = self.widgets.gladevcp.get_active()
self.widgets.gladevcpbox.set_sensitive( i )
if self.d.frontend == _PD._TOUCHY:
self.widgets.centerembededgvcp.set_active(True)
self.widgets.centerembededgvcp.set_sensitive(True)
self.widgets.sideembededgvcp.set_sensitive(False)
self.widgets.standalonegvcp.set_sensitive(False)
elif self.d.frontend == _PD._GMOCCAPY or self.d.frontend == _PD._AXIS:
self.widgets.sideembededgvcp.set_sensitive(True)
self.widgets.centerembededgvcp.set_sensitive(True)
self.widgets.standalonegvcp.set_sensitive(False)
if not self.widgets.centerembededgvcp.get_active() and not self.widgets.sideembededgvcp.get_active():
self.widgets.centerembededgvcp.set_active(True)
else:
self.widgets.sideembededgvcp.set_sensitive(False)
self.widgets.centerembededgvcp.set_sensitive(False)
self.widgets.standalonegvcp.set_sensitive(True)
self.widgets.standalonegvcp.set_active(True)
i = self.widgets.standalonegvcp.get_active()
self.widgets.gladevcpsize.set_sensitive(i)
self.widgets.gladevcpposition.set_sensitive(i)
self.widgets.gladevcpforcemax.set_sensitive(i)
if not i:
self.widgets.gladevcpsize.set_active(False)
self.widgets.gladevcpposition.set_active(False)
self.widgets.gladevcpforcemax.set_active(False)
i = self.widgets.gladevcpsize.get_active()
self.widgets.gladevcpwidth.set_sensitive(i)
self.widgets.gladevcpheight.set_sensitive(i)
i = self.widgets.gladevcpposition.get_active()
self.widgets.gladevcpxpos.set_sensitive(i)
self.widgets.gladevcpypos.set_sensitive(i)
for i in (("zerox","x"),("zeroy","y"),("zeroz","z"),("zeroa","a"),("autotouchz","z")):
if not i[1] in(self.d.available_axes):
self.widgets[i[0]].set_active(False)
self.widgets[i[0]].set_sensitive(False)
else:
self.widgets[i[0]].set_sensitive(True)
def has_spindle_speed_control(self):
for test in ("s-stepgen-step", "s-pwm-pulse", "s-encoder-a", "spindle-enable", "spindle-cw", "spindle-ccw", "spindle-brake",
"s-pot-output"):
has_spindle = self.findsignal(test)
print test,has_spindle
if has_spindle:
return True
if self.d.serial_vfd and (self.d.mitsub_vfd or self.d.gs2_vfd):
return True
return False
def clean_unused_ports(self, *args):
# if parallel ports not used clear all signals
parportnames = ("pp1","pp2","pp3")
for check,connector in enumerate(parportnames):
if self.d.number_pports >= (check+1):continue
# initialize parport input / inv pins
for i in (1,2,3,4,5,6,7,8,10,11,12,13,15):
pinname ="%s_Ipin%d"% (connector,i)
self.d[pinname] = _PD.UNUSED_INPUT
pinname ="%s_Ipin%d_inv"% (connector,i)
self.d[pinname] = False
# initialize parport output / inv pins
for i in (1,2,3,4,5,6,7,8,9,14,16,17):
pinname ="%s_Opin%d"% (connector,i)
self.d[pinname] = _PD.UNUSED_OUTPUT
pinname ="%s_Opin%d_inv"% (connector,i)
self.d[pinname] = False
# clear all unused mesa signals
for boardnum in(0,1):
for connector in(1,2,3,4,5,6,7,8,9):
if self.d.number_mesa >= boardnum + 1 :
if connector in(self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._NUMOFCNCTRS]) :
continue
# This initializes GPIO input pins
for i in range(0,16):
pinname ="mesa%dc%dpin%d"% (boardnum,connector,i)
self.d[pinname] = _PD.UNUSED_INPUT
pinname ="mesa%dc%dpin%dtype"% (boardnum,connector,i)
self.d[pinname] = _PD.GPIOI
# This initializes GPIO output pins
for i in range(16,24):
pinname ="mesa%dc%dpin%d"% (boardnum,connector,i)
self.d[pinname] = _PD.UNUSED_OUTPUT
pinname ="mesa%dc%dpin%dtype"% (boardnum,connector,i)
self.d[pinname] = _PD.GPIOO
# This initializes the mesa inverse pins
for i in range(0,24):
pinname ="mesa%dc%dpin%dinv"% (boardnum,connector,i)
self.d[pinname] = False
# clear unused sserial signals
keeplist =[]
# if the current firmware supports sserial better check for used channels
# and make a 'keeplist'. we don't want to clear them
if self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._MAXSSERIALPORTS]:
#search all pins for sserial port
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._NUMOFCNCTRS]) :
for pin in range (0,24):
firmptype,compnum = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._STARTOFDATA+pin+(concount*24)]
p = 'mesa%dc%dpin%d' % (boardnum, connector, pin)
ptype = 'mesa%dc%dpin%dtype' % (boardnum, connector , pin)
if self.d[ptype] in (_PD.TXDATA0,_PD.TXDATA1,_PD.TXDATA2,_PD.TXDATA3,_PD.TXDATA4,_PD.SS7I76M0,_PD.SS7I76M2,_PD.SS7I76M3,
_PD.SS7I77M0,_PD.SS7I77M1,_PD.SS7I77M3,_PD.SS7I77M4) and not self.d[p] == _PD.UNUSED_SSERIAL:
if self.d[ptype] in (_PD.TXDATA0,_PD.SS7I76M0,_PD.SS7I77M0): channelnum = 0
elif self.d[ptype] in (_PD.TXDATA1,_PD.SS7I77M1): channelnum = 1
elif self.d[ptype] == _PD.TXDATA2: channelnum = 2
elif self.d[ptype] in (_PD.TXDATA3,_PD.SS7I76M3,_PD.SS7I77M3): channelnum = 3
elif self.d[ptype] in (_PD.TXDATA4,_PD.SS7I77M4): channelnum = 4
keeplist.append(channelnum)
#print "board # %d sserial keeplist"%(boardnum),keeplist
# ok clear the sserial pins unless they are in the keeplist
port = 0# TODO hard code at only 1 sserial port
for channel in range(0,_PD._NUM_CHANNELS): #TODO hardcoded at 5 sserial channels instead of 8
if channel in keeplist: continue
# This initializes pins
for i in range(0,self._p._SSCOMBOLEN):
pinname ="mesa%dsserial%d_%dpin%d"% (boardnum, port,channel,i)
if i < 24:
self.d[pinname] = _PD.UNUSED_INPUT
else:
self.d[pinname] = _PD.UNUSED_OUTPUT
pinname ="mesa%dsserial%d_%dpin%dtype"% (boardnum, port,channel,i)
if i < 24:
self.d[pinname] = _PD.GPIOI
else:
self.d[pinname] = _PD.GPIOO
pinname ="mesa%dsserial%d_%dpin%dinv"% (boardnum, port,channel,i)
self.d[pinname] = False
def debug_iter(self,test,testwidget,message=None):
print "#### DEBUG :",message
for i in ("_gpioosignaltree","_gpioisignaltree","_steppersignaltree","_encodersignaltree","_muxencodersignaltree",
"_pwmcontrolsignaltree","_pwmrelatedsignaltree","_tppwmsignaltree",
"_gpioliststore","_encoderliststore","_muxencoderliststore","_pwmliststore","_tppwmliststore"):
modelcheck = self.widgets[testwidget].get_model()
if modelcheck == self.d[i]:print i;break
#********************
# Common Helper functions
#********************
def tandem_check(self, letter):
tandem_stepper = self.make_pinname(self.stepgen_sig("%s2"%letter))
tandem_pwm = self.make_pinname(self.pwmgen_sig("%s2"%letter))
print letter, bool(tandem_stepper or tandem_pwm), tandem_stepper, tandem_pwm
return bool(tandem_stepper or tandem_pwm)
def stepgen_sig(self, axis):
thisaxisstepgen = axis + "-stepgen-step"
test = self.findsignal(thisaxisstepgen)
return test
# find the individual related oins to step gens
# so that we can check if they were inverted
def stepgen_invert_pins(self,pinnumber):
# sample pinname = mesa0c0pin11
signallist_a = []
signallist_b = []
pin = int(pinnumber[10:])
connector = int(pinnumber[6:7])
boardnum = int(pinnumber[4:5])
channel = None
pinlist = self.list_related_pins([_PD.STEPA,_PD.STEPB], boardnum, connector, channel, pin, 0)
#print pinlist
for num,i in enumerate(pinlist):
if self.d[i[0]+"inv"]:
gpioname = self.make_pinname(self.findsignal( self.d[i[0]] ),True)
#print gpioname
if num:
signallist_b.append(gpioname)
else:
signallist_a.append(gpioname)
return [signallist_a, signallist_b]
def spindle_invert_pins(self,pinnumber):
# sample pinname = mesa0sserial0_0pin11
signallist = []
pin = int(pinnumber[18:])
port = int(pinnumber[12:13])
boardnum = int(pinnumber[4:5])
channel = int(pinnumber[14:15])
pinlist = self.list_related_pins([_PD.POTO,_PD.POTE], boardnum, port, channel, pin, 0)
for i in pinlist:
if self.d[i[0]+"inv"]:
name = self.d[i[0]+"type"]
signallist.append(name)
return signallist
def encoder_sig(self, axis):
thisaxisencoder = axis +"-encoder-a"
test = self.findsignal(thisaxisencoder)
return test
def resolver_sig(self, axis):
thisaxisresolver = axis +"-resolver"
test = self.findsignal(thisaxisresolver)
return test
def amp_8i20_sig(self, axis):
thisaxis8i20 = "%s-8i20"% axis
test = self.findsignal(thisaxis8i20)
return test
def potoutput_sig(self,axis):
thisaxispot = "%s-pot-output"% axis
test = self.findsignal(thisaxispot)
return test
def pwmgen_sig(self, axis):
thisaxispwmgen = axis + "-pwm-pulse"
test = self.findsignal( thisaxispwmgen)
return test
def pwmgen_invert_pins(self,pinnumber):
print "list pwm invert pins",pinnumber
# sample pinname = mesa0c0pin11
signallist = []
pin = int(pinnumber[10:])
connector = int(pinnumber[6:7])
boardnum = int(pinnumber[4:5])
channel = None
pinlist = self.list_related_pins([_PD.PWMP, _PD.PWMD, _PD.PWME], boardnum, connector, channel, pin, 0)
print pinlist
for i in pinlist:
if self.d[i[0]+"inv"]:
gpioname = self.make_pinname(self.findsignal( self.d[i[0]] ),True)
print gpioname
signallist.append(gpioname)
return signallist
def tppwmgen_sig(self, axis):
thisaxispwmgen = axis + "-tppwm-a"
test = self.findsignal(thisaxispwmgen)
return test
def tppwmgen_has_6(self, axis):
thisaxispwmgen = axis + "-tppwm-anot"
test = self.findsignal(thisaxispwmgen)
return test
def home_sig(self, axis):
thisaxishome = set(("all-home", "home-" + axis, "min-home-" + axis, "max-home-" + axis, "both-home-" + axis))
for i in thisaxishome:
if self.findsignal(i): return i
return None
def min_lim_sig(self, axis):
thisaxishome = set(("all-limit", "min-" + axis,"min-home-" + axis, "both-" + axis, "both-home-" + axis))
for i in thisaxishome:
if self.findsignal(i): return i
return None
def max_lim_sig(self, axis):
thisaxishome = set(("all-limit", "max-" + axis, "max-home-" + axis, "both-" + axis, "both-home-" + axis))
for i in thisaxishome:
if self.findsignal(i): return i
return None
def get_value(self,w):
return get_value(w)
def show_try_errors(self):
exc_type, exc_value, exc_traceback = sys.exc_info()
formatted_lines = traceback.format_exc().splitlines()
print
print "****Pncconf verbose debugging:",formatted_lines[0]
traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
print formatted_lines[-1]
def hostmot2_command_string(self, substitution = False):
def make_name(bname,bnum):
if substitution:
return "[HMOT](CARD%d)"% (bnum)
else:
return "hm2_%s.%d"% (bname,bnum)
# mesa stuff
load_cmnds = []
board0 = self.d.mesa0_currentfirmwaredata[_PD._BOARDNAME]
board1 = self.d.mesa1_currentfirmwaredata[_PD._BOARDNAME]
driver0 = ' %s'% self.d.mesa0_currentfirmwaredata[_PD._HALDRIVER]
driver1 = ' %s'% self.d.mesa1_currentfirmwaredata[_PD._HALDRIVER]
directory0 = self.d.mesa0_currentfirmwaredata[_PD._DIRECTORY]
directory1 = self.d.mesa1_currentfirmwaredata[_PD._DIRECTORY]
firm0 = self.d.mesa0_currentfirmwaredata[_PD._FIRMWARE]
firm1 = self.d.mesa1_currentfirmwaredata[_PD._FIRMWARE]
firmstring0 = firmstring1 = board0_ip = board1_ip = ""
mesa0_3pwm = mesa1_3pwm = ''
mesa0_ioaddr = mesa1_ioaddr = ''
load_cmnds.append("loadrt hostmot2")
if '7i43' in board0:
mesa0_ioaddr = ' ioaddr=%s ioaddr_hi=0 epp_wide=1'% self.d.mesa0_parportaddrs
if '7i43' in board1:
mesa1_ioaddr = ' ioaddr=%s ioaddr_hi=0 epp_wide=1'% self.d.mesa1_parportaddrs
if 'eth' in driver0:
firmstring0 =''
if self.d.mesa0_card_addrs:
board0_ip = ''' board_ip="%s"''' % self.d.mesa0_card_addrs
elif not "5i25" in board0:
firmstring0 = "firmware=hm2/%s/%s.BIT" % (directory0, firm0)
if 'eth' in driver1:
firmstring1 =''
if self.d.mesa1_card_addrs:
board1_ip = ''' board_ip="%s"'''% self.d.mesa1_card_addrs
elif not "5i25" in board1:
firmstring1 = "firmware=hm2/%s/%s.BIT" % (directory1, firm1)
# TODO fix this hardcoded hack: only one serialport
ssconfig0 = ssconfig1 = resolver0 = resolver1 = temp = ""
if self.d.mesa0_numof_sserialports:
for i in range(1,_PD._NUM_CHANNELS+1):
if i <= self.d.mesa0_numof_sserialchannels:
# m number in the name signifies the required sserial mode
for j in ("123456789"):
if ("m"+j) in self.d["mesa0sserial0_%dsubboard"% (i-1)]:
temp = temp + j
break
else: temp = temp + "0" # default case
else:
temp = temp + "x"
ssconfig0 = " sserial_port_0=%s"% temp
if self.d.number_mesa == 2 and self.d.mesa1_numof_sserialports:
for i in range(1,_PD._NUM_CHANNELS+1):
if i <= self.d.mesa1_numof_sserialchannels:
# m number in the name signifies the required sserial mode
for j in ("123456789"):
if ("m"+j) in self.d["mesa1sserial0_%dsubboard"% (i-1)]:
temp = temp + j
break
else: temp = temp + "0" # default case
else:
temp = temp + "x"
ssconfig1 = " sserial_port_0=%s"% temp
if self.d.mesa0_numof_resolvers:
resolver0 = " num_resolvers=%d"% self.d.mesa0_numof_resolvers
if self.d.mesa1_numof_resolvers:
resolver1 = " num_resolvers=%d"% self.d.mesa1_numof_resolvers
if self.d.mesa0_numof_tppwmgens:
mesa0_3pwm = ' num_3pwmgens=%d' %self.d.mesa0_numof_tppwmgens
if self.d.mesa1_numof_tppwmgens:
mesa1_3pwm = ' num_3pwmgens=%d' %self.d.mesa1_numof_tppwmgens
if self.d.number_mesa == 1:
load_cmnds.append( """loadrt%s%s%s config="%s num_encoders=%d num_pwmgens=%d%s num_stepgens=%d%s%s" """ % (
driver0, board0_ip, mesa0_ioaddr, firmstring0, self.d.mesa0_numof_encodergens, self.d.mesa0_numof_pwmgens,
mesa0_3pwm, self.d.mesa0_numof_stepgens, ssconfig0, resolver0))
elif self.d.number_mesa == 2 and (driver0 == driver1):
load_cmnds.append( """loadrt%s%s%s config="%s num_encoders=%d num_pwmgens=%d%s num_stepgens=%d%s%s,\
%s%s num_encoders=%d num_pwmgens=%d%s num_stepgens=%d%s%s" """ % (
driver0, board0_ip, mesa0_ioaddr, firmstring0, self.d.mesa0_numof_encodergens, self.d.mesa0_numof_pwmgens,
mesa0_3pwm, self.d.mesa0_numof_stepgens, ssconfig0, resolver0, mesa1_ioaddr, firmstring1,
self.d.mesa1_numof_encodergens, self.d.mesa1_numof_pwmgens, mesa1_3pwm,
self.d.mesa1_numof_stepgens, ssconfig1, resolver1))
elif self.d.number_mesa == 2:
load_cmnds.append( """loadrt%s%s%s config="%s num_encoders=%d num_pwmgens=%d%s num_stepgens=%d%s%s" """ % (
driver0, board0_ip, mesa0_ioaddr, firmstring0, self.d.mesa0_numof_encodergens, self.d.mesa0_numof_pwmgens,
mesa0_3pwm, self.d.mesa0_numof_stepgens, ssconfig0, resolver0 ))
load_cmnds.append( """loadrt%s%s%s config="%s num_encoders=%d num_pwmgens=%d%s num_stepgens=%d%s%s" """ % (
driver1, board1_ip, mesa1_ioaddr, firmstring1, self.d.mesa1_numof_encodergens, self.d.mesa1_numof_pwmgens,
mesa0_3pwm, self.d.mesa1_numof_stepgens, ssconfig1, resolver1 ))
for boardnum in range(0,int(self.d.number_mesa)):
if boardnum == 1 and (board0 == board1):
halnum = 1
else:
halnum = 0
prefix = make_name(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME],halnum)
if self.d["mesa%d_numof_pwmgens"% boardnum] > 0:
load_cmnds.append( "setp %s.pwmgen.pwm_frequency %d"% (prefix, self.d["mesa%d_pwm_frequency"% boardnum] ))
load_cmnds.append( "setp %s.pwmgen.pdm_frequency %d"% (prefix, self.d["mesa%d_pdm_frequency"% boardnum] ))
load_cmnds.append( "setp %s.watchdog.timeout_ns %d"% (prefix, self.d["mesa%d_watchdog_timeout"% boardnum] ))
# READ
read_cmnds = []
for boardnum in range(0,int(self.d.number_mesa)):
if boardnum == 1 and (self.d.mesa0_currentfirmwaredata[_PD._BOARDNAME] == self.d.mesa1_currentfirmwaredata[_PD._BOARDNAME]):
halnum = 1
else:
halnum = 0
prefix = make_name(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME],halnum)
read_cmnds.append( "addf %s.read servo-thread"% (prefix))
# WRITE
write_cmnds = []
for boardnum in range(0,int(self.d.number_mesa)):
if boardnum == 1 and (self.d.mesa0_currentfirmwaredata[_PD._BOARDNAME] == self.d.mesa1_currentfirmwaredata[_PD._BOARDNAME]):
halnum = 1
else:
halnum = 0
prefix = make_name(self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME],halnum)
write_cmnds.append( "addf %s.write servo-thread"% (prefix))
if '7i76e' in self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME] or \
'7i92' in self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME]:
write_cmnds.append( "setp %s.dpll.01.timer-us -50"% (prefix))
write_cmnds.append( "setp %s.stepgen.timer-number 1"% (prefix))
return load_cmnds,read_cmnds,write_cmnds
def pport_command_string(self):
# LOAD
load_cmnds = []
# parport stuff
port3name = port2name = port1name = port3dir = port2dir = port1dir = ""
if self.d.number_pports>2:
port3name = " " + self.d.ioaddr3
if self.d.pp3_direction:
port3dir =" out"
else:
port3dir =" in"
if self.d.number_pports>1:
port2name = " " + self.d.ioaddr2
if self.d.pp2_direction:
port2dir =" out"
else:
port2dir =" in"
port1name = self.d.ioaddr1
if self.d.pp1_direction:
port1dir =" out"
else:
port1dir =" in"
load_cmnds.append("loadrt hal_parport cfg=\"%s%s%s%s%s%s\"" % (port1name, port1dir, port2name, port2dir, port3name, port3dir))
# READ
read_cmnds = []
read_cmnds.append( "addf parport.0.read servo-thread")
if self.d.number_pports > 1:
read_cmnds.append( "addf parport.1.read servo-thread")
if self.d.number_pports > 2:
read_cmnds.append( "addf parport.2.read servo-thread")
# WRITE
write_cmnds = []
write_cmnds.append( "addf parport.0.write servo-thread")
if self.d.number_pports > 1:
write_cmnds.append( "addf parport.1.write servo-thread")
if self.d.number_pports > 2:
write_cmnds.append( "addf parport.2.write servo-thread")
return load_cmnds,read_cmnds,write_cmnds
# This method returns I/O pin designation (name and number) of a given HAL signalname.
# It does not check to see if the signalname is in the list more then once.
# if parports are not used then signals are not searched.
def findsignal(self, sig):
if self.d.number_pports:
ppinput = {}
ppoutput = {}
for i in (1,2,3):
for s in (2,3,4,5,6,7,8,9,10,11,12,13,15):
key = self.d["pp%d_Ipin%d" %(i,s)]
ppinput[key] = "pp%d_Ipin%d" %(i,s)
for s in (1,2,3,4,5,6,7,8,9,14,16,17):
key = self.d["pp%d_Opin%d" %(i,s)]
ppoutput[key] = "pp%d_Opin%d" %(i,s)
mesa = {}
for boardnum in range(0,int(self.d.number_mesa)):
for concount,connector in enumerate(self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._NUMOFCNCTRS]) :
for s in range(0,24):
key = self.d["mesa%dc%dpin%d"% (boardnum,connector,s)]
mesa[key] = "mesa%dc%dpin%d" %(boardnum,connector,s)
if self.d["mesa%d_numof_sserialports"% boardnum]:
sserial = {}
port = 0
for channel in range (0,self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._MAXSSERIALCHANNELS]):
if channel ==_PD._NUM_CHANNELS: break # TODO may not be all channels available
for pin in range (0,_PD._SSCOMBOLEN):
key = self.d['mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)]
sserial[key] = 'mesa%dsserial%d_%dpin%d' % (boardnum, port, channel, pin)
try:
return mesa[sig]
except:
try:
return sserial[sig]
except:
pass
if self.d.number_pports:
try:
return ppinput[sig]
except:
try:
return ppoutput[sig]
except:
return None
else: return None
# search all the current firmware array for related pins
# if not the same component number as the pin that changed or
# if not in the relate component type keep searching
# if is the right component type and number, check the relatedsearch array for a match
# if its a match add it to a list of pins (pinlist) that need to be updated
def list_related_pins(self, relatedsearch, boardnum, connector, channel, pin, style):
#print relatedsearch, boardnum, connector, channel, pin, style
pinlist =[]
if not channel == None:
subfirmname = self.d["mesa%dsserial%d_%dsubboard"% (boardnum, connector, channel)]
for subnum,temp in enumerate(_PD.MESA_DAUGHTERDATA):
if _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBFIRMNAME] == subfirmname: break
subboardname = _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBBOARDNAME]
currentptype,currentcompnum = _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBSTARTOFDATA+pin]
for t_pin in range (0,_PD._SSCOMBOLEN):
comptype,compnum = _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBSTARTOFDATA+t_pin]
if compnum != currentcompnum: continue
if comptype not in (relatedsearch): continue
if style == 0:
tochange = ['mesa%dsserial%d_%dpin%d'% (boardnum,connector,channel,t_pin),boardnum,connector,channel,t_pin]
if style == 1:
tochange = ['mesa%dsserial%d_%dpin%dtype'% (boardnum,connector,channel,t_pin),boardnum,connector,channel,t_pin]
if style == 2:
tochange = ['mesa%dsserial%d_%dpin%dinv'% (boardnum,connector,channel,t_pin),boardnum,connector,channel,t_pin]
pinlist.append(tochange)
else:
for concount,i in enumerate(self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._NUMOFCNCTRS]):
if i == connector:
currentptype,currentcompnum = self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._STARTOFDATA+pin+(concount*24)]
for t_concount,t_connector in enumerate(self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._NUMOFCNCTRS]):
for t_pin in range (0,24):
comptype,compnum = self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._STARTOFDATA+t_pin+(t_concount*24)]
if compnum != currentcompnum: continue
if comptype not in (relatedsearch): continue
if style == 0:
tochange = ['mesa%dc%dpin%d'% (boardnum,t_connector,t_pin),boardnum,t_connector,None,t_pin]
if style == 1:
tochange = ['mesa%dc%dpin%dtype'% (boardnum,t_connector,t_pin),boardnum,t_connector,None,t_pin]
if style == 2:
tochange = ['mesa%dc%dpin%dinv'% (boardnum,t_connector,t_pin),boardnum,t_connector,None,t_pin]
pinlist.append(tochange)
return pinlist
# This method takes a signalname data pin (eg mesa0c3pin1)
# and converts it to a HAL pin names (eg hm2_5i20.0.gpio.01)
# component number conversion is for adjustment of position of pins related to the
# 'controlling pin' eg encoder-a (controlling pin) encoder-b encoder -I
# (a,b,i are related pins for encoder component)
# gpionumber is a flag to return a gpio piname instead of the component pinname
# this is used when we want to invert the pins of a component output (such as a stepper)
# because you actually must invert the GPIO that would be in that position
# prefixonly flag is used when we want the pin name without the component name.
# used with sserial when we want the sserial port and channel so we can add out own name (eg enable pins)
def make_pinname(self, pin, gpionumber = False, prefixonly = False, substitution = False):
def make_name(bname,bnum):
if substitution:
return "[HMOT](CARD%d)"% (bnum)
else:
return "hm2_%s.%d"% (bname, bnum)
test = str(pin)
halboardnum = 0
if test == "None": return None
elif 'mesa' in test:
type_name = { _PD.GPIOI:"gpio", _PD.GPIOO:"gpio", _PD.GPIOD:"gpio", _PD.SSR0:"ssr",
_PD.ENCA:"encoder", _PD.ENCB:"encoder",_PD.ENCI:"encoder",_PD.ENCM:"encoder",
_PD.RES0:"resolver",_PD.RES1:"resolver",_PD.RES2:"resolver",_PD.RES3:"resolver",_PD.RES4:"resolver",_PD.RES5:"resolver",
_PD.MXE0:"encoder", _PD.MXE1:"encoder",
_PD.PWMP:"pwmgen",_PD.PWMD:"pwmgen", _PD.PWME:"pwmgen", _PD.PDMP:"pwmgen", _PD.PDMD:"pwmgen", _PD.PDME:"pwmgen",
_PD.UDMU:"pwmgen",_PD.UDMD:"pwmgen", _PD.UDME:"pwmgen",_PD.STEPA:"stepgen", _PD.STEPB:"stepgen",
_PD.TPPWMA:"tppwmgen",_PD.TPPWMB:"tppwmgen",_PD.TPPWMC:"tppwmgen",
_PD.TPPWMAN:"tppwmgen",_PD.TPPWMBN:"tppwmgen",_PD.TPPWMCN:"tppwmgen",
_PD.TPPWME:"tppwmgen",_PD.TPPWMF:"tppwmgen",_PD.AMP8I20:"8i20",_PD.POTO:"spinout",
_PD.POTE:"spinena",_PD.POTD:"spindir",_PD.ANALOGIN:"analog","Error":"None" }
boardnum = int(test[4:5])
boardname = self.d["mesa%d_currentfirmwaredata"% boardnum][_PD._BOARDNAME]
meta = self.get_board_meta(boardname)
num_of_pins = meta.get('PINS_PER_CONNECTOR')
ptype = self.d[pin+"type"]
if boardnum == 1 and self.d.mesa1_currentfirmwaredata[_PD._BOARDNAME] == self.d.mesa0_currentfirmwaredata[_PD._BOARDNAME]:
halboardnum = 1
if 'serial' in test:
# sample pin name = mesa0sserial0_0pin24
pinnum = int(test[18:])
portnum = int(test[12:13])
channel = int(test[14:15])
subfirmname = self.d["mesa%dsserial%d_%dsubboard"% (boardnum, portnum, channel)]
for subnum,temp in enumerate(_PD.MESA_DAUGHTERDATA):
#print "pinname search -",_PD.MESA_DAUGHTERDATA[subnum][_PD._SUBFIRMNAME],subfirmname
if _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBFIRMNAME] == subfirmname: break
#print "pinname -found subboard name:",_PD.MESA_DAUGHTERDATA[subnum][_PD._SUBFIRMNAME],subfirmname,subnum,"channel:",channel
subboardname = _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBBOARDNAME]
firmptype,compnum = _PD.MESA_DAUGHTERDATA[subnum][_PD._SUBSTARTOFDATA+pinnum]
# we iter over this dic because of locale translation problems when using
# comptype = type_name[ptype]
comptype = "ERROR FINDING COMPONENT TYPE"
for key,value in type_name.iteritems():
if key == ptype:
comptype = value
break
if value == "Error":
print "**** ERROR PNCCONF: pintype error in make_pinname: (sserial) ptype = ",ptype
return None
# if gpionumber flag is true - convert to gpio pin name
if gpionumber or ptype in(_PD.GPIOI,_PD.GPIOO,_PD.GPIOD,_PD.SSR0):
if "7i77" in (subboardname) or "7i76" in(subboardname)or "7i84" in(subboardname):
if ptype in(_PD.GPIOO,_PD.GPIOD):
comptype = "output"
if pinnum >15 and pinnum <24:
pinnum = pinnum-16
elif pinnum >39:
pinnum = pinnum -32
elif ptype == _PD.GPIOI:
comptype = "input"
if pinnum >23 and pinnum < 40:
pinnum = pinnum-8
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel) + comptype+"-%02d"% (pinnum)
elif "7i69" in (subboardname) or "7i73" in (subboardname) or "7i64" in(subboardname):
if ptype in(_PD.GPIOO,_PD.GPIOD):
comptype = "output"
pinnum -= 24
elif ptype == _PD.GPIOI:
comptype = "input"
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel) + comptype+"-%02d"% (pinnum)
elif "7i70" in (subboardname) or "7i71" in (subboardname):
if ptype in(_PD.GPIOO,_PD.GPIOD):
comptype = "output"
elif ptype == _PD.GPIOI:
comptype = "input"
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel) + comptype+"-%02d"% (pinnum)
else:
print "**** ERROR PNCCONF: subboard name ",subboardname," in make_pinname: (sserial) ptype = ",ptype,pin
return None
elif ptype in (_PD.AMP8I20,_PD.POTO,_PD.POTE,_PD.POTD) or prefixonly:
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel)
elif ptype in(_PD.PWMP,_PD.PDMP,_PD.UDMU):
comptype = "analogout"
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel) + comptype+"%d"% (compnum)
elif ptype == (_PD.ANALOGIN):
if "7i64" in(subboardname):
comptype = "analog"
else:
comptype = "analogin"
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel) + comptype+"%d"% (compnum)
elif ptype == (_PD.ENCA):
comptype = "enc"
return "%s.%s.%d.%d."% (make_name(boardname,halboardnum),subboardname,portnum,channel) + comptype+"%d"% (compnum)
else:
print "**** ERROR PNCCONF: pintype error in make_pinname: (sserial) ptype = ",ptype,pin
return None
else:
# sample pin name = mesa0c3pin1
pinnum = int(test[10:])
connum = int(test[6:7])
# we iter over this dic because of locale translation problems when using
# comptype = type_name[ptype]
comptype = "ERROR FINDING COMPONENT TYPE"
# we need concount (connector designations are not in numerical order, pin names are) and comnum from this
for concount,i in enumerate(self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._NUMOFCNCTRS]):
if i == connum:
dummy,compnum = self.d["mesa%d_currentfirmwaredata"% (boardnum)][_PD._STARTOFDATA+pinnum+(concount*24)]
break
for key,value in type_name.iteritems():
if key == ptype: comptype = value
if value == "Error":
print "**** ERROR PNCCONF: pintype error in make_pinname: (mesa) ptype = ",ptype
return None
# if gpionumber flag is true - convert to gpio pin name
if gpionumber or ptype in(_PD.GPIOI,_PD.GPIOO,_PD.GPIOD,_PD.SSR0):
print '->',ptype,dummy,compnum,pin
if ptype == _PD.SSR0:
compnum -= 100
return "%s."% (make_name(boardname,halboardnum)) + "ssr.00.out-%02d"% (compnum)
else:
compnum = int(pinnum)+(concount* num_of_pins )
return "%s."% (make_name(boardname,halboardnum)) + "gpio.%03d"% (compnum)
elif ptype in (_PD.ENCA,_PD.ENCB,_PD.ENCI,_PD.ENCM,_PD.PWMP,_PD.PWMD,_PD.PWME,_PD.PDMP,_PD.PDMD,_PD.PDME,_PD.UDMU,_PD.UDMD,_PD.UDME,
_PD.STEPA,_PD.STEPB,_PD.STEPC,_PD.STEPD,_PD.STEPE,_PD.STEPF,
_PD.TPPWMA,_PD.TPPWMB,_PD.TPPWMC,_PD.TPPWMAN,_PD.TPPWMBN,_PD.TPPWMCN,_PD.TPPWME,_PD.TPPWMF):
return "%s."% (make_name(boardname,halboardnum)) + comptype+".%02d"% (compnum)
elif ptype in (_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5):
temp = (_PD.RES0,_PD.RES1,_PD.RES2,_PD.RES3,_PD.RES4,_PD.RES5)
for num,dummy in enumerate(temp):
if ptype == dummy:break
return "%s."% (make_name(boardname,halboardnum)) + comptype+".%02d"% (compnum*6+num)
elif ptype in (_PD.MXE0,_PD.MXE1):
num = 0
if ptype == _PD.MXE1: num = 1
return "%s."% (make_name(boardname,halboardnum)) + comptype+".%02d"% ((compnum * 2 + num))
elif 'pp' in test:
print test
ending = "-out"
test = str(pin)
print self.d[pin]
pintype = str(test[4:5])
print pintype
pinnum = int(test[8:])
print pinnum
connum = int(test[2:3])-1
print connum
if pintype == 'I': ending = "-in"
return "parport."+str(connum)+".pin-%02d"%(pinnum)+ending
else:
print "pintype error in make_pinname: pinname = ",test
return None
# Boiler code
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
# starting with 'pncconf -d' gives debug messages
if __name__ == "__main__":
usage = "usage: pncconf -h for options"
parser = OptionParser(usage=usage)
parser.add_option("-d", action="store", metavar='all', dest="debug",
help="Print debug info and ignore realtime/kernel tests.\nUse 'alldev' to show all the page tabs. 'step' to stop at each debug print,'excl','5i25','rawfirm','curfirm'")
(options, args) = parser.parse_args()
if options.debug:
app = App(dbgstate=options.debug)
else:
app = App('')
gtk.main()
|
lgpl-2.1
| -1,847,330,764,788,389,000
| 54.005267
| 192
| 0.527267
| false
| 3.77671
| false
| false
| false
|
HaebinShin/tensorflow
|
tensorflow/python/ops/nn_ops.py
|
1
|
56530
|
# Copyright 2015 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 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.
# ==============================================================================
"""Wrappers for primitive Neural Net (NN) Operations."""
# pylint: disable=invalid-name
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_nn_ops import *
# pylint: enable=wildcard-import
# Aliases for some automatically-generated names.
local_response_normalization = gen_nn_ops.lrn
def atrous_conv2d(value, filters, rate, padding, name=None):
"""Atrous convolution (a.k.a. convolution with holes or dilated convolution).
Computes a 2-D atrous convolution, also known as convolution with holes or
dilated convolution, given 4-D `value` and `filters` tensors. If the `rate`
parameter is equal to one, it performs regular 2-D convolution. If the `rate`
parameter is greater than one, it performs convolution with holes, sampling
the input values every `rate` pixels in the `height` and `width` dimensions.
This is equivalent to convolving the input with a set of upsampled filters,
produced by inserting `rate - 1` zeros between two consecutive values of the
filters along the `height` and `width` dimensions, hence the name atrous
convolution or convolution with holes (the French word trous means holes in
English).
More specifically:
output[b, i, j, k] = sum_{di, dj, q} filters[di, dj, q, k] *
value[b, i + rate * di, j + rate * dj, q]
Atrous convolution allows us to explicitly control how densely to compute
feature responses in fully convolutional networks. Used in conjunction with
bilinear interpolation, it offers an alternative to `conv2d_transpose` in
dense prediction tasks such as semantic image segmentation, optical flow
computation, or depth estimation. It also allows us to effectively enlarge
the field of view of filters without increasing the number of parameters or
the amount of computation.
For a description of atrous convolution and how it can be used for dense
feature extraction, please see: [Semantic Image Segmentation with Deep
Convolutional Nets and Fully Connected CRFs](http://arxiv.org/abs/1412.7062).
The same operation is investigated further in [Multi-Scale Context Aggregation
by Dilated Convolutions](http://arxiv.org/abs/1511.07122). Previous works
that effectively use atrous convolution in different ways are, among others,
[OverFeat: Integrated Recognition, Localization and Detection using
Convolutional Networks](http://arxiv.org/abs/1312.6229) and [Fast Image
Scanning with Deep Max-Pooling Convolutional Neural Networks]
(http://arxiv.org/abs/1302.1700). Atrous convolution is also closely related
to the so-called noble identities in multi-rate signal processing.
There are many different ways to implement atrous convolution (see the refs
above). The implementation here reduces
atrous_conv2d(value, filters, rate, padding=padding)
to the following three operations:
paddings = ...
net = space_to_batch(value, paddings, block_size=rate)
net = conv2d(net, filters, strides=[1, 1, 1, 1], padding="VALID")
crops = ...
net = batch_to_space(net, crops, block_size=rate)
Advanced usage. Note the following optimization: A sequence of `atrous_conv2d`
operations with identical `rate` parameters, 'SAME' `padding`, and filters
with odd heights/ widths:
net = atrous_conv2d(net, filters1, rate, padding="SAME")
net = atrous_conv2d(net, filters2, rate, padding="SAME")
...
net = atrous_conv2d(net, filtersK, rate, padding="SAME")
can be equivalently performed cheaper in terms of computation and memory as:
pad = ... # padding so that the input dims are multiples of rate
net = space_to_batch(net, paddings=pad, block_size=rate)
net = conv2d(net, filters1, strides=[1, 1, 1, 1], padding="SAME")
net = conv2d(net, filters2, strides=[1, 1, 1, 1], padding="SAME")
...
net = conv2d(net, filtersK, strides=[1, 1, 1, 1], padding="SAME")
net = batch_to_space(net, crops=pad, block_size=rate)
because a pair of consecutive `space_to_batch` and `batch_to_space` ops with
the same `block_size` cancel out when their respective `paddings` and `crops`
inputs are identical.
Args:
value: A 4-D `Tensor` of type `float`. It needs to be in the default "NHWC"
format. Its shape is `[batch, in_height, in_width, in_channels]`.
filters: A 4-D `Tensor` with the same type as `value` and shape
`[filter_height, filter_width, in_channels, out_channels]`. `filters`'
`in_channels` dimension must match that of `value`. Atrous convolution is
equivalent to standard convolution with upsampled filters with effective
height `filter_height + (filter_height - 1) * (rate - 1)` and effective
width `filter_width + (filter_width - 1) * (rate - 1)`, produced by
inserting `rate - 1` zeros along consecutive elements across the
`filters`' spatial dimensions.
rate: A positive int32. The stride with which we sample input values across
the `height` and `width` dimensions. Equivalently, the rate by which we
upsample the filter values by inserting zeros across the `height` and
`width` dimensions. In the literature, the same parameter is sometimes
called `input stride` or `dilation`.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
name: Optional name for the returned tensor.
Returns:
A `Tensor` with the same type as `value`.
Raises:
ValueError: If input/output depth does not match `filters`' shape, or if
padding is other than `'VALID'` or `'SAME'`.
"""
with ops.op_scope([value, filters], name, "atrous_conv2d") as name:
value = ops.convert_to_tensor(value, name="value")
filters = ops.convert_to_tensor(filters, name="filters")
if not value.get_shape()[3].is_compatible_with(filters.get_shape()[2]):
raise ValueError(
"value's input channels does not match filters' input channels, "
"{} != {}".format(value.get_shape()[3], filters.get_shape()[2]))
if rate < 1:
raise ValueError("rate {} cannot be less than one".format(rate))
if rate == 1:
value = gen_nn_ops.conv2d(input=value,
filter=filters,
strides=[1, 1, 1, 1],
padding=padding)
return value
# We have two padding contributions. The first is used for converting "SAME"
# to "VALID". The second is required so that the height and width of the
# zero-padded value tensor are multiples of rate.
# Padding required to reduce to "VALID" convolution
if padding == "SAME":
# Handle filters whose shape is unknown during graph creation.
if filters.get_shape().is_fully_defined():
filter_shape = filters.get_shape().as_list()
else:
filter_shape = array_ops.shape(filters)
filter_height, filter_width = filter_shape[0], filter_shape[1]
# Spatial dimensions of the filters and the upsampled filters in which we
# introduce (rate - 1) zeros between consecutive filter values.
filter_height_up = filter_height + (filter_height - 1) * (rate - 1)
filter_width_up = filter_width + (filter_width - 1) * (rate - 1)
pad_height = filter_height_up - 1
pad_width = filter_width_up - 1
# When pad_height (pad_width) is odd, we pad more to bottom (right),
# following the same convention as conv2d().
pad_top = pad_height // 2
pad_bottom = pad_height - pad_top
pad_left = pad_width // 2
pad_right = pad_width - pad_left
elif padding == "VALID":
pad_top = 0
pad_bottom = 0
pad_left = 0
pad_right = 0
else:
raise ValueError("Invalid padding")
# Handle input whose shape is unknown during graph creation.
if value.get_shape().is_fully_defined():
value_shape = value.get_shape().as_list()
else:
value_shape = array_ops.shape(value)
in_height = value_shape[1] + pad_top + pad_bottom
in_width = value_shape[2] + pad_left + pad_right
# More padding so that rate divides the height and width of the input.
pad_bottom_extra = (rate - in_height % rate) % rate
pad_right_extra = (rate - in_width % rate) % rate
# The paddings argument to space_to_batch includes both padding components.
space_to_batch_pad = [[pad_top, pad_bottom + pad_bottom_extra],
[pad_left, pad_right + pad_right_extra]]
value = array_ops.space_to_batch(input=value,
paddings=space_to_batch_pad,
block_size=rate)
value = gen_nn_ops.conv2d(input=value,
filter=filters,
strides=[1, 1, 1, 1],
padding="VALID",
name=name)
# The crops argument to batch_to_space is just the extra padding component.
batch_to_space_crop = [[0, pad_bottom_extra], [0, pad_right_extra]]
value = array_ops.batch_to_space(input=value,
crops=batch_to_space_crop,
block_size=rate)
return value
def conv2d_transpose(value,
filter,
output_shape,
strides,
padding="SAME",
name=None):
"""The transpose of `conv2d`.
This operation is sometimes called "deconvolution" after [Deconvolutional
Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is
actually the transpose (gradient) of `conv2d` rather than an actual
deconvolution.
Args:
value: A 4-D `Tensor` of type `float` and shape
`[batch, height, width, in_channels]`.
filter: A 4-D `Tensor` with the same type as `value` and shape
`[height, width, output_channels, in_channels]`. `filter`'s
`in_channels` dimension must match that of `value`.
output_shape: A 1-D `Tensor` representing the output shape of the
deconvolution op.
strides: A list of ints. The stride of the sliding window for each
dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the [comment here](https://www.tensorflow.org/api_docs/python/nn.html#convolution)
name: Optional name for the returned tensor.
Returns:
A `Tensor` with the same type as `value`.
Raises:
ValueError: If input/output depth does not match `filter`'s shape, or if
padding is other than `'VALID'` or `'SAME'`.
"""
with ops.op_scope([value, filter, output_shape], name,
"conv2d_transpose") as name:
value = ops.convert_to_tensor(value, name="value")
filter = ops.convert_to_tensor(filter, name="filter")
if not value.get_shape()[3].is_compatible_with(filter.get_shape()[3]):
raise ValueError("input channels does not match filter's input channels, "
"{} != {}".format(value.get_shape()[3], filter.get_shape(
)[3]))
output_shape_ = ops.convert_to_tensor(output_shape, name="output_shape")
if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(4)):
raise ValueError("output_shape must have shape (4,), got {}"
.format(output_shape_.get_shape()))
if isinstance(output_shape, (list, np.ndarray)):
# output_shape's shape should be == [4] if reached this point.
if not filter.get_shape()[2].is_compatible_with(output_shape[3]):
raise ValueError(
"output_shape does not match filter's output channels, "
"{} != {}".format(output_shape[3], filter.get_shape()[2]))
if padding != "VALID" and padding != "SAME":
raise ValueError("padding must be either VALID or SAME:"
" {}".format(padding))
return gen_nn_ops.conv2d_backprop_input(input_sizes=output_shape_,
filter=filter,
out_backprop=value,
strides=strides,
padding=padding,
name=name)
def conv3d_transpose(value,
filter,
output_shape,
strides,
padding="SAME",
name=None):
"""The transpose of `conv3d`.
This operation is sometimes called "deconvolution" after [Deconvolutional
Networks](http://www.matthewzeiler.com/pubs/cvpr2010/cvpr2010.pdf), but is
actually the transpose (gradient) of `conv3d` rather than an actual
deconvolution.
Args:
value: A 5-D `Tensor` of type `float` and shape
`[batch, depth, height, width, in_channels]`.
filter: A 5-D `Tensor` with the same type as `value` and shape
`[depth, height, width, output_channels, in_channels]`. `filter`'s
`in_channels` dimension must match that of `value`.
output_shape: A 1-D `Tensor` representing the output shape of the
deconvolution op.
strides: A list of ints. The stride of the sliding window for each
dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the [comment here](https://www.tensorflow.org/api_docs/python/nn.html#convolution)
name: Optional name for the returned tensor.
Returns:
A `Tensor` with the same type as `value`.
Raises:
ValueError: If input/output depth does not match `filter`'s shape, or if
padding is other than `'VALID'` or `'SAME'`.
"""
with ops.op_scope([value, filter, output_shape], name,
"conv3d_transpose") as name:
value = ops.convert_to_tensor(value, name="value")
filter = ops.convert_to_tensor(filter, name="filter")
if not value.get_shape()[4].is_compatible_with(filter.get_shape()[4]):
raise ValueError("input channels does not match filter's input channels, "
"{} != {}".format(value.get_shape()[4], filter.get_shape(
)[4]))
output_shape_ = ops.convert_to_tensor(output_shape, name="output_shape")
if not output_shape_.get_shape().is_compatible_with(tensor_shape.vector(5)):
raise ValueError("output_shape must have shape (5,), got {}"
.format(output_shape_.get_shape()))
if isinstance(output_shape, (list, np.ndarray)):
# output_shape's shape should be == [5] if reached this point.
if not filter.get_shape()[3].is_compatible_with(output_shape[4]):
raise ValueError(
"output_shape does not match filter's output channels, "
"{} != {}".format(output_shape[4], filter.get_shape()[3]))
if padding != "VALID" and padding != "SAME":
raise ValueError("padding must be either VALID or SAME:"
" {}".format(padding))
return gen_nn_ops.conv3d_backprop_input_v2(input_sizes=output_shape_,
filter=filter,
out_backprop=value,
strides=strides,
padding=padding,
name=name)
# pylint: disable=protected-access
def bias_add(value, bias, data_format=None, name=None):
"""Adds `bias` to `value`.
This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
Broadcasting is supported, so `value` may have any number of dimensions.
Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
case where both types are quantized.
Args:
value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
`int16`, `int8`, `complex64`, or `complex128`.
bias: A 1-D `Tensor` with size matching the last dimension of `value`.
Must be the same type as `value` unless `value` is a quantized type,
in which case a different quantized type may be used.
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `value`.
"""
with ops.op_scope([value, bias], name, "BiasAdd") as name:
value = ops.convert_to_tensor(value, name="input")
bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias")
return gen_nn_ops._bias_add(value, bias, data_format=data_format, name=name)
ops.RegisterShape("BiasAdd")(common_shapes.bias_add_shape)
ops.RegisterShape("BiasAddGrad")(common_shapes.bias_add_grad_shape)
# pylint: disable=protected-access
def bias_add_v1(value, bias, name=None):
"""Adds `bias` to `value`.
This is a deprecated version of bias_add and will soon to be removed.
This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D.
Broadcasting is supported, so `value` may have any number of dimensions.
Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the
case where both types are quantized.
Args:
value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`,
`int16`, `int8`, `complex64`, or `complex128`.
bias: A 1-D `Tensor` with size matching the last dimension of `value`.
Must be the same type as `value` unless `value` is a quantized type,
in which case a different quantized type may be used.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `value`.
"""
with ops.op_scope([value, bias], name, "BiasAddV1") as name:
value = ops.convert_to_tensor(value, name="input")
bias = ops.convert_to_tensor(bias, dtype=value.dtype, name="bias")
return gen_nn_ops._bias_add_v1(value, bias, name=name)
ops.RegisterShape("BiasAddV1")(common_shapes.bias_add_shape)
ops.RegisterShape("BiasAddGradV1")(common_shapes.bias_add_grad_shape)
def relu6(features, name=None):
"""Computes Rectified Linear 6: `min(max(features, 0), 6)`.
Args:
features: A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`,
`int16`, or `int8`.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `features`.
"""
with ops.op_scope([features], name, "Relu6") as name:
features = ops.convert_to_tensor(features, name="features")
return gen_nn_ops._relu6(features, name=name)
def softmax_cross_entropy_with_logits(logits, labels, name=None):
"""Computes softmax cross entropy between `logits` and `labels`.
Measures the probability error in discrete classification tasks in which the
classes are mutually exclusive (each entry is in exactly one class). For
example, each CIFAR-10 image is labeled with one and only one label: an image
can be a dog or a truck, but not both.
**NOTE:** While the classes are mutually exclusive, their probabilities
need not be. All that is required is that each row of `labels` is
a valid probability distribution. If they are not, the computation of the
gradient will be incorrect.
If using exclusive `labels` (wherein one and only
one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.
**WARNING:** This op expects unscaled logits, since it performs a `softmax`
on `logits` internally for efficiency. Do not call this op with the
output of `softmax`, as it will produce incorrect results.
`logits` and `labels` must have the same shape `[batch_size, num_classes]`
and the same dtype (either `float32` or `float64`).
Args:
logits: Unscaled log probabilities.
labels: Each row `labels[i]` must be a valid probability distribution.
name: A name for the operation (optional).
Returns:
A 1-D `Tensor` of length `batch_size` of the same type as `logits` with the
softmax cross entropy loss.
"""
# TODO(pcmurray) Raise an error when the labels do not sum to 1. Note: This
# could break users who call this with bad labels, but disregard the bad
# results.
# The second output tensor contains the gradients. We use it in
# _CrossEntropyGrad() in nn_grad but not here.
cost, unused_backprop = gen_nn_ops._softmax_cross_entropy_with_logits(
logits, labels, name=name)
return cost
def sparse_softmax_cross_entropy_with_logits(logits, labels, name=None):
"""Computes sparse softmax cross entropy between `logits` and `labels`.
Measures the probability error in discrete classification tasks in which the
classes are mutually exclusive (each entry is in exactly one class). For
example, each CIFAR-10 image is labeled with one and only one label: an image
can be a dog or a truck, but not both.
**NOTE:** For this operation, the probability of a given label is considered
exclusive. That is, soft classes are not allowed, and the `labels` vector
must provide a single specific index for the true class for each row of
`logits` (each minibatch entry). For soft softmax classification with
a probability distribution for each entry, see
`softmax_cross_entropy_with_logits`.
**WARNING:** This op expects unscaled logits, since it performs a softmax
on `logits` internally for efficiency. Do not call this op with the
output of `softmax`, as it will produce incorrect results.
A common use case is to have logits of shape `[batch_size, num_classes]` and
labels of shape `[batch_size]`. But higher dimensions are supported.
Args:
logits: Unscaled log probabilities of rank `r` and shape
`[d_0, d_1, ..., d_{r-2}, num_classes]` and dtype `float32` or `float64`.
labels: `Tensor` of shape `[d_0, d_1, ..., d_{r-2}]` and dtype `int32` or
`int64`. Each entry in `labels` must be an index in `[0, num_classes)`.
Other values will result in a loss of 0, but incorrect gradient
computations.
name: A name for the operation (optional).
Returns:
A `Tensor` of the same shape as `labels` and of the same type as `logits`
with the softmax cross entropy loss.
Raises:
ValueError: If logits are scalars (need to have rank >= 1) or if the rank
of the labels is not equal to the rank of the labels minus one.
"""
# TODO(pcmurray) Raise an error when the label is not an index in
# [0, num_classes). Note: This could break users who call this with bad
# labels, but disregard the bad results.
# Reshape logits and labels to rank 2.
with ops.op_scope([labels, logits], name,
"SparseSoftmaxCrossEntropyWithLogits"):
labels = ops.convert_to_tensor(labels)
logits = ops.convert_to_tensor(logits)
# Store label shape for result later.
labels_static_shape = labels.get_shape()
labels_shape = array_ops.shape(labels)
if logits.get_shape().ndims is not None and logits.get_shape().ndims == 0:
raise ValueError("Logits cannot be scalars - received shape %s.",
logits.get_shape())
if logits.get_shape().ndims is not None and (
labels_static_shape.ndims is not None and
labels_static_shape.ndims != logits.get_shape().ndims - 1):
raise ValueError("Rank mismatch: Labels rank (received %s) should equal "
"logits rank (received %s) - 1.",
labels_static_shape.ndims, logits.get_shape().ndims)
# Check if no reshapes are required.
if logits.get_shape().ndims == 2:
cost, _ = gen_nn_ops._sparse_softmax_cross_entropy_with_logits(
logits, labels, name=name)
return cost
# Reshape logits to 2 dim, labels to 1 dim.
num_classes = array_ops.gather(array_ops.shape(logits),
array_ops.rank(logits) - 1)
logits = array_ops.reshape(logits, [-1, num_classes])
labels = array_ops.reshape(labels, [-1])
# The second output tensor contains the gradients. We use it in
# _CrossEntropyGrad() in nn_grad but not here.
cost, _ = gen_nn_ops._sparse_softmax_cross_entropy_with_logits(
logits, labels, name=name)
cost = array_ops.reshape(cost, labels_shape)
cost.set_shape(labels_static_shape)
return cost
@ops.RegisterShape("SparseSoftmaxCrossEntropyWithLogits")
def _SparseSoftmaxCrossEntropyWithLogitsShape(op):
"""Shape function for SparseSoftmaxCrossEntropyWithLogits op."""
logits_shape = op.inputs[0].get_shape()
input_shape = logits_shape.with_rank(2)
batch_size = input_shape[0]
# labels_shape
op.inputs[1].get_shape().merge_with(tensor_shape.vector(batch_size))
return [tensor_shape.vector(batch_size.value), input_shape]
@ops.RegisterShape("SoftmaxCrossEntropyWithLogits")
def _SoftmaxCrossEntropyWithLogitsShape(op):
"""Shape function for SoftmaxCrossEntropyWithLogits op."""
logits_shape = op.inputs[0].get_shape()
labels_shape = op.inputs[1].get_shape()
input_shape = logits_shape.merge_with(labels_shape).with_rank(2)
batch_size = input_shape[0]
return [tensor_shape.vector(batch_size.value), input_shape]
def avg_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
"""Performs the average pooling on the input.
Each entry in `output` is the mean of the corresponding size `ksize`
window in `value`.
Args:
value: A 4-D `Tensor` of shape `[batch, height, width, channels]` and type
`float32`, `float64`, `qint8`, `quint8`, or `qint32`.
ksize: A list of ints that has length >= 4.
The size of the window for each dimension of the input tensor.
strides: A list of ints that has length >= 4.
The stride of the sliding window for each dimension of the
input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the [comment here](https://www.tensorflow.org/api_docs/python/nn.html#convolution)
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: Optional name for the operation.
Returns:
A `Tensor` with the same type as `value`. The average pooled output tensor.
"""
with ops.op_scope([value], name, "AvgPool") as name:
value = ops.convert_to_tensor(value, name="input")
return gen_nn_ops._avg_pool(value,
ksize=ksize,
strides=strides,
padding=padding,
data_format=data_format,
name=name)
def max_pool(value, ksize, strides, padding, data_format="NHWC", name=None):
"""Performs the max pooling on the input.
Args:
value: A 4-D `Tensor` with shape `[batch, height, width, channels]` and
type `tf.float32`.
ksize: A list of ints that has length >= 4. The size of the window for
each dimension of the input tensor.
strides: A list of ints that has length >= 4. The stride of the sliding
window for each dimension of the input tensor.
padding: A string, either `'VALID'` or `'SAME'`. The padding algorithm.
See the [comment here](https://www.tensorflow.org/api_docs/python/nn.html#convolution)
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: Optional name for the operation.
Returns:
A `Tensor` with type `tf.float32`. The max pooled output tensor.
"""
with ops.op_scope([value], name, "MaxPool") as name:
value = ops.convert_to_tensor(value, name="input")
return gen_nn_ops._max_pool(value,
ksize=ksize,
strides=strides,
padding=padding,
data_format=data_format,
name=name)
ops.RegisterShape("Relu")(common_shapes.unchanged_shape)
ops.RegisterShape("Relu6")(common_shapes.unchanged_shape)
ops.RegisterShape("Elu")(common_shapes.unchanged_shape)
ops.RegisterShape("Softplus")(common_shapes.unchanged_shape)
ops.RegisterShape("Softsign")(common_shapes.unchanged_shape)
@ops.RegisterShape("ReluGrad")
@ops.RegisterShape("Relu6Grad")
@ops.RegisterShape("EluGrad")
@ops.RegisterShape("SoftplusGrad")
@ops.RegisterShape("SoftsignGrad")
def _BinaryElementwiseShape(op):
"""Returns same shape as both inputs to op.
Args:
op: Input operation.
Returns:
Shape of both inputs to `op`.
"""
return [op.inputs[0].get_shape().merge_with(op.inputs[1].get_shape())]
ops.RegisterShape("L2Loss")(common_shapes.scalar_shape)
ops.RegisterShape("LRN")(common_shapes.unchanged_shape_with_rank(4))
@ops.RegisterShape("LRNGrad")
def _LRNGradShape(op):
"""Shape function for LRNGrad op."""
in_grads_shape = op.inputs[0].get_shape().with_rank(4)
in_image_shape = op.inputs[1].get_shape().with_rank(4)
out_image_shape = op.inputs[2].get_shape().with_rank(4)
return [in_grads_shape.merge_with(in_image_shape).merge_with(out_image_shape)]
ops.RegisterShape("Softmax")(common_shapes.unchanged_shape_with_rank(2))
ops.RegisterShape("LogSoftmax")(common_shapes.unchanged_shape_with_rank(2))
@ops.RegisterShape("InTopK")
def _InTopKShape(op):
"""Shape function for InTopK op."""
predictions_shape = op.inputs[0].get_shape().with_rank(2)
targets_shape = op.inputs[1].get_shape().with_rank(1)
batch_size = predictions_shape[0].merge_with(targets_shape[0])
return [tensor_shape.vector(batch_size.value)]
@ops.RegisterShape("TopK")
@ops.RegisterShape("TopKV2")
def _TopKShape(op):
"""Shape function for TopK and TopKV2 ops."""
input_shape = op.inputs[0].get_shape().with_rank_at_least(1)
if len(op.inputs) >= 2:
k = tensor_util.constant_value(op.inputs[1])
else:
k = op.get_attr("k")
last = input_shape[-1].value
if last is not None and k is not None and last < k:
raise ValueError("input.shape %s must have last dimension >= k = %d" %
(input_shape, k))
output_shape = input_shape[:-1].concatenate([k])
return [output_shape, output_shape]
@ops.RegisterShape("BatchNormWithGlobalNormalization")
def _BatchNormShape(op):
"""Shape function for BatchNormWithGlobalNormalization op."""
input_shape = op.inputs[0].get_shape().with_rank(4)
mean_shape = op.inputs[1].get_shape().with_rank(1)
var_shape = op.inputs[2].get_shape().with_rank(1)
beta_shape = op.inputs[3].get_shape().with_rank(1)
gamma_shape = op.inputs[4].get_shape().with_rank(1)
mean_shape[0].merge_with(input_shape[3])
var_shape[0].merge_with(input_shape[3])
beta_shape[0].merge_with(input_shape[3])
gamma_shape[0].merge_with(input_shape[3])
return [input_shape]
@ops.RegisterShape("BatchNormWithGlobalNormalizationGrad")
def _BatchNormGradShape(op):
"""Shape function for BatchNormWithGlobalNormalizationGrad op."""
input_shape = op.inputs[0].get_shape().with_rank(4)
mean_shape = op.inputs[1].get_shape().with_rank(1)
var_shape = op.inputs[2].get_shape().with_rank(1)
beta_shape = op.inputs[3].get_shape().with_rank(1)
out_backprop_shape = op.inputs[4].get_shape().with_rank(4)
input_shape = input_shape.merge_with(out_backprop_shape)
vector_dim = input_shape[3]
vector_dim = vector_dim.merge_with(mean_shape[0])
vector_dim = vector_dim.merge_with(var_shape[0])
vector_dim = vector_dim.merge_with(beta_shape[0])
return [input_shape] + ([tensor_shape.vector(vector_dim)] * 4)
ops.RegisterShape("Conv2D")(common_shapes.conv2d_shape)
ops.RegisterShape("DepthwiseConv2dNative")(
common_shapes.depthwise_conv2d_native_shape)
ops.RegisterShape("AvgPool")(common_shapes.avg_pool_shape)
ops.RegisterShape("MaxPool")(common_shapes.max_pool_shape)
@ops.RegisterShape("MaxPoolWithArgmax")
def _MaxPoolWithArgMaxShape(op):
"""Shape function for MaxPoolWithArgmax op."""
return common_shapes.max_pool_shape(op) * 2
@ops.RegisterShape("AvgPoolGrad")
def _AvgPoolGradShape(op):
"""Shape function for the AvgPoolGrad op."""
orig_input_shape = tensor_util.constant_value(op.inputs[0])
if orig_input_shape is not None:
return [tensor_shape.TensorShape(orig_input_shape.tolist())]
else:
# NOTE(mrry): We could in principle work out the shape from the
# gradients and the attrs, but if we do not know orig_input_shape
# statically, then we are unlikely to know the shape of the
# gradients either.
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("Conv2DBackpropFilter")
def _Conv2DBackpropFilterShape(op):
"""Shape function for the Conv2DBackpropFilter op."""
filter_shape = tensor_util.constant_value(op.inputs[1])
if filter_shape is not None:
return [tensor_shape.TensorShape(filter_shape.tolist())]
else:
# NOTE(mrry): We could in principle work out the shape from the
# gradients and the attrs, but if we do not know filter_shape
# statically, then we are unlikely to know the shape of the
# gradients either.
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("Conv2DBackpropInput")
def _Conv2DBackpropInputShape(op):
"""Shape function for the Conv2DBackpropInput op."""
input_shape = tensor_util.constant_value(op.inputs[0])
if input_shape is not None:
return [tensor_shape.TensorShape(input_shape.tolist())]
else:
# NOTE(mrry): We could in principle work out the shape from the
# gradients and the attrs, but if we do not know input_shape
# statically, then we are unlikely to know the shape of the
# gradients either.
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("DepthwiseConv2dNativeBackpropFilter")
def _DepthwiseConv2dNativeBackpropFilterShape(op):
"""Shape function for the DepthwiseConv2dNativeBackpropFilter op."""
filter_shape = tensor_util.constant_value(op.inputs[1])
if filter_shape is not None:
return [tensor_shape.TensorShape(filter_shape.tolist())]
else:
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("DepthwiseConv2dNativeBackpropInput")
def _DepthwiseConv2dNativeBackpropInputShape(op):
"""Shape function for the DepthwiseConv2dNativeBackpropInput op."""
input_shape = tensor_util.constant_value(op.inputs[0])
if input_shape is not None:
return [tensor_shape.TensorShape(input_shape.tolist())]
else:
return [tensor_shape.unknown_shape(ndims=4)]
@ops.RegisterShape("MaxPoolGrad")
@ops.RegisterShape("MaxPoolGradWithArgmax")
def _MaxPoolGradShape(op):
"""Shape function for the MaxPoolGrad op."""
orig_input_shape = op.inputs[0].get_shape().with_rank(4)
return [orig_input_shape]
@ops.RegisterStatistics("Conv2D", "flops")
def _calc_conv_flops(graph, node):
"""Calculates the compute resources needed for Conv2D."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
filter_in_depth = int(filter_shape[2])
output_count = np.prod(output_shape.as_list())
return ops.OpStats("flops", (output_count * filter_in_depth * filter_height *
filter_width * 2))
@ops.RegisterStatistics("Conv2D", "weight_parameters")
def _calc_conv_weight_params(graph, node):
"""Calculates the on-disk size of the weights for Conv2D."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
filter_in_depth = int(filter_shape[2])
filter_out_depth = int(filter_shape[3])
return ops.OpStats("weight_parameters", (filter_height * filter_width *
filter_in_depth * filter_out_depth))
@ops.RegisterStatistics("DepthwiseConv2dNative", "flops")
def _calc_depthwise_conv_flops(graph, node):
"""Calculates the compute resources needed for DepthwiseConv2dNative."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
output_count = np.prod(output_shape.as_list())
return ops.OpStats("flops", (output_count * filter_height * filter_width * 2))
@ops.RegisterStatistics("DepthwiseConv2dNative", "weight_parameters")
def _calc_depthwise_conv_weight_params(graph, node):
"""Calculates the on-disk size of the weights for DepthwiseConv2dNative."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
filter_in_depth = int(filter_shape[2])
filter_channel_multiplier = int(filter_shape[3])
return ops.OpStats("weight_parameters", (filter_height * filter_width *
filter_in_depth *
filter_channel_multiplier))
@ops.RegisterShape("Conv3D")
def _Conv3DShape(op):
"""Shape function for Conv3D."""
input_shape = op.inputs[0].get_shape().with_rank(5)
filter_shape = op.inputs[1].get_shape().with_rank(5)
batch_size = input_shape[0]
out_channels = filter_shape[4]
# Check that the input number of channels is compatible between
# input data and filter size.
input_shape[4].assert_is_compatible_with(filter_shape[3])
stride_b, stride_p, stride_r, stride_c, stride_d = op.get_attr("strides")
assert stride_b == 1
assert stride_d == 1
padding_type = op.get_attr("padding")
out_planes, out_rows, out_cols = common_shapes.get_conv_output_size(
input_shape[1:4], filter_shape[0:3], (stride_p, stride_r, stride_c),
padding_type)
return [tensor_shape.TensorShape([batch_size, out_planes, out_rows, out_cols,
out_channels])]
@ops.RegisterShape("MaxPool3D")
@ops.RegisterShape("AvgPool3D")
def _Pool3DShape(op):
"""Shape function for Max/AvgPool3D."""
input_shape = op.inputs[0].get_shape().with_rank(5)
ksize_b, ksize_p, ksize_r, ksize_c, ksize_d = op.get_attr("ksize")
assert ksize_b == 1
assert ksize_d == 1
stride_b, stride_p, stride_r, stride_c, stride_d = op.get_attr("strides")
assert stride_b == 1
assert stride_d == 1
batch_size = input_shape[0]
channels = input_shape[4]
padding = op.get_attr("padding")
out_planes, out_rows, out_cols = common_shapes.get_conv_output_size(
input_shape[1:4], (ksize_p, ksize_r, ksize_c),
(stride_p, stride_r, stride_c), padding)
return [tensor_shape.TensorShape([batch_size, out_planes, out_rows, out_cols,
channels])]
@ops.RegisterShape("Conv3DBackpropFilter")
def _Conv3DBackpropFilterShape(op):
"""Shape function for the Conv3DBackpropFilter op."""
filter_shape = op.inputs[1].get_shape()
return [filter_shape.with_rank(5)]
@ops.RegisterShape("Conv3DBackpropInput")
def _Conv3DBackpropInputShape(op):
"""Shape function for the Conv3DBackpropInput op."""
input_shape = op.inputs[0].get_shape()
return [input_shape.with_rank(5)]
@ops.RegisterShape("Conv3DBackpropFilterV2")
def _Conv3DBackpropFilterShapeV2(op):
"""Shape function for the Conv3DBackpropFilterV2 op."""
filter_shape = tensor_util.constant_value(op.inputs[1])
return [tensor_shape.TensorShape(filter_shape).with_rank(5)]
@ops.RegisterShape("Conv3DBackpropInputV2")
def _Conv3DBackpropInputShapeV2(op):
"""Shape function for the Conv3DBackpropInputV2 op."""
input_shape = tensor_util.constant_value(op.inputs[0])
return [tensor_shape.TensorShape(input_shape).with_rank(5)]
@ops.RegisterShape("AvgPool3DGrad")
def _AvgPool3DGradShape(op):
"""Shape function for the AvgPool3DGrad op."""
orig_input_shape = tensor_util.constant_value(op.inputs[0])
return [tensor_shape.TensorShape(orig_input_shape).with_rank(5)]
@ops.RegisterShape("MaxPool3DGrad")
def _MaxPool3DGradShape(op):
"""Shape function for the MaxPoolGrad op."""
orig_input_shape = op.inputs[0].get_shape().with_rank(5)
return [orig_input_shape]
@ops.RegisterStatistics("BiasAdd", "flops")
def _calc_bias_add_flops(graph, node):
"""Calculates the computing needed for BiasAdd."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
input_count = np.prod(input_shape.as_list())
return ops.OpStats("flops", input_count)
@ops.RegisterStatistics("BiasAdd", "weight_parameters")
def _calc_bias_add_weight_params(graph, node):
"""Calculates the on-disk weight parameters for BiasAdd."""
bias_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[1])
bias_shape.assert_is_fully_defined()
bias_count = np.prod(bias_shape.as_list())
return ops.OpStats("weight_parameters", bias_count)
def xw_plus_b(x, weights, biases, name=None): # pylint: disable=invalid-name
"""Computes matmul(x, weights) + biases.
Args:
x: a 2D tensor. Dimensions typically: batch, in_units
weights: a 2D tensor. Dimensions typically: in_units, out_units
biases: a 1D tensor. Dimensions: out_units
name: A name for the operation (optional). If not specified
"xw_plus_b" is used.
Returns:
A 2-D Tensor computing matmul(x, weights) + biases.
Dimensions typically: batch, out_units.
"""
with ops.op_scope([x, weights, biases], name, "xw_plus_b") as name:
x = ops.convert_to_tensor(x, name="x")
weights = ops.convert_to_tensor(weights, name="weights")
biases = ops.convert_to_tensor(biases, name="biases")
mm = math_ops.matmul(x, weights)
return bias_add(mm, biases, name=name)
def xw_plus_b_v1(x, weights, biases, name=None): # pylint: disable=invalid-name
"""Computes matmul(x, weights) + biases.
This is a deprecated version of that will soon be removed.
Args:
x: a 2D tensor. Dimensions typically: batch, in_units
weights: a 2D tensor. Dimensions typically: in_units, out_units
biases: a 1D tensor. Dimensions: out_units
name: A name for the operation (optional). If not specified
"xw_plus_b_v1" is used.
Returns:
A 2-D Tensor computing matmul(x, weights) + biases.
Dimensions typically: batch, out_units.
"""
with ops.op_scope([x, weights, biases], name, "xw_plus_b_v1") as name:
x = ops.convert_to_tensor(x, name="x")
weights = ops.convert_to_tensor(weights, name="weights")
biases = ops.convert_to_tensor(biases, name="biases")
mm = math_ops.matmul(x, weights)
return bias_add_v1(mm, biases, name=name)
# pylint: disable=invalid-name
def dropout(x, keep_prob, noise_shape=None, seed=None, name=None):
"""Computes dropout.
With probability `keep_prob`, outputs the input element scaled up by
`1 / keep_prob`, otherwise outputs `0`. The scaling is so that the expected
sum is unchanged.
By default, each element is kept or dropped independently. If `noise_shape`
is specified, it must be
[broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]`
will make independent decisions. For example, if `shape(x) = [k, l, m, n]`
and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be
kept independently and each row and column will be kept or not kept together.
Args:
x: A tensor.
keep_prob: A scalar `Tensor` with the same type as x. The probability
that each element is kept.
noise_shape: A 1-D `Tensor` of type `int32`, representing the
shape for randomly generated keep/drop flags.
seed: A Python integer. Used to create random seeds. See
[`set_random_seed`](../../api_docs/python/constant_op.md#set_random_seed)
for behavior.
name: A name for this operation (optional).
Returns:
A Tensor of the same shape of `x`.
Raises:
ValueError: If `keep_prob` is not in `(0, 1]`.
"""
with ops.op_scope([x], name, "dropout") as name:
x = ops.convert_to_tensor(x, name="x")
if isinstance(keep_prob, float) and not 0 < keep_prob <= 1:
raise ValueError("keep_prob must be a scalar tensor or a float in the "
"range (0, 1], got %g" % keep_prob)
keep_prob = ops.convert_to_tensor(keep_prob,
dtype=x.dtype,
name="keep_prob")
keep_prob.get_shape().assert_is_compatible_with(tensor_shape.scalar())
noise_shape = noise_shape if noise_shape is not None else array_ops.shape(x)
# uniform [keep_prob, 1.0 + keep_prob)
random_tensor = keep_prob
random_tensor += random_ops.random_uniform(noise_shape,
seed=seed,
dtype=x.dtype)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = math_ops.floor(random_tensor)
ret = x * math_ops.inv(keep_prob) * binary_tensor
ret.set_shape(x.get_shape())
return ret
def top_k(input, k=1, sorted=True, name=None):
"""Finds values and indices of the `k` largest entries for the last dimension.
If the input is a vector (rank-1), finds the `k` largest entries in the vector
and outputs their values and indices as vectors. Thus `values[j]` is the
`j`-th largest entry in `input`, and its index is `indices[j]`.
For matrices (resp. higher rank input), computes the top `k` entries in each
row (resp. vector along the last dimension). Thus,
values.shape = indices.shape = input.shape[:-1] + [k]
If two elements are equal, the lower-index element appears first.
Args:
input: 1-D or higher `Tensor` with last dimension at least `k`.
k: 0-D `int32` `Tensor`. Number of top elements to look for along the last
dimension (along each row for matrices).
sorted: If true the resulting `k` elements will be sorted by the values in
descending order.
name: Optional name for the operation.
Returns:
values: The `k` largest elements along each last dimensional slice.
indices: The indices of `values` within the last dimension of `input`.
"""
return gen_nn_ops._top_kv2(input, k=k, sorted=sorted, name=name)
def conv1d(value, filters, stride, padding,
use_cudnn_on_gpu=None, data_format=None,
name=None):
"""Computes a 1-D convolution given 3-D input and filter tensors.
Given an input tensor of shape [batch, in_width, in_channels]
and a filter / kernel tensor of shape
[filter_width, in_channels, out_channels], this op reshapes
the arguments to pass them to conv2d to perform the equivalent
convolution operation.
Internally, this op reshapes the input tensors and invokes
`tf.nn.conv2d`. A tensor of shape [batch, in_width, in_channels]
is reshaped to [batch, 1, in_width, in_channels], and the filter
is reshaped to [1, filter_width, in_channels, out_channels].
The result is then reshaped back to [batch, out_width, out_channels]
(where out_width is a function of the stride and padding as in
conv2d) and returned to the caller.
Args:
value: A 3D `Tensor`. Must be of type `float32` or `float64`.
filters: A 3D `Tensor`. Must have the same type as `input`.
stride: An `integer`. The number of entries by which
the filter is moved right at each step.
padding: 'SAME' or 'VALID'
use_cudnn_on_gpu: An optional `bool`. Defaults to `True`.
data_format: An optional `string` from `"NHWC", "NCHW"`. Defaults
to `"NHWC"`, the data is stored in the order of
[batch, in_width, in_channels]. The `"NCHW"` format stores
data as [batch, in_channels, in_width].
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as input.
"""
with ops.op_scope([value, filters], name, "conv1d") as name:
# Reshape the input tensor to [batch, 1, in_width, in_channels]
value = array_ops.expand_dims(value, 1)
# And reshape the filter to [1, filter_width, in_channels, out_channels]
filters = array_ops.expand_dims(filters, 0)
result = gen_nn_ops.conv2d(value, filters, [1, 1, stride, 1], padding,
use_cudnn_on_gpu=use_cudnn_on_gpu,
data_format=data_format)
return array_ops.squeeze(result, [1])
@ops.RegisterShape("Dilation2D")
def _Dilation2DShape(op):
"""Shape function for Dilation2D op."""
input_shape = op.inputs[0].get_shape().with_rank(4)
filter_shape = op.inputs[1].get_shape().with_rank(3)
batch_size = input_shape[0]
in_rows = input_shape[1]
in_cols = input_shape[2]
depth = input_shape[3]
filter_rows = filter_shape[0]
filter_cols = filter_shape[1]
# Check that the input depths are compatible.
input_shape[3].assert_is_compatible_with(filter_shape[2])
stride_b, stride_r, stride_c, stride_d = op.get_attr("strides")
if stride_b != 1 or stride_d != 1:
raise ValueError("Current implementation does not yet support "
"strides in the batch and depth dimensions.")
rate_b, rate_r, rate_c, rate_d = op.get_attr("rates")
if rate_b != 1 or rate_d != 1:
raise ValueError("Current implementation does not yet support "
"rates in the batch and depth dimensions.")
filter_rows_eff = filter_rows + (filter_rows - 1) * (rate_r - 1)
filter_cols_eff = filter_cols + (filter_cols - 1) * (rate_c - 1)
padding = op.get_attr("padding")
out_rows, out_cols = common_shapes.get2d_conv_output_size(in_rows, in_cols,
filter_rows_eff,
filter_cols_eff,
stride_r, stride_c,
padding)
output_shape = [batch_size, out_rows, out_cols, depth]
return [tensor_shape.TensorShape(output_shape)]
@ops.RegisterShape("Dilation2DBackpropInput")
def _Dilation2DBackpropInputShape(op):
"""Shape function for Dilation2DBackpropInput op."""
return [op.inputs[0].get_shape()]
@ops.RegisterShape("Dilation2DBackpropFilter")
def _Dilation2DBackpropFilterShape(op):
"""Shape function for Dilation2DBackpropFilter op."""
return [op.inputs[1].get_shape()]
@ops.RegisterStatistics("Dilation2D", "flops")
def _calc_dilation2d_flops(graph, node):
"""Calculates the compute resources needed for Dilation2D."""
input_shape = graph_util.tensor_shape_from_node_def_name(graph, node.input[0])
input_shape.assert_is_fully_defined()
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
output_shape = graph_util.tensor_shape_from_node_def_name(graph, node.name)
output_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
output_count = np.prod(output_shape.as_list())
return ops.OpStats("flops", (output_count * filter_height * filter_width * 2))
@ops.RegisterStatistics("Dilation2D", "weight_parameters")
def _calc_dilation2d_weight_params(graph, node):
"""Calculates the on-disk size of the weights for Dilation2D."""
filter_shape = graph_util.tensor_shape_from_node_def_name(graph,
node.input[1])
filter_shape.assert_is_fully_defined()
filter_height = int(filter_shape[0])
filter_width = int(filter_shape[1])
filter_depth = int(filter_shape[2])
return ops.OpStats("weight_parameters",
(filter_height * filter_width * filter_depth))
def erosion2d(value, kernel, strides, rates, padding, name=None):
"""Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors.
The `value` tensor has shape `[batch, in_height, in_width, depth]` and the
`kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e.,
each input channel is processed independently of the others with its own
structuring function. The `output` tensor has shape
`[batch, out_height, out_width, depth]`. The spatial dimensions of the
output tensor depend on the `padding` algorithm. We currently only support the
default "NHWC" `data_format`.
In detail, the grayscale morphological 2-D erosion is given by:
output[b, y, x, c] =
min_{dy, dx} value[b,
strides[1] * y - rates[1] * dy,
strides[2] * x - rates[2] * dx,
c] -
kernel[dy, dx, c]
Duality: The erosion of `value` by the `kernel` is equal to the negation of
the dilation of `-value` by the reflected `kernel`.
Args:
value: A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`.
kernel: A `Tensor`. Must have the same type as `value`.
3-D with shape `[kernel_height, kernel_width, depth]`.
strides: A list of `ints` that has length `>= 4`.
1-D of length 4. The stride of the sliding window for each dimension of
the input tensor. Must be: `[1, stride_height, stride_width, 1]`.
rates: A list of `ints` that has length `>= 4`.
1-D of length 4. The input stride for atrous morphological dilation.
Must be: `[1, rate_height, rate_width, 1]`.
padding: A `string` from: `"SAME", "VALID"`.
The type of padding algorithm to use.
name: A name for the operation (optional). If not specified "erosion2d"
is used.
Returns:
A `Tensor`. Has the same type as `value`.
4-D with shape `[batch, out_height, out_width, depth]`.
Raises:
ValueError: If the `value` depth does not match `kernel`' shape, or if
padding is other than `'VALID'` or `'SAME'`.
"""
with ops.op_scope([value, kernel], name, "erosion2d") as name:
# Reduce erosion to dilation by duality.
return math_ops.neg(gen_nn_ops.dilation2d(input=math_ops.neg(value),
filter=array_ops.reverse(
kernel, [True, True, False]),
strides=strides,
rates=rates,
padding=padding,
name=name))
# pylint: enable=invalid-name
|
apache-2.0
| 5,910,611,416,458,937,000
| 41.535741
| 92
| 0.660375
| false
| 3.586929
| false
| false
| false
|
joseguerrero/sembrando
|
src/presentacion/paginas/pantalla9.py
|
1
|
30062
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from librerias import pantalla
from librerias.boton import boton
from librerias.texto import texto
from librerias.popups import PopUp
from librerias.imagen import imagen
from librerias.contenido import cont
from librerias.imgfondo import fondo
from librerias.pixelperfect import *
from librerias.textopopups import p9
from librerias.objmask import object_mask
from paginas import menucfg
from paginas import pantalla2
from paginas import pantalla8
from paginas import pantalla10
class estado(pantalla.Pantalla):
def __init__(self, parent):
"""
Método inicializador de la clase.
@param parent: Instancia del gestor de pantallas.
@type parent: Manejador
"""
self.parent = parent
self.previa = True
self.deteccion_movimiento = False
self.fondo_texto = False
self.background = pygame.image.load(self.fondos + "fondo-mapa2.png")
self.banner_siembra = imagen(self.banners + "banner-siembra.png", 0, 0)
self.banner_inf = imagen(self.banners + "banner-inf.png", 0, 432)
self.mouse = object_mask("Cursor", 850, 512, self.varios + "puntero.png")
# Para mantener las piezas del mapa bien ubicadas no se deben modificar los valores x e y de las regiones, solo de zulia.
self.zulia = object_mask(u"región zuliana", 13, 140, self.varios + "zulia-des.png", self.varios + "zulia-act.png")
self.occ = object_mask(u"región occidental", self.zulia.rect.left + 55, self.zulia.rect.top - 6, self.varios + "occ-des.png", self.varios + "occ-act.png")
self.central = object_mask(u"región central", self.zulia.rect.left + 115, self.zulia.rect.top + 37, self.varios + "central-des.png", self.varios + "central-act.png")
self.capital = object_mask(u"región capital", self.zulia.rect.left + 152, self.zulia.rect.top + 32, self.varios + "capital-des.png", self.varios + "capital-act.png")
self.ori = object_mask(u"región nor oriental", self.zulia.rect.left +195, self.zulia.rect.top + 29, self.varios + "ori-des.png", self.varios + "ori-act.png")
self.andes = object_mask(u"región los andes", self.zulia.rect.left + 23, self.zulia.rect.top + 48, self.varios + "andes-des.png", self.varios + "andes-act.png")
self.llanos = object_mask(u"región los llanos", self.zulia.rect.left + 26, self.zulia.rect.top + 47, self.varios + "llanos-des.png", self.varios + "llanos-act.png")
self.guayana = object_mask(u"región guayana", self.zulia.rect.left + 140, self.zulia.rect.top + 48, self.varios + "guayana-des.png", self.varios + "guayana-act.png")
self.insu = object_mask(u"región insular", self.zulia.rect.left + 149, self.zulia.rect.top - 6, self.varios + "insular-des.png", self.varios + "insular-act.png")
self.limites1 = pygame.image.load(self.varios + "limitemar.png").convert_alpha()
self.limites2 = pygame.image.load(self.varios + "limitemar2.png").convert_alpha()
self.zona_r = pygame.image.load(self.varios + "zona-recla.png").convert_alpha()
self.n_estados = pygame.image.load(self.varios + "nombre-estados.png").convert_alpha()
self.cargar_botones()
self.cargar_textos()
self.resume()
self.bg = fondo(573, 377)
def cargar_textos(self):
"""
Carga los textos utilizados en esta pantalla.
"""
self.texto9_2_1 = texto(490, 60, cont["texto9_2_1"] , self.parent.config.t_fuente, "normal", 1000)
self.texto9_2_2 = texto(490, self.texto9_2_1.y + self.texto9_2_1.ancho_final + 10, cont["texto9_2_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_2_3 = texto(490, self.texto9_2_2.y + self.texto9_2_2.ancho_final + 10, cont["texto9_2_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_2_4 = texto(490, self.texto9_2_3.y + self.texto9_2_3.ancho_final + 10, cont["texto9_2_4"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_3_1 = texto(490, 60, cont["texto9_3_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_3_2 = texto(490, self.texto9_3_1.y + self.texto9_3_1.ancho_final + 10, cont["texto9_3_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_3_3 = texto(490, self.texto9_3_2.y + self.texto9_3_2.ancho_final + 10, cont["texto9_3_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_4_1 = texto(490, 60, cont["texto9_4_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_4_2 = texto(490, self.texto9_4_1.y + self.texto9_4_1.ancho_final + 10, cont["texto9_4_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_4_3 = texto(490, self.texto9_4_2.y + self.texto9_4_2.ancho_final + 10, cont["texto9_4_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_5_1 = texto(490, 60, cont["texto9_5_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_5_2 = texto(490, self.texto9_5_1.y + self.texto9_5_1.ancho_final + 10, cont["texto9_5_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_5_3 = texto(490, self.texto9_5_2.y + self.texto9_5_2.ancho_final + 10, cont["texto9_5_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_6_1 = texto(490, 60, cont["texto9_6_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_6_2 = texto(490, self.texto9_6_1.y + self.texto9_6_1.ancho_final + 10, cont["texto9_6_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_6_3 = texto(490, self.texto9_6_2.y + self.texto9_6_2.ancho_final + 10, cont["texto9_6_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_7_1 = texto(490, 60, cont["texto9_7_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_7_2 = texto(490, self.texto9_7_1.y + self.texto9_7_1.ancho_final + 10, cont["texto9_7_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_7_3 = texto(490, self.texto9_7_2.y + self.texto9_7_2.ancho_final + 10, cont["texto9_7_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_8_1 = texto(490, 60, cont["texto9_8_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_8_2 = texto(490, self.texto9_8_1.y + self.texto9_8_1.ancho_final + 10, cont["texto9_8_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_8_3 = texto(490, self.texto9_8_2.y + self.texto9_8_2.ancho_final + 10, cont["texto9_8_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_9_1 = texto(490, 60, cont["texto9_9_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_9_2 = texto(490, self.texto9_9_1.y + self.texto9_9_1.ancho_final + 10, cont["texto9_9_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_9_3 = texto(490, self.texto9_9_2.y + self.texto9_9_2.ancho_final + 10, cont["texto9_9_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_10_1 = texto(490, 60, cont["texto9_10_1"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_10_2 = texto(490, self.texto9_10_1.y + self.texto9_10_1.ancho_final + 10, cont["texto9_10_2"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_10_3 = texto(490, self.texto9_10_2.y + self.texto9_10_2.ancho_final + 10, cont["texto9_10_3"], self.parent.config.t_fuente, "normal", 1000)
self.texto9_10_4 = texto(490, self.texto9_10_3.y + self.texto9_10_3.ancho_final + 10, cont["texto9_10_4"], self.parent.config.t_fuente, "normal", 1000)
self.popup_ins1 = PopUp(self.parent, (p9["texto1"] , ), "", None , self.grupo_popup, 1, 750, 400, -100)
self.popup_ins1.agregar_grupo()
def cargar_botones(self):
"""
Carga los botones utilizados en esta pantalla.
"""
self.home = boton("home", "Menú", self.botones + "boton-menu.png", 3, 889, 440, None, False, 1)
self.volver = boton("volver", "Regresar", self.botones + "boton-regresar.png", 3, 320, 445, None, False, 1)
self.config = boton("config", "Accesibilidad", self.botones + "boton-acc.png", 3 ,60, 445, None, False, 1)
def start(self):
pass
def cleanUp(self):
pass
def pause(self):
pass
def resume(self):
"""
Verifica si se realizaron cambios en la configuración. Carga los valores iniciales de esta pantalla.
"""
if self.parent.config.texto_cambio == True:
self.cargar_botones()
self.cargar_textos()
self.parent.config.texto_cambio = False
self.popup_ins1.agregar_grupo()
self.capital.apagar()
self.ori.apagar()
self.zulia.apagar()
self.occ.apagar()
self.andes.apagar()
self.llanos.apagar()
self.central.apagar()
self.guayana.apagar()
self.grupo_banner.add(self.banner_siembra, self.banner_inf)
self.grupo_botones.add(self.config, self.volver, self.home)
self.grupo_mapa.add(self.zulia, self.occ, self.central, self.insu, self.capital, self.ori, self.andes, self.llanos, self.guayana)
self.spserver.processtext(u"Pantalla: La Agricultura en Venezuela: ", self.parent.config.activar_lector)
self.spserver.processtext(p9["lector1"], self.parent.config.activar_lector)
def handleEvents(self, events):
"""
Evalúa los eventos que se generan en esta pantalla.
@param events: Lista de los eventos.
@type events: list
"""
for event in events:
if event.type == pygame.QUIT:
self.parent.quit()
if event.type == pygame.KEYDOWN:
self.chequeo_mascaras(self.grupo_mapa)
self.chequeo_botones(self.grupo_botones)
self.lista_final = self.lista_palabra + self.lista_mascaras + self.lista_botones
self.numero_elementos = len(self.lista_final)
if event.key == pygame.K_RIGHT:
self.fondo_texto = False
self.grupo_palabras.empty()
self.deteccion_movimiento = True
self.controlador_lector_evento_K_RIGHT()
elif event.key == pygame.K_LEFT:
self.fondo_texto = False
self.grupo_palabras.empty()
self.controlador_lector_evento_K_LEFT()
if self.deteccion_movimiento:
if event.key == pygame.K_RETURN:
if self.x.tipo_objeto == "mapa":
self.fondo_texto = True
if self.x.id == u"región capital":
self.grupo_palabras.empty()
self.central.apagar()
self.llanos.apagar()
self.zulia.apagar()
self.ori.apagar()
self.occ.apagar()
self.andes.apagar()
self.llanos.apagar()
self.capital.iluminar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_2_1.img_palabras, self.texto9_2_2.img_palabras, self.texto9_2_3.img_palabras, self.texto9_2_4.img_palabras)
self.spserver.processtext(cont["texto9_2_1l"] + self.texto9_2_2.texto + self.texto9_2_3.texto + self.texto9_2_4.texto, self.parent.config.activar_lector)
elif self.x.id == u"región central":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.zulia.apagar()
self.ori.apagar()
self.occ.apagar()
self.andes.apagar()
self.llanos.apagar()
self.central.iluminar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_3_1.img_palabras, self.texto9_3_2.img_palabras, self.texto9_3_3.img_palabras)
self.spserver.processtext(cont["texto9_3_1l"] + self.texto9_3_2.texto + self.texto9_3_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región los llanos":
self.grupo_palabras.empty()
self.capital.apagar()
self.central.apagar()
self.ori.apagar()
self.zulia.apagar()
self.occ.apagar()
self.andes.apagar()
self.llanos.iluminar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_4_1.img_palabras, self.texto9_4_2.img_palabras, self.texto9_4_3.img_palabras)
self.spserver.processtext(cont["texto9_4_1l"] + self.texto9_4_2.texto + self.texto9_4_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región occidental":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.zulia.apagar()
self.andes.apagar()
self.occ.iluminar()
self.llanos.apagar()
self.guayana.apagar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_5_1.img_palabras, self.texto9_5_2.img_palabras, self.texto9_5_3.img_palabras)
self.spserver.processtext(cont["texto9_5_1l"] + self.texto9_5_2.texto + self.texto9_5_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región zuliana":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.zulia.iluminar()
self.occ.apagar()
self.andes.apagar()
self.llanos.apagar()
self.guayana.apagar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_6_1.img_palabras, self.texto9_6_2.img_palabras, self.texto9_6_3.img_palabras)
self.spserver.processtext(cont["texto9_6_1l"] + self.texto9_6_2.texto + self.texto9_6_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región los andes":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.zulia.apagar()
self.ori.apagar()
self.occ.apagar()
self.andes.iluminar()
self.llanos.apagar()
self.guayana.apagar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_7_1.img_palabras, self.texto9_7_2.img_palabras, self.texto9_7_3.img_palabras)
self.spserver.processtext(cont["texto9_7_1l"] + self.texto9_7_2.texto + self.texto9_7_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región nor oriental":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.iluminar()
self.zulia.apagar()
self.occ.apagar()
self.andes.apagar()
self.guayana.apagar()
self.insu.apagar()
self.grupo_palabras.add(self.texto9_8_1.img_palabras, self.texto9_8_2.img_palabras, self.texto9_8_3.img_palabras)
self.spserver.processtext(cont["texto9_8_1l"] + self.texto9_8_2.texto + self.texto9_8_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región guayana":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.occ.apagar()
self.zulia.apagar()
self.andes.apagar()
self.llanos.apagar()
self.insu.apagar()
self.guayana.iluminar()
self.grupo_palabras.add(self.texto9_9_1.img_palabras, self.texto9_9_2.img_palabras, self.texto9_9_3.img_palabras)
self.spserver.processtext(cont["texto9_9_1l"] + self.texto9_9_2.texto + self.texto9_9_3.texto, self.parent.config.activar_lector)
if self.x.id == u"región insular":
self.grupo_palabras.empty()
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.occ.apagar()
self.zulia.apagar()
self.andes.apagar()
self.llanos.apagar()
self.guayana.apagar()
self.insu.iluminar()
self.grupo_palabras.add(self.texto9_10_1.img_palabras, self.texto9_10_2.img_palabras, self.texto9_10_3.img_palabras, self.texto9_10_4.img_palabras )
self.spserver.processtext(cont["texto9_10_1l"] + self.texto9_10_2.texto + self.texto9_10_3.texto + self.texto9_10_4.texto, self.parent.config.activar_lector)
elif self.x.tipo_objeto == "boton":
if self.x.id == "volver":
self.limpiar_grupos()
self.parent.animacion = 3
self.parent.changeState(pantalla8.estado(self.parent, 3))
elif self.x.id == "config":
self.limpiar_grupos()
self.parent.pushState(menucfg.estado(self.parent, self.previa))
elif self.x.id == "home":
self.limpiar_grupos()
self.parent.changeState(pantalla2.estado(self.parent))
lista = spritecollide_pp(self.mouse, self.grupo_mapa)
if not lista == []:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.deteccion_movimiento = False
self.fondo_texto = True
if lista[0].id == u"región capital":
self.central.apagar()
self.llanos.apagar()
self.ori.apagar()
self.occ.apagar()
self.zulia.apagar()
self.andes.apagar()
self.llanos.apagar()
self.capital.iluminar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_2_1.img_palabras, self.texto9_2_2.img_palabras, self.texto9_2_3.img_palabras , self.texto9_2_4.img_palabras)
if lista[0].id == u"región central":
self.capital.apagar()
self.llanos.apagar()
self.ori.apagar()
self.occ.apagar()
self.zulia.apagar()
self.andes.apagar()
self.llanos.apagar()
self.central.iluminar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_3_1.img_palabras, self.texto9_3_2.img_palabras, self.texto9_3_3.img_palabras)
if lista[0].id == u"región los llanos":
self.capital.apagar()
self.central.apagar()
self.llanos.iluminar()
self.zulia.apagar()
self.ori.apagar()
self.occ.apagar()
self.andes.apagar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_4_1.img_palabras, self.texto9_4_2.img_palabras, self.texto9_4_3.img_palabras)
if lista[0].id == u"región occidental":
self.capital.apagar()
self.llanos.apagar()
self.ori.apagar()
self.central.apagar()
self.zulia.apagar()
self.occ.iluminar()
self.llanos.apagar()
self.guayana.apagar()
self.andes.apagar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_5_1.img_palabras, self.texto9_5_2.img_palabras, self.texto9_5_3.img_palabras)
if lista[0].id == u"región zuliana":
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.zulia.iluminar()
self.occ.apagar()
self.andes.apagar()
self.llanos.apagar()
self.guayana.apagar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_6_1.img_palabras, self.texto9_6_2.img_palabras, self.texto9_6_3.img_palabras)
if lista[0].id == u"región los andes":
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.guayana.apagar()
self.zulia.apagar()
self.ori.apagar()
self.occ.apagar()
self.andes.iluminar()
self.llanos.apagar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_7_1.img_palabras, self.texto9_7_2.img_palabras, self.texto9_7_3.img_palabras)
if lista[0].id == u"región nor oriental":
self.capital.apagar()
self.central.apagar()
self.ori.iluminar()
self.llanos.apagar()
self.guayana.apagar()
self.zulia.apagar()
self.occ.apagar()
self.andes.apagar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_8_1.img_palabras, self.texto9_8_2.img_palabras, self.texto9_8_3.img_palabras)
if lista[0].id == u"región guayana":
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.zulia.apagar()
self.occ.apagar()
self.andes.apagar()
self.guayana.iluminar()
self.insu.apagar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_9_1.img_palabras, self.texto9_9_2.img_palabras, self.texto9_9_3.img_palabras)
if lista[0].id == u"región insular":
self.capital.apagar()
self.llanos.apagar()
self.central.apagar()
self.ori.apagar()
self.zulia.apagar()
self.occ.apagar()
self.andes.apagar()
self.guayana.apagar()
self.insu.iluminar()
self.grupo_palabras.empty()
self.grupo_palabras.add(self.texto9_10_1.img_palabras, self.texto9_10_2.img_palabras, self.texto9_10_3.img_palabras, self.texto9_10_4.img_palabras)
elif not self.deteccion_movimiento:
self.fondo_texto = False
self.capital.apagar()
self.central.apagar()
self.guayana.apagar()
self.andes.apagar()
self.zulia.apagar()
self.occ.apagar()
self.ori.apagar()
self.llanos.apagar()
self.grupo_palabras.empty()
self.grupo_fondotexto.empty()
if pygame.sprite.spritecollideany(self.raton, self.grupo_botones):
sprite = pygame.sprite.spritecollide(self.raton, self.grupo_botones, False)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if sprite[0].id == "volver":
self.limpiar_grupos()
self.parent.animacion = 3
self.parent.changeState(pantalla8.estado(self.parent, 3))
elif sprite[0].id == "config":
self.limpiar_grupos()
self.parent.pushState(menucfg.estado(self.parent, self.previa))
elif sprite[0].id == "home":
self.limpiar_grupos()
self.parent.changeState(pantalla2.estado(self.parent))
self.minimag(events)
def update(self):
"""
Actualiza la posición del cursor, el magnificador de pantalla en caso de que este activado, los
tooltip de los botones y animaciones o textos correspondientes.
"""
self.raton.update()
self.obj_magno.magnificar(self.parent.screen)
self.grupo_botones.update(self.grupo_tooltip)
self.mouse.rect.center = pygame.mouse.get_pos()
def draw(self):
"""
Dibuja el fondo de pantalla y los elementos pertenecientes a los grupos de sprites sobre la superficie
del manejador de pantallas.
"""
self.parent.screen.blit(self.background, (0, 0))
self.grupo_banner.draw(self.parent.screen)
self.parent.screen.blit(self.zona_r, (320, 233))
self.parent.screen.blit(self.limites1, (50, 60))
self.parent.screen.blit(self.limites2, (305, 145))
self.grupo_mapa.draw(self.parent.screen)
self.grupo_popup.draw(self.parent.screen)
if self.fondo_texto:
self.parent.screen.blit(self.bg.img, (451, 55))
self.grupo_botones.draw(self.parent.screen)
self.grupo_fondotexto.draw(self.parent.screen)
self.grupo_palabras.draw(self.parent.screen)
self.grupo_tooltip.draw(self.parent.screen)
self.parent.screen.blit(self.n_estados, (40, 95))
if self.parent.habilitar:
self.grupo_magnificador.draw(self.parent.screen, self.enable)
if self.deteccion_movimiento:
self.dibujar_rect()
def ir_glosario(self):
self.parent.pushState(pantalla10.estado(self.parent))
|
gpl-3.0
| 7,081,254,828,094,702,000
| 58.114173
| 189
| 0.497036
| false
| 3.289877
| true
| false
| false
|
barct/odoo-coop
|
infocoop_epec_consumos/tab_fact.py
|
1
|
5194
|
# -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
from openerp.osv import osv
from collections import OrderedDict
class infocoop_tab_fact(models.Model):
_inherit = "infocoop_tab_fact"
class Values():
code = "(desconocido)"
conexiones = 1
consumo = 0
cargo_fijo = 0
monto_ee = 0
monto_ts = 0
consumo_ts = 0
monto_pe = 0
consumo_pe = 0
monto_impuestos = 0
monto_otros = 0
def __iadd__(self, vals):
self.conexiones += vals.conexiones
self.consumo += vals.consumo
self.cargo_fijo += vals.cargo_fijo
self.monto_ee += vals.monto_ee
self.monto_ts += vals.monto_ts
self.consumo_ts += vals.consumo_ts
self.monto_pe += vals.monto_pe
self.consumo_pe += vals.consumo_pe
self.monto_impuestos += vals.monto_impuestos
self.monto_otros += vals.monto_otros
return self
def __unicode__(self):
txt = """code %s
conexiones %s
consumo: %s
cargo_fijo: %s
monto_ee: %s
monto_ts: %s
consumo_ts: %s
monto_pe: %s
consumo_pe: %s
monto_impuestos: %s
monto_otros: %s """
return txt % (self.code,
self.conexiones,
self.consumo,
self.cargo_fijo,
self.monto_ee,
self.monto_ts,
self.consumo_ts,
self.monto_pe,
self.consumo_pe,
self.monto_impuestos,
self.monto_otros, )
class ParticularReport(models.AbstractModel):
_name = 'report.infocoop_epec_consumos.report_example_report_view'
def get_epec_data(self, docs):
data = list()
for r in docs:
values = dict()
liq_ids = self.env["infocoop_liquidac"].search([
("servicios", "=", "/E"),
("periodo", "=", r.periodo), ])
for l in liq_ids:
if l.service_category_id.group_id:
group, level = l.service_category_id.\
group_id.define_segment(l.cons_ee)
else:
group = l.service_category_id.group_id.code
level = None
v = Values()
v.consumo = float(l.cons_ee)
v.cargo_fijo = float(l.cargo_fijo)
v.monto_ee = float(l.imp_ee)
v.monto_impuestos = float(l.neto_imp)
v.consumo_ts = float(l.ts_kwh)
v.monto_ts = float(l.ts_amount)
v.consumo_pe = float(l.pe_kwh)
v.monto_pe = float(l.pe_amount)
v.monto_otros = l.neto_serv - \
(v.monto_ee + v.cargo_fijo + v.monto_ts + v.monto_pe)
code = None
if l.service_category_id.group_id.code == "UR":
if l.pe_level == 2:
code = "5010"
elif l.pe_level == 3:
code = "5020"
elif l.ts_level == 2:
if l.cons_ee <= 150:
code = "5500"
else:
code = "5510"
elif l.ts_level == 1:
if l.cons_ee <= 150:
code = "5500"
elif l.cons_ee <= 450:
code = "5530"
else:
code = "5540"
else:
code = "5000"
v.code = group + str(level) + "-" + code
else:
if group == "NR" and level == 3:
v.code = group + str(level) + \
"-" + l.service_category_id.code
else:
v.code = group + str(level)
if v.code in values:
values[v.code] += v
else:
values[v.code] = v
data.append(
{"doc": r,
"values": OrderedDict(sorted(values.items(),
key=lambda t: t[0])), })
return data
@api.multi
def render_html(self, data=None):
report_obj = self.env['report']
report = report_obj._get_report_from_name(
'infocoop_epec_consumos.report_example_report_view')
docs = self.env['infocoop_tab_fact'].browse(self._ids)
data = self.get_epec_data(docs)
docargs = {
'doc_ids': self._ids,
'doc_model': report.model,
'docs': docs,
'data': data,
}
return report_obj.render(
'infocoop_epec_consumos.report_example_report_view', docargs)
|
gpl-3.0
| -7,498,251,093,839,075,000
| 33.85906
| 78
| 0.426646
| false
| 3.799561
| false
| false
| false
|
ufal/ker
|
server.py
|
1
|
9594
|
#!/usr/bin/env python
import flask
from flask import Flask
from flask import request
from werkzeug import secure_filename
import os, random, datetime, codecs
import sys, json, magic
import cPickle as pickle
import regex as re
import keywords
import argparse
import xml.etree.ElementTree
import zipfile
app = Flask(__name__)
upload_dir = "uploads"
cs_tagger = None
cs_idf_doc_count = None
cs_idf_table = None
en_tagger = None
en_idf_doc_count = None
en_idf_table = None
@app.route('/')
def index():
return "{}\n"
def root_dir(): # pragma: no cover
return os.path.abspath(os.path.dirname(__file__))
def get_file(file_name):
try:
src = os.path.join(root_dir(), file_name)
return open(src).read()
except IOError as exc:
return str(exc)
@app.route('/web', methods=['GET'])
def show_web():
content = get_file("web.html")
print content
return flask.Response(content, mimetype="text/html")
@app.route('/demo', methods=['GET'])
def show_simple_demo():
content = get_file("web.html")
content = re.sub(r"\$\(\'#header", "//", content)
content = re.sub(r"\$\(\'#footer", "//", content)
return flask.Response(content, mimetype="text/html")
@app.route('/', methods=['POST'])
def post_request():
start_time = datetime.datetime.now()
if 'file' in request.files:
file = request.files['file']
else:
class _file_wrapper(object):
def __init__(self, data):
self._data = data
import uuid
self.filename = str(uuid.uuid4())
def save(self, path):
with codecs.open(path, mode="w+", encoding="utf-8") as fout:
fout.write(self._data)
file = _file_wrapper(request.form["data"])
tagger = cs_tagger
idf_doc_count = cs_idf_doc_count
idf_table = cs_idf_table
json_response = None
try:
post_id = datetime.datetime.now().strftime("%Y-%m-%d/%H/%M-%S-")+\
str(random.randint(10000, 99999))
post_dir = os.path.join(upload_dir, post_id)
os.makedirs(post_dir)
if request.args.get('language') == 'en':
tagger = en_tagger
idf_doc_count = en_idf_doc_count
idf_table = en_idf_table
elif request.args.get('language') == 'cs':
pass
elif request.args.get('language'):
raise Exception('Unsupported language {}'.format(request.args.get('language')))
if request.args.get('threshold'):
try:
threshold = float(request.args.get('threshold'))
except:
raise Exception("Threshold \"{}\" is not valid float.".format(request.args.get("threshold")))
else:
threshold = 0.2
if request.args.get("maximum-words"):
try:
maximum_words = int(request.args.get('maximum-words'))
except:
raise Exception("Maximum number of words \"{}\" is not an integer.".format(request.args.get("maximum-words")))
else:
maximum_words = 15
file_name = secure_filename(file.filename)
file_path = os.path.join(post_dir, file_name)
file.save(os.path.join(file_path))
data, code = \
process_file(file_path, tagger, idf_doc_count, idf_table, threshold, maximum_words)
except Exception as e:
code = 400
data = {"error": e.message}
finally:
json_response = json.dumps(data)
print json_response.encode('unicode-escape')
log = {}
log['remote_addr'] = request.remote_addr
log['response_json'] = data
log['response_code'] = code
log['time'] = start_time.strftime("%Y-%m-%d %H:%M:%S")
log['duration'] = (datetime.datetime.now() - start_time).total_seconds()
f_log = open(os.path.join(post_dir, "log.json"), 'w')
json.dump(log, f_log)
f_log.close()
response = flask.Response(json_response,
content_type='application/json; charset=utf-8')
response.headers.add('content-length', len(json_response.encode('utf-8')))
response.status_code = code
return response
def process_file(file_path, tagger, idf_doc_count, idf_table, threshold, maximum_words):
"""
Takes the uploaded file, detecs its type (plain text, alto XML, zip)
and calls a parsing function accordingly. If everything succeeds it
returns keywords and 200 code, returns an error otherwise.
"""
file_info = magic.from_file(file_path)
lines = []
if re.match("^UTF-8 Unicode (with BOM) text", file_info):
lines = lines_from_txt_file(file_path, encoding='utf-8-sig')
elif re.match("^UTF-8 Unicode", file_info):
lines = lines_from_txt_file(file_path, encoding='utf-8')
elif re.match("^ASCII text", file_info):
lines = lines_from_txt_file(file_path, encoding='utf-8')
elif re.match('^XML 1.0 document', file_info) and \
(file_path.endswith('.alto') or file_path.endswith('.xml')):
lines = lines_from_alto_file(file_path)
elif re.match('^Zip archive data', file_info):
lines = lines_from_zip_file(file_path)
else:
return {"eror": "Unsupported file type: {}".format(file_info)}, 400
if not lines:
return {"error": "Empty file"}, 400
return keywords.get_keywords(lines, tagger, idf_doc_count, idf_table, threshold, maximum_words), 200
def lines_from_txt_file(file_path, encoding='utf-8'):
"""
Loads lines of text from a plain text file.
:param file_path: Path to the alto file or a file-like object.
"""
if type(file_path) is str:
f = codecs.open(file_path, 'r', encoding)
else:
f = file_path
content = [l.strip() for l in f]
f.close()
return content
def lines_from_alto_file(file_path):
"""
Loads lines of text from a provided alto file.
:param file_path: Path to the alto file or a file-like object.
"""
e = xml.etree.ElementTree.parse(file_path).getroot()
layout = None
for c in e.getchildren():
if c.tag.endswith('Layout'):
layout = c
break
if layout is None:
raise Exception("XML is not ALTO file (does not contain layout object).")
for page in layout.getchildren():
if not page.tag.endswith("Page"):
continue
text_lines = layout.findall(".//{http://www.loc.gov/standards/alto/ns-v2#}TextLine")
for text_line in text_lines:
line_words = []
for string in text_line.getchildren():
if not string.tag.endswith('String'):
continue
line_words.append(string.attrib['CONTENT'])
yield " ".join(line_words)
def lines_from_zip_file(file_path):
"""
Loads lines of text from a provided zip file. If it contains alto file, it
uses them, otherwise looks for txt files. Files can in an arbitrary depth.
:param file_path: Path to the uploaded zip file.
:type file_path: str
"""
archive = zipfile.ZipFile(file_path)
alto_files = [n for n in archive.namelist() if n.endswith(".alto") or n.endswith(".xml")]
if alto_files:
for f_name in alto_files:
for line in lines_from_alto_file(archive.open(f_name)):
yield line
else:
txt_files = [n for n in archive.namelist() if n.endswith(".txt")]
if not txt_files:
raise Exception("Archive contains neither alto files nor text files.")
for f_name in txt_files:
for line in lines_from_txt_file(archive.open(f_name)):
yield line
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Runs the KER server.')
parser.add_argument("--cs-morphodita", help="Path to a Czech tagger model for Morphodita.", required=True)
parser.add_argument("--cs-idf", help="Czech idf model.", required=True)
parser.add_argument("--en-morphodita", help="Path to a English tagger model for Morphodita.", required=True)
parser.add_argument("--en-idf", help="English idf model.", required=True)
parser.add_argument("--port", help="Port the server runs on", type=int, default=5000)
parser.add_argument("--host", help="IP address the server will run at", type=str, default="127.0.0.1")
args = parser.parse_args()
if os.path.exists(args.cs_morphodita):
cs_tagger = keywords.Morphodita(args.cs_morphodita)
else:
print >> sys.stderr, "File with Czech Morphodita model does not exist: {}".format(args.cs_morphodita)
exit(1)
if os.path.exists(args.cs_idf):
f_idf = open(args.cs_idf, 'rb')
cs_idf_doc_count = float(pickle.load(f_idf))
cs_idf_table = pickle.load(f_idf)
f_idf.close()
else:
print >> sys.stderr, "File with Czech IDF model does not exist: {}".format(args.cs_idf)
exit(1)
if os.path.exists(args.en_morphodita):
en_tagger = keywords.Morphodita(args.en_morphodita)
else:
print >> sys.stderr, "File with English Morphodita model does not exist: {}".format(args.en_morphodita)
exit(1)
if os.path.exists(args.en_idf):
f_idf = open(args.en_idf, 'rb')
en_idf_doc_count = float(pickle.load(f_idf))
en_idf_table = pickle.load(f_idf)
f_idf.close()
else:
print >> sys.stderr, "File with English IDF model does not exist: {}".format(args.en_idf)
exit(1)
app.run(debug=True, host=args.host, port=args.port)
|
lgpl-3.0
| 3,862,969,899,623,233,500
| 34.142857
| 126
| 0.603294
| false
| 3.533702
| false
| false
| false
|
Juanlu001/CBC.Solve
|
cbc/swing/fsinewton/solver/boundary_conditions.py
|
1
|
4016
|
"""Module containing implementation of monolithic FSI boundary conditions"""
__author__ = "Gabriel Balaban"
__copyright__ = "Copyright (C) 2010 Simula Research Laboratory and %s" % __author__
__license__ = "GNU GPL Version 3 or any later version"
from dolfin import *
class FSIBC(object):
"""
Boundary Conditions class for Monolithic FSI
Arguments
problem
object of type pfsi.FsiNewtonTest
spaces
object of type FSISpaces
"""
def __init__(self,problem,spaces):
self.problem = problem
self.spaces = spaces
#Time dependant BC are set on the intial guess and at each time step.
self.bcallU1_ini = self.create_all_dirichlet_conditions("Initial guess")
#Newton Increment BC are homogeneous
self.bcallI = self.create_all_dirichlet_conditions("Newton Step")
[bc.homogenize() for bc in self.bcallI]
def create_all_dirichlet_conditions(self, bcsetname = ""):
info_blue("\nCreating Dirichlet Boundary Conditions " + bcsetname)
return self.create_fluid_bc() + self.create_structure_bc() + \
self.create_mesh_bc()
def create_bc(self,space,boundaries,values,bcname):
#If Boundaries specified without values assume homogeneous
if boundaries is not None and (values == [] or values is None):
dim = space.num_sub_spaces()
#A Function Space returns dim 0 but really has dim 1.
if dim == 0:
dim = 1
zeros = tuple(["0.0" for i in range(dim)])
values = [zeros for i in range(len(boundaries))]
#Try to generate the BC
bcs = []
## try:
for boundary,value in zip(boundaries,values):
if boundary == 'GammaFSI':
fsibounds = self.problem.interiorboundarynums["FSI_bound"]
interiormeshfunc = self.problem.meshfunctions["interiorfacet"]
for fsibound in fsibounds:
print fsibound
bcs += [DirichletBC(space, value,interiormeshfunc,fsibound)]
else:
bcs += [DirichletBC(space, value, boundary)]
info("Created bc %s"%bcname)
## except:
## info("No Dirichlet bc created for %s"%bcname)
return bcs
def create_fluid_bc(self):
bcv = self.create_bc(self.spaces.V_F,self.problem.fluid_velocity_dirichlet_boundaries(),\
self.problem.fluid_velocity_dirichlet_values(),"Fluid Velocity")
bcp = self.create_fluid_pressure_bc()
return bcv + bcp
def create_fluid_pressure_bc(self):
return self.create_bc(self.spaces.Q_F,self.problem.fluid_pressure_dirichlet_boundaries(),\
self.problem.fluid_pressure_dirichlet_values(),"Fluid Pressure")
def create_structure_bc(self):
bcU = self.create_bc(self.spaces.C_S,self.problem.structure_dirichlet_boundaries(),\
self.problem.structure_dirichlet_values(),"Structure Displacement")
bcP = self.create_bc(self.spaces.V_S,self.problem.structure_velocity_dirichlet_boundaries(),\
self.problem.structure_velocity_dirichlet_values(),"Structure Velocity")
return bcU + bcP
def create_mesh_bc(self):
#If no Mesh BC specified assume domain boundary and fixed"
if self.problem.mesh_dirichlet_boundaries() is None:
#The value will be set to zero in self.create_bc
return self.create_bc(self.self.spaces.C_F,["on_boundary"],None,"Mesh Displacement")
#Allow the user to explicitly create no mesh bc whatsoever.
elif self.problem.mesh_dirichlet_boundaries() == "NoBC":
return []
else:
return self.create_bc(self.spaces.C_F,self.problem.mesh_dirichlet_boundaries(),\
self.problem.mesh_dirichlet_values(),"Mesh Displacement")
|
gpl-3.0
| -6,300,717,971,602,277,000
| 43.131868
| 101
| 0.608317
| false
| 3.960552
| false
| false
| false
|
timopulkkinen/BubbleFish
|
tools/telemetry/telemetry/core/chrome/win_platform_backend.py
|
1
|
3723
|
# Copyright (c) 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.
import ctypes
import subprocess
try:
import win32api # pylint: disable=F0401
import win32con # pylint: disable=F0401
import win32process # pylint: disable=F0401
except ImportError:
win32api = None
win32con = None
win32process = None
from telemetry.core.chrome import platform_backend
class WinPlatformBackend(platform_backend.PlatformBackend):
def _GetProcessHandle(self, pid):
mask = (win32con.PROCESS_QUERY_INFORMATION |
win32con.PROCESS_VM_READ)
return win32api.OpenProcess(mask, False, pid)
# pylint: disable=W0613
def StartRawDisplayFrameRateMeasurement(self):
raise NotImplementedError()
def StopRawDisplayFrameRateMeasurement(self):
raise NotImplementedError()
def GetRawDisplayFrameRateMeasurements(self):
raise NotImplementedError()
def IsThermallyThrottled(self):
raise NotImplementedError()
def HasBeenThermallyThrottled(self):
raise NotImplementedError()
def GetSystemCommitCharge(self):
class PerformanceInfo(ctypes.Structure):
"""Struct for GetPerformanceInfo() call
http://msdn.microsoft.com/en-us/library/ms683210
"""
_fields_ = [('size', ctypes.c_ulong),
('CommitTotal', ctypes.c_size_t),
('CommitLimit', ctypes.c_size_t),
('CommitPeak', ctypes.c_size_t),
('PhysicalTotal', ctypes.c_size_t),
('PhysicalAvailable', ctypes.c_size_t),
('SystemCache', ctypes.c_size_t),
('KernelTotal', ctypes.c_size_t),
('KernelPaged', ctypes.c_size_t),
('KernelNonpaged', ctypes.c_size_t),
('PageSize', ctypes.c_size_t),
('HandleCount', ctypes.c_ulong),
('ProcessCount', ctypes.c_ulong),
('ThreadCount', ctypes.c_ulong)]
def __init__(self):
self.size = ctypes.sizeof(self)
super(PerformanceInfo, self).__init__()
performance_info = PerformanceInfo()
ctypes.windll.psapi.GetPerformanceInfo(
ctypes.byref(performance_info), performance_info.size)
return performance_info.CommitTotal * performance_info.PageSize / 1024
def GetMemoryStats(self, pid):
memory_info = win32process.GetProcessMemoryInfo(
self._GetProcessHandle(pid))
return {'VM': memory_info['PagefileUsage'],
'VMPeak': memory_info['PeakPagefileUsage'],
'WorkingSetSize': memory_info['WorkingSetSize'],
'WorkingSetSizePeak': memory_info['PeakWorkingSetSize']}
def GetIOStats(self, pid):
io_stats = win32process.GetProcessIoCounters(
self._GetProcessHandle(pid))
return {'ReadOperationCount': io_stats['ReadOperationCount'],
'WriteOperationCount': io_stats['WriteOperationCount'],
'ReadTransferCount': io_stats['ReadTransferCount'],
'WriteTransferCount': io_stats['WriteTransferCount']}
def GetChildPids(self, pid):
"""Retunds a list of child pids of |pid|."""
child_pids = []
pid_ppid_list = subprocess.Popen(['wmic', 'process', 'get',
'ParentProcessId,ProcessId'],
stdout=subprocess.PIPE).communicate()[0]
for pid_ppid in pid_ppid_list.splitlines()[1:]: #skip header
if not pid_ppid:
continue
curr_ppid, curr_pid = pid_ppid.split()
if int(curr_ppid) == pid:
child_pids.append(int(curr_pid))
child_pids.extend(self.GetChildPids(int(curr_pid)))
return child_pids
|
bsd-3-clause
| 2,244,057,969,717,524,000
| 36.606061
| 77
| 0.640612
| false
| 3.964856
| false
| false
| false
|
Jajcus/pyxmpp2
|
pyxmpp2/mainloop/wait.py
|
1
|
2125
|
#
# (C) Copyright 2011 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# pylint: disable-msg=W0201
"""Utility functions to wait until a socket (or object implementing .fileno()
in POSIX) is ready for input or output."""
from __future__ import absolute_import, division
__docformat__ = "restructuredtext en"
import select
if hasattr(select, "poll"):
def wait_for_read(socket, timeout = None):
"""Wait up to `timeout` seconds until `socket` is ready for reading.
"""
if timeout is not None:
timeout *= 1000
poll = select.poll()
poll.register(socket, select.POLLIN)
events = poll.poll(timeout)
return bool(events)
def wait_for_write(socket, timeout = None):
"""Wait up to `timeout` seconds until `socket` is ready for writing.
"""
if timeout is not None:
timeout *= 1000
poll = select.poll()
poll.register(socket, select.POLLOUT)
events = poll.poll(timeout)
return bool(events)
else:
def wait_for_read(socket, timeout = None):
"""Wait up to `timeout` seconds until `socket` is ready for reading.
"""
readable = select.select([socket], [], [], timeout)[0]
return bool(readable)
def wait_for_write(socket, timeout = None):
"""Wait up to `timeout` seconds until `socket` is ready for writing.
"""
writable = select.select([], [socket], [], timeout)[1]
return bool(writable)
|
lgpl-2.1
| -7,421,785,645,248,673,000
| 35.637931
| 77
| 0.660235
| false
| 3.994361
| false
| false
| false
|
kamitchell/py2app
|
py2app/filters.py
|
1
|
1048
|
from pkg_resources import require
require("macholib")
import os
import sys
from macholib.util import has_filename_filter, in_system_path
def not_stdlib_filter(module, prefix=None):
"""
Return False if the module is located in the standard library
"""
if prefix is None:
prefix = sys.prefix
prefix = os.path.join(os.path.realpath(prefix), '')
rp = os.path.realpath(module.filename)
if rp.startswith(prefix):
rest = rp[len(prefix):]
if '/site-python/' in rest:
return True
elif '/site-packages/' in rest:
return True
else:
return False
return True
def not_system_filter(module):
"""
Return False if the module is located in a system directory
"""
return not in_system_path(module.filename)
def bundle_or_dylib_filter(module):
"""
Return False if the module does not have a filetype attribute
corresponding to a Mach-O bundle or dylib
"""
return getattr(module, 'filetype', None) in ('bundle', 'dylib')
|
mit
| 183,278,461,600,789,730
| 27.324324
| 67
| 0.645992
| false
| 3.969697
| false
| false
| false
|
tuukka/sonata-svn-test
|
sonata/plugins/test.py
|
1
|
2113
|
# this is the magic interpreted by Sonata, referring to on_enable etc. below:
### BEGIN PLUGIN INFO
# [plugin]
# plugin_format: 0, 0
# name: Test plugin
# version: 0, 0, 1
# description: A simple test plugin.
# author: Tuukka Hastrup
# author_email: Tuukka.Hastrup@iki.fi
# url: http://sonata.berlios.de
# license: GPL v3 or later
# [capabilities]
# enablables: on_enable
# tabs: construct_tab
# playing_song_observers: on_song_change
# lyrics_fetching: on_lyrics_fetch
### END PLUGIN INFO
# nothing magical from here on
import gobject, gtk, pango
from sonata.misc import escape_html
songlabel = None
lyricslabel = None
# this gets called when the plugin is loaded, enabled, or disabled:
def on_enable(state):
global songlabel, lyricslabel
if state:
songlabel = gtk.Label("No song info received yet.")
songlabel.props.ellipsize = pango.ELLIPSIZE_END
lyricslabel = gtk.Label("No lyrics requests yet.")
lyricslabel.props.ellipsize = pango.ELLIPSIZE_END
else:
songlabel = None
lyricslabel = None
# this constructs the parts of the tab when called:
def construct_tab():
vbox = gtk.VBox()
vbox.pack_start(gtk.Label("Hello world!"))
vbox.pack_start(songlabel)
vbox.pack_start(lyricslabel)
vbox.pack_start(gtk.Label("(You can modify me at %s)" %
__file__.rstrip("c")))
vbox.show_all()
# the return value goes off to Base.new_tab(page, stock, text, focus):
# (tab content, icon name, tab name, the widget to focus on tab switch)
return (vbox, None, "Test plugin", None)
# this gets called when a new song is playing:
def on_song_change(songinfo):
if songinfo:
songlabel.set_markup("<b>Info for currently playing song:</b>"+
"\n%s" % escape_html(repr(songinfo)))
else:
songlabel.set_text("Currently not playing any song.")
songlabel.show()
# this gets requests for lyrics:
def on_lyrics_fetch(callback, artist, title):
lyricslabel.set_markup(
"Got request for lyrics for artist %r title %r." %
(artist, title))
# callback(lyrics, error)
gobject.timeout_add(0, callback, None,
"%s doesn't have lyrics for %r." %
(__name__, (artist, title)))
|
gpl-3.0
| 4,461,166,768,552,095,000
| 27.554054
| 77
| 0.705632
| false
| 2.984463
| false
| false
| false
|
datacommonsorg/data
|
scripts/us_bjs/nps/preprocess_data.py
|
1
|
19122
|
import pandas as pd
from absl import flags
from absl import app
FLAGS = flags.FLAGS
flags.DEFINE_string('preprocess_file',
'NPS_1978-2018_Data.tsv',
'file path to tsv file with data to proess',
short_name='p')
def convert_nan_for_calculation(value):
if pd.isna(value):
return 0
else:
return value
def total_jurisdiction_columns_helper(df):
"""calculation to include private facility numbers"""
df["PVINF_Temp"] = df["PVINF"].apply(convert_nan_for_calculation)
df["PVOTHF_Temp"] = df["PVOTHF"].apply(convert_nan_for_calculation)
df["PVINM_Temp"] = df["PVINM"].apply(convert_nan_for_calculation)
df["PVOTHM_Temp"] = df["PVOTHM"].apply(convert_nan_for_calculation)
df["Female_Total_Temp"] = df[["JURTOTF", "PVINF_Temp", "PVOTHF_Temp"
]].sum(axis=1).where(df["PVINCLF"] == 2,
df["JURTOTF"])
df["Male_Total_Temp"] = df[["JURTOTM", "PVINM_Temp", "PVOTHM_Temp"
]].sum(axis=1).where(df["PVINCLM"] == 2,
df["JURTOTM"])
"""calculation to include local facility numbers"""
df["LFF_Temp"] = df["LFF"].apply(convert_nan_for_calculation)
df["LFM_Temp"] = df["LFM"].apply(convert_nan_for_calculation)
df["Female_Total_Temp"] = df[["Female_Total_Temp", "LFF_Temp"
]].sum(axis=1).where(df["LFINCLF"] == 2,
df["Female_Total_Temp"])
df["Male_Total_Temp"] = df[["Male_Total_Temp", "LFM_Temp"
]].sum(axis=1).where(df["LFINCLM"] == 2,
df["Male_Total_Temp"])
"""calculation to include numbers from local facilities solely to ease crowding"""
df["LFCRSTF_Temp"] = df["LFCRSTF"].apply(convert_nan_for_calculation)
df["LFCRSTM_Temp"] = df["LFCRSTM"].apply(convert_nan_for_calculation)
df["Female_Total_Temp"] = df[["Female_Total_Temp", "LFCRSTF_Temp"
]].sum(axis=1).where(df["LFCRINCF"] == 2,
df["Female_Total_Temp"])
df["Male_Total_Temp"] = df[["Male_Total_Temp", "LFCRSTM_Temp"
]].sum(axis=1).where(df["LFCRINCM"] == 2,
df["Male_Total_Temp"])
"""calculation to include federal and other state facility numbers"""
df["FEDF_Temp"] = df["FEDF"].apply(convert_nan_for_calculation)
df["OTHSTF_Temp"] = df["OTHSTF"].apply(convert_nan_for_calculation)
df["FEDM_Temp"] = df["FEDM"].apply(convert_nan_for_calculation)
df["OTHSTM_Temp"] = df["OTHSTM"].apply(convert_nan_for_calculation)
df["Female_Total_Temp"] = df[[
"Female_Total_Temp", "FEDF_Temp", "OTHSTF_Temp"
]].sum(axis=1).where(df["FACINCLF"] == 2, df["Female_Total_Temp"])
df["Male_Total_Temp"] = df[["Male_Total_Temp", "FEDM_Temp", "OTHSTM_Temp"
]].sum(axis=1).where(df["FACINCLM"] == 2,
df["Male_Total_Temp"])
def get_columns(df):
df_out = {}
total_jurisdiction_columns_helper(df)
df_out["GeoId"] = df["GeoId"]
df_out["YEAR"] = df["YEAR"]
df_out["Count_Person_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"Female_Total_Temp"]
df_out[
"Count_Person_Female_Incarcerated_WhiteAlone_MeasuredBasedOnJurisdiction"] = df[
"WHITEF"]
df_out[
"Count_Person_BlackOrAfricanAmericanAlone_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"BLACKF"]
df_out[
"Count_Person_Female_HispanicOrLatino_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"HISPF"]
df_out[
"Count_Person_AmericanIndianOrAlaskaNativeAlone_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"AIANF"]
df_out[
"Count_Person_AsianAlone_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"ASIANF"]
df_out[
"Count_Person_Female_Incarcerated_NativeHawaiianOrOtherPacificIslanderAlone_MeasuredBasedOnJurisdiction"] = df[
"NHPIF"]
df_out[
"Count_Person_Female_Incarcerated_TwoOrMoreRaces_MeasuredBasedOnJurisdiction"] = df[
"TWORACEF"]
df_out[
"Count_MortalityEvent_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHTOTF"]
df_out[
"Count_MortalityEvent_Female_Incarcerated_JudicialExecution_MeasuredBasedOnJurisdiction"] = df[
"DTHEXECF"]
df_out[
"Count_MortalityEvent_Female_IllnessOrNaturalCause_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHILLNF"]
df_out[
"Count_MortalityEvent_AIDS_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHAIDSF"]
df_out[
"Count_MortalityEvent_Female_Incarcerated_IntentionalSelf-Harm(Suicide)_MeasuredBasedOnJurisdiction"] = df[
"DTHSUICF"]
df_out[
"Count_MortalityEvent_Accidents(UnintentionalInjuries)_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHACCF"]
df_out[
"Count_MortalityEvent_DeathDueToAnotherPerson_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHPERSF"]
df_out[
"Count_MortalityEvent_Assault(Homicide)_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHHOMIF"]
df_out[
"Count_MortalityEvent_Female_Incarcerated_NPSOtherCauseOfDeath_MeasuredBasedOnJurisdiction"] = df[
"DTHOTHF"]
df_out[
"Count_IncarcerationEvent_AdmittedToPrison_Female_Incarcerated_MaxSentenceGreaterThan1Year_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"ADTOTF"]
df_out[
"Count_IncarcerationEvent_Female_Incarcerated_MaxSentenceGreaterThan1Year_ReleasedFromPrison_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"RLTOTF"]
df_out[
"Count_Person_Female_Incarcerated_MaxSentenceGreaterThan1Year_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"JURGT1F"]
df_out[
"Count_Person_Female_Incarcerated_MaxSentence1YearOrLess_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"JURLT1F"]
df_out[
"Count_Person_Female_Incarcerated_Unsentenced_MeasuredBasedOnJurisdiction"] = df[
"JURUNSF"]
df_out[
"Count_Person_Female_Incarcerated_InState_PrivatelyOperated_MeasuredBasedOnJurisdiction"] = df[
"PVINF"]
df_out[
"Count_Person_Female_Incarcerated_OutOfState_PrivatelyOperated_MeasuredBasedOnJurisdiction"] = df[
"PVOTHF"]
df_out[
"Count_Person_Female_Incarcerated_Local_LocallyOperated_MeasuredBasedOnJurisdiction"] = df[
"LFF"]
df_out[
"Count_Person_FederallyOperated_Female_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"FEDF"]
df_out[
"Count_Person_Female_Incarcerated_OutOfState_StateOperated_MeasuredBasedOnJurisdiction"] = df[
"OTHSTF"]
df_out[
"Count_Person_Female_Incarcerated_NotAUSCitizen_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZTOTF"]
df_out[
"Count_Person_Female_Incarcerated_MaxSentenceGreaterThan1Year_NotAUSCitizen_Sentenced_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZGT1F"]
df_out[
"Count_Person_Female_Incarcerated_MaxSentence1YearOrLess_NotAUSCitizen_Sentenced_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZLE1F"]
df_out[
"Count_Person_Female_Incarcerated_NotAUSCitizen_StateOperated&FederallyOperated&PrivatelyOperated_Unsentenced_MeasuredBasedOnCustody"] = df[
"NCITZUNSF"]
df_out[
"Count_Person_Female_Incarcerated_Under18_MeasuredBasedOnCustody"] = df[
"CUSLT18F"]
df_out["Count_Person_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"Male_Total_Temp"]
df_out[
"Count_Person_Incarcerated_Male_WhiteAlone_MeasuredBasedOnJurisdiction"] = df[
"WHITEM"]
df_out[
"Count_Person_BlackOrAfricanAmericanAlone_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"BLACKM"]
df_out[
"Count_Person_HispanicOrLatino_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"HISPM"]
df_out[
"Count_Person_AmericanIndianOrAlaskaNativeAlone_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"AIANM"]
df_out[
"Count_Person_AsianAlone_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"ASIANM"]
df_out[
"Count_Person_Incarcerated_Male_NativeHawaiianOrOtherPacificIslanderAlone_MeasuredBasedOnJurisdiction"] = df[
"NHPIM"]
df_out[
"Count_Person_Incarcerated_Male_TwoOrMoreRaces_MeasuredBasedOnJurisdiction"] = df[
"TWORACEM"]
df_out[
"Count_MortalityEvent_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHTOTM"]
df_out[
"Count_MortalityEvent_Incarcerated_JudicialExecution_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHEXECM"]
df_out[
"Count_MortalityEvent_IllnessOrNaturalCause_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHILLNM"]
df_out[
"Count_MortalityEvent_AIDS_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHAIDSM"]
df_out[
"Count_MortalityEvent_Incarcerated_IntentionalSelf-Harm(Suicide)_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHSUICM"]
df_out[
"Count_MortalityEvent_Accidents(UnintentionalInjuries)_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHACCM"]
df_out[
"Count_MortalityEvent_DeathDueToAnotherPerson_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHPERSM"]
df_out[
"Count_MortalityEvent_Assault(Homicide)_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"DTHHOMIM"]
df_out[
"Count_MortalityEvent_Incarcerated_Male_NPSOtherCauseOfDeath_MeasuredBasedOnJurisdiction"] = df[
"DTHOTHM"]
df_out[
"Count_IncarcerationEvent_AdmittedToPrison_Incarcerated_Male_MaxSentenceGreaterThan1Year_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"ADTOTM"]
df_out[
"Count_IncarcerationEvent_Incarcerated_Male_MaxSentenceGreaterThan1Year_ReleasedFromPrison_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"RLTOTM"]
df_out[
"Count_Person_Incarcerated_Male_MaxSentenceGreaterThan1Year_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"JURGT1M"]
df_out[
"Count_Person_Incarcerated_Male_MaxSentence1YearOrLess_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"JURLT1M"]
df_out[
"Count_Person_Incarcerated_Male_Unsentenced_MeasuredBasedOnJurisdiction"] = df[
"JURUNSM"]
df_out[
"Count_Person_Incarcerated_InState_Male_PrivatelyOperated_MeasuredBasedOnJurisdiction"] = df[
"PVINM"]
df_out[
"Count_Person_Incarcerated_Male_OutOfState_PrivatelyOperated_MeasuredBasedOnJurisdiction"] = df[
"PVOTHM"]
df_out[
"Count_Person_Incarcerated_Local_LocallyOperated_Male_MeasuredBasedOnJurisdiction"] = df[
"LFM"]
df_out[
"Count_Person_FederallyOperated_Incarcerated_Male_MeasuredBasedOnJurisdiction"] = df[
"FEDM"]
df_out[
"Count_Person_Incarcerated_Male_OutOfState_StateOperated_MeasuredBasedOnJurisdiction"] = df[
"OTHSTM"]
df_out[
"Count_Person_Incarcerated_Male_NotAUSCitizen_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZTOTM"]
df_out[
"Count_Person_Incarcerated_Male_MaxSentenceGreaterThan1Year_NotAUSCitizen_Sentenced_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZGT1M"]
df_out[
"Count_Person_Incarcerated_Male_MaxSentence1YearOrLess_NotAUSCitizen_Sentenced_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZLE1M"]
df_out[
"Count_Person_Incarcerated_Male_NotAUSCitizen_StateOperated&FederallyOperated&PrivatelyOperated_Unsentenced_MeasuredBasedOnCustody"] = df[
"NCITZUNSM"]
df_out[
"Count_Person_Incarcerated_Male_Under18_MeasuredBasedOnCustody"] = df[
"CUSLT18M"]
df_out["Count_Person_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"Female_Total_Temp"] + df["Male_Total_Temp"]
df_out[
"Count_Person_Incarcerated_WhiteAlone_MeasuredBasedOnJurisdiction"] = df[
"WHITEF"] + df["WHITEM"]
df_out[
"Count_Person_BlackOrAfricanAmericanAlone_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"BLACKF"] + df["BLACKM"]
df_out[
"Count_Person_HispanicOrLatino_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"HISPF"] + df["HISPM"]
df_out[
"Count_Person_AmericanIndianOrAlaskaNativeAlone_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"AIANF"] + df["AIANM"]
df_out[
"Count_Person_AsianAlone_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"ASIANF"] + df["ASIANM"]
df_out[
"Count_Person_Incarcerated_NativeHawaiianOrOtherPacificIslanderAlone_MeasuredBasedOnJurisdiction"] = df[
"NHPIF"] + df["NHPIM"]
df_out[
"Count_Person_Incarcerated_TwoOrMoreRaces_MeasuredBasedOnJurisdiction"] = df[
"TWORACEF"] + df["TWORACEM"]
df_out[
"Count_MortalityEvent_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHTOTF"] + df["DTHTOTM"]
df_out[
"Count_MortalityEvent_Incarcerated_JudicialExecution_MeasuredBasedOnJurisdiction"] = df[
"DTHEXECF"] + df["DTHEXECM"]
df_out[
"Count_MortalityEvent_IllnessOrNaturalCause_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHILLNF"] + df["DTHILLNM"]
df_out[
"Count_MortalityEvent_AIDS_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHAIDSF"] + df["DTHAIDSM"]
df_out[
"Count_MortalityEvent_Incarcerated_IntentionalSelf-Harm(Suicide)_MeasuredBasedOnJurisdiction"] = df[
"DTHSUICF"] + df["DTHSUICM"]
df_out[
"Count_MortalityEvent_Accidents(UnintentionalInjuries)_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHACCF"] + df["DTHACCM"]
df_out[
"Count_MortalityEvent_DeathDueToAnotherPerson_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHPERSF"] + df["DTHPERSM"]
df_out[
"Count_MortalityEvent_Assault(Homicide)_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"DTHHOMIF"] + df["DTHHOMIM"]
df_out[
"Count_MortalityEvent_Incarcerated_NPSOtherCauseOfDeath_MeasuredBasedOnJurisdiction"] = df[
"DTHOTHF"] + df["DTHOTHM"]
df_out[
"Count_IncarcerationEvent_AdmittedToPrison_Incarcerated_MaxSentenceGreaterThan1Year_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"ADTOTF"] + df["ADTOTM"]
df_out[
"Count_IncarcerationEvent_Incarcerated_MaxSentenceGreaterThan1Year_ReleasedFromPrison_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"RLTOTF"] + df["RLTOTM"]
df_out[
"Count_Person_Incarcerated_MaxSentenceGreaterThan1Year_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"JURGT1F"] + df["JURGT1M"]
df_out[
"Count_Person_Incarcerated_MaxSentence1YearOrLess_Sentenced_MeasuredBasedOnJurisdiction"] = df[
"JURLT1F"] + df["JURLT1M"]
df_out[
"Count_Person_Incarcerated_Unsentenced_MeasuredBasedOnJurisdiction"] = df[
"JURUNSF"] + df["JURUNSM"]
df_out[
"Count_Person_Incarcerated_InState_PrivatelyOperated_MeasuredBasedOnJurisdiction"] = df[
"PVINF"] + df["PVINM"]
df_out[
"Count_Person_Incarcerated_OutOfState_PrivatelyOperated_MeasuredBasedOnJurisdiction"] = df[
"PVOTHF"] + df["PVOTHM"]
df_out[
"Count_Person_Incarcerated_Local_LocallyOperated_MeasuredBasedOnJurisdiction"] = df[
"LFF"] + df["LFM"]
df_out[
"Count_Person_FederallyOperated_Incarcerated_MeasuredBasedOnJurisdiction"] = df[
"FEDF"] + df["FEDM"]
df_out[
"Count_Person_Incarcerated_OutOfState_StateOperated_MeasuredBasedOnJurisdiction"] = df[
"OTHSTF"] + df["OTHSTM"]
df_out[
"Count_Person_Incarcerated_NotAUSCitizen_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZTOTF"] + df["NCITZTOTM"]
df_out[
"Count_Person_Incarcerated_MaxSentenceGreaterThan1Year_NotAUSCitizen_Sentenced_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZGT1F"] + df["NCITZGT1M"]
df_out[
"Count_Person_Incarcerated_MaxSentence1YearOrLess_NotAUSCitizen_Sentenced_StateOperated&FederallyOperated&PrivatelyOperated_MeasuredBasedOnCustody"] = df[
"NCITZLE1F"] + df["NCITZLE1M"]
df_out[
"Count_Person_Incarcerated_NotAUSCitizen_StateOperated&FederallyOperated&PrivatelyOperated_Unsentenced_MeasuredBasedOnCustody"] = df[
"NCITZUNSF"] + df["NCITZUNSM"]
df_out["Count_Person_Incarcerated_Under18_MeasuredBasedOnCustody"] = df[
"CUSLT18F"] + df["CUSLT18M"]
return df_out
def convert_geoId(fips_code):
"""Creates geoId column"""
return 'geoId/' + str(fips_code).zfill(2)
def convert_missing_value_to_nan(value):
"""codes for missing values are always negative and actual data is always >= 0"""
if isinstance(value, int) and value < 0:
return float("nan")
else:
return value
def convert_nan_to_empty_cell(value):
if pd.isna(value):
return ''
else:
return value
def preprocess_df(raw_df):
"""cleans raw_df
Args:
raw_data: raw data frame to be used as starting point for cleaning
"""
df = raw_df.copy()
df['GeoId'] = df['STATEID'].apply(convert_geoId)
# convert missing values to NaN for aggregation
for column_name in list(df.columns):
df[column_name] = df[column_name].apply(convert_missing_value_to_nan)
#get columns matching stat var names and add aggregate columns
df_out = pd.DataFrame(get_columns(df))
#convert NaN to empty cell
for column_name in list(df_out.columns):
df_out[column_name] = df_out[column_name].apply(
convert_nan_to_empty_cell)
return df_out
def main(args):
filename = FLAGS.preprocess_file
print('Processing {0}'.format(filename))
df = pd.read_csv(filename, delimiter='\t')
processed_df = preprocess_df(df)
processed_df.to_csv(filename.replace('.tsv', '_processed.csv'), index=False)
print('Done processing {0}'.format(filename))
if __name__ == '__main__':
app.run(main)
|
apache-2.0
| 8,942,910,421,515,007,000
| 45.867647
| 174
| 0.653488
| false
| 2.993425
| false
| false
| false
|
scotwk/cloud-custodian
|
tools/zerodark/zerodark/ipdb.py
|
1
|
24394
|
# Copyright 2017-2018 Capital One Services, 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, 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.
__author__ = "Kapil Thangavelu <kapil.foss@gmail.com>"
import boto3
import click
from c7n.credentials import SessionFactory
from c7n.sqsexec import MessageIterator
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from datetime import timedelta
from dateutil.parser import parse as date_parse
import gzip
import json
import logging
import multiprocessing
import os
import sqlite3
import time
import yaml
from .constants import RESOURCE_KEY, REGION_KEY
from .metrics import Resource
from .utils import human_size, unwrap, get_dates
log = logging.getLogger('zerodark.ipdb')
APP_TAG = os.environ.get('APP_TAG', 'app')
ENV_TAG = os.environ.get('ENV_TAG', 'env')
CONTACT_TAG = os.environ.get('CONTACT_TAG', 'contact')
def download_config(
client, bucket, prefix, account_id, region, day, store, rtypes=()):
config_prefix = "%sAWSLogs/%s/Config/%s/%s/ConfigHistory/" % (
prefix,
account_id,
region,
day.strftime('%Y/%-m/%-d'))
results = client.list_objects_v2(
Bucket=bucket,
Prefix=config_prefix)
if not os.path.exists(store):
os.makedirs(store)
files = []
downloads = Counter()
for k in results.get('Contents', ()):
found = False
for rt in rtypes:
if rt in k['Key']:
found = True
if not found:
continue
fname = k['Key'].rsplit('/', 1)[-1]
fpath = os.path.join(store, fname)
files.append(fpath)
if os.path.exists(fpath):
downloads['Cached'] += 1
downloads['CacheSize'] += k['Size']
continue
downloads['Downloads'] += 1
downloads['DownloadSize'] += k['Size']
client.download_file(bucket, k['Key'], fpath)
log.debug(
"Downloaded:%d Size:%d Cached:%d Size:%s Prefix:%s",
downloads['Downloads'],
downloads['DownloadSize'],
downloads['Cached'],
downloads['CacheSize'],
config_prefix)
return files, downloads
def process_account_resources(
account_id, bucket, prefix, region,
store, start, end, resource='NetworkInterface'):
client = boto3.client('s3')
files = []
t = time.time()
period_stats = Counter()
period = (end - start).days
resource = RESOURCE_MAPPING[resource]
for i in range(period):
day = start + timedelta(i)
d_files, stats = download_config(
client, bucket, prefix, account_id, region, day, store,
rtypes=(resource,))
files.extend(d_files)
period_stats.update(stats)
period_stats['FetchTime'] = int(time.time() - t)
return files, period_stats
def resource_info(eni_cfg):
desc = eni_cfg.get('description')
instance_id = eni_cfg['attachment'].get('instanceId', '')
if instance_id:
rtype = RESOURCE_KEY['ec2']
rid = instance_id
elif desc.startswith('ELB app/'):
rtype = RESOURCE_KEY["alb"]
rid = desc.split('/')[1]
elif desc.startswith('ELB net/'):
rtype = RESOURCE_KEY["nlb"]
rid = desc.split('/')[1]
elif desc.startswith('ELB '):
rtype = RESOURCE_KEY['elb']
rid = desc.split(' ', 1)[1]
elif desc.startswith('AWS ElasticMapReduce'):
rtype = RESOURCE_KEY['emr']
rid = desc.rsplit(' ', 1)[1]
elif desc.startswith('AWS created network interface for directory'):
rtype = RESOURCE_KEY['dir']
rid = desc.rsplit(' ', 1)[1]
elif desc.startswith('AWS Lambda VPC ENI:'):
rtype = RESOURCE_KEY['lambda']
rid = eni_cfg['requesterId'].split(':', 1)[1]
elif desc == 'RDSNetworkInterface':
rtype = RESOURCE_KEY['rds']
rid = ''
elif desc == 'RedshiftNetworkInterface':
rtype = RESOURCE_KEY['redshift']
rid = ''
elif desc.startswith('ElastiCache '):
rtype = RESOURCE_KEY['elasticache']
rid = desc.split(' ', 1)[1]
elif desc.startswith('ElastiCache+'):
rtype = RESOURCE_KEY['elasticache']
rid = desc.split('+', 1)[1]
elif desc.startswith('Interface for NAT Gateway '):
rtype = RESOURCE_KEY['nat']
rid = desc.rsplit(' ', 1)[1]
elif desc.startswith('EFS mount target'):
rtype = RESOURCE_KEY['efs-mount']
fsid, fsmd = desc.rsplit(' ', 2)[1:]
rid = "%s:%s" % (fsid, fsmd[1:-1])
elif desc.startswith('CloudHSM Managed Interface'):
rtype = RESOURCE_KEY['hsm']
rid = ''
elif desc.startswith('CloudHsm ENI '):
rtype = RESOURCE_KEY['hsmv2']
rid = desc.rsplit(' ', 1)[1]
elif desc == 'DMSNetworkInterface':
rtype = RESOURCE_KEY['dms']
rid = ''
elif desc.startswith('DAX '):
rtype = RESOURCE_KEY['dax']
rid = desc.rsplit(' ', 1)[1]
elif desc.startswith('arn:aws:ecs:'):
# a running task with attached net
# 'arn:aws:ecs:us-east-1:0111111111110:attachment/37a927f2-a8d1-46d7-8f96-d6aef13cc5b0'
# also has public ip.
rtype = RESOURCE_KEY['ecs']
rid = desc.rsplit('/', 1)[1]
elif desc.startswith('VPC Endpoint Interface'):
# instanceOwnerId: amazon-aws
# interfaceType: 'vpc_endpoint'
rtype = RESOURCE_KEY['vpce']
rid = desc.rsplit(' ', 1)[1]
elif eni_cfg['attachment']['instanceOwnerId'] == 'aws-lambda':
rtype = RESOURCE_KEY['lambda']
rid = eni_cfg['requesterId'].split(':', 1)[1]
else:
rtype = RESOURCE_KEY['unknown']
rid = json.dumps(eni_cfg)
return rtype, rid
def resource_config_iter(files, batch_size=10000):
for f in files:
with gzip.open(f) as fh:
data = json.load(fh)
for config_set in chunks(data['configurationItems'], batch_size):
yield config_set
def record_stream_filter(record_stream, record_filter, batch_size=5000):
batch = []
for record_set in record_stream:
for r in record_set:
if record_filter(r):
batch.append(r)
if len(batch) % batch_size == 0:
yield batch
batch = []
if batch:
yield batch
EBS_SCHEMA = """
create table if not exists ebs (
volume_id text primary key,
instance_id text,
account_id text,
region text,
app text,
env text,
contact text,
start text,
end text
)
"""
def index_ebs_files(db, record_stream):
stats = Counter()
t = time.time()
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
cursor.execute(EBS_SCHEMA)
rows = []
deletes = {}
skipped = 0
for record_set in record_stream:
for cfg in record_set:
stats['Records'] += 1
stats['Record%s' % cfg['configurationItemStatus']] += 1
if cfg['configurationItemStatus'] in ('ResourceDeleted',):
deletes[cfg['resourceId']] = cfg['configurationItemCaptureTime']
continue
if not cfg['configuration'].get('attachments'):
skipped += 1
continue
rows.append((
cfg['resourceId'],
cfg['configuration']['attachments'][0]['instanceId'],
cfg['awsAccountId'],
cfg['awsRegion'],
cfg['tags'].get(APP_TAG),
cfg['tags'].get(ENV_TAG),
cfg['tags'].get(CONTACT_TAG),
cfg['resourceCreationTime'],
None))
if rows:
for idx, r in enumerate(rows):
if r[0] in deletes:
rows[idx] = list(r)
rows[idx][-1] = deletes[r[0]]
cursor.executemany(
'''insert or replace into ebs values (?, ?, ?, ?, ?, ?, ?, ?, ?)''', rows)
stats['RowCount'] += len(rows)
log.debug("ebs stored:%d", len(rows))
stats['RowCount'] += len(rows)
stats['IndexTime'] = int(time.time() - t)
return stats
EC2_SCHEMA = """
create table if not exists ec2 (
instance_id text primary key,
account_id text,
region text,
ip_address text,
app text,
env text,
contact text,
asg text,
start datetime,
end datetime
"""
def index_ec2_files(db, record_stream):
stats = Counter()
t = time.time()
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
cursor.execute(EC2_SCHEMA)
rows = []
deletes = []
for record_set in record_stream:
for cfg in record_set:
stats['Records'] += 1
stats['Record%s' % cfg['configurationItemStatus']] += 1
if cfg['configurationItemStatus'] in ('ResourceDeleted',):
deletes.append(((
cfg['configurationItemCaptureTime'], cfg['resourceId'])))
continue
if not cfg.get('tags'):
continue
rows.append((
cfg['resourceId'],
cfg['awsAccountId'],
cfg['awsRegion'],
cfg['configuration'].get('privateIpAddress', ''),
cfg['tags'].get(APP_TAG),
cfg['tags'].get(ENV_TAG),
cfg['tags'].get(CONTACT_TAG),
cfg['tags'].get('aws:autoscaling:groupName', ''),
cfg['resourceCreationTime'],
None))
if len(rows) % 1000 == 0:
stats['RowCount'] += len(rows)
cursor.executemany(
'''insert or replace into ec2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
rows)
rows = []
if deletes:
log.info("Delete count %d", len(deletes))
stmt = 'update ec2 set end = ? where instance_id = ?'
for p in deletes:
cursor.execute(stmt, p)
if rows:
cursor.executemany(
'''insert or replace into ec2 values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''', rows)
log.debug("ec2s stored:%d", len(rows))
stats['RowCount'] += len(rows)
stats['IndexTime'] = int(time.time() - t)
return stats
S3_SCHEMA = """
create table if not exists buckets (
name text,
account_id text,
region text,
app text,
env text,
contact text,
start datetime,
end datetime,
resource text
)"""
def index_s3_files(db, record_stream):
stats = Counter()
t = time.time()
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
cursor.execute(S3_SCHEMA)
deletes = {}
rows = []
for record_set in record_stream:
for cfg in record_set:
stats['Records'] += 1
stats['Record%s' % cfg['configurationItemStatus']] += 1
if cfg['configurationItemStatus'] == 'ResourceNotRecorded':
continue
if cfg['configurationItemStatus'] in ('ResourceDeleted'):
deletes[cfg['resourceId']] = cfg['configurationItemCaptureTime']
rows.append((
cfg['resourceId'], None, None, None, None, None, None,
cfg['configurationItemCaptureTime'], None))
continue
rows.append((
cfg['resourceId'],
cfg['awsAccountId'],
cfg['awsRegion'],
cfg['tags'].get(APP_TAG),
cfg['tags'].get(ENV_TAG),
cfg['tags'].get(CONTACT_TAG),
cfg['resourceCreationTime'],
None,
json.dumps(cfg)))
if len(rows) % 10000:
cursor.executemany(
'''insert or replace into buckets values (?, ?, ?, ?, ?, ?, ?, ?, ?)''', rows)
stats['RowCount'] += len(rows)
if rows:
cursor.executemany(
'''insert or replace into buckets values (?, ?, ?, ?, ?, ?, ?, ?, ?)''', rows)
stats['RowCount'] += len(rows)
stats['IndexTime'] = int(time.time() - t)
return stats
ELB_SCHEMA = """
create table if not exists elbs (
name text primary key,
account_id text,
region text,
app text,
env text,
contact text,
start datetime,
end datetime
)"""
def index_elb_files(db, record_stream):
stats = Counter()
t = time.time()
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
cursor.execute(ELB_SCHEMA)
rows = []
deletes = {}
for record_set in record_stream:
for cfg in record_set:
stats['Records'] += 1
stats['Record%s' % cfg['configurationItemStatus']] += 1
if cfg['configurationItemStatus'] in ('ResourceDeleted',):
deletes[cfg['resourceId']] = cfg['configurationItemCaptureTime']
continue
rows.append((
cfg['resourceName'],
cfg['awsAccountId'],
cfg['awsRegion'],
cfg['tags'].get(APP_TAG),
cfg['tags'].get(ENV_TAG),
cfg['tags'].get(CONTACT_TAG),
cfg['resourceCreationTime'],
None))
if rows:
for idx, r in enumerate(rows):
if r[0] in deletes:
rows[idx] = list(r)
rows[idx][-1] = deletes[r[0]]
cursor.executemany(
'''insert or replace into elbs values (?, ?, ?, ?, ?, ?, ?, ?)''', rows)
stats['RowCount'] += len(rows)
log.debug("elbs stored:%d", len(rows))
stats['RowCount'] += len(rows)
stats['IndexTime'] = int(time.time() - t)
return stats
ENI_SCHEMA = """
create table if not exists enis (
eni_id text primary key,
ip_address text,
account_id text,
resource_id text,
resource_type integer,
subnet_id text,
region integer,
start datetime,
end datetime
)"""
def index_eni_files(db, record_stream):
stats = Counter()
t = time.time()
with sqlite3.connect(db) as conn:
cursor = conn.cursor()
cursor.execute(ENI_SCHEMA)
cursor.execute('create index if not exists eni_idx on enis(ip_address)')
rows = []
skipped = 0
deletes = {}
rids = set()
for record_set in record_stream:
for cfg in record_set:
stats['Records'] += 1
stats['Record%s' % cfg['configurationItemStatus']] += 1
if cfg['configurationItemStatus'] not in (
'ResourceDeleted', 'ResourceDiscovered', 'OK'):
raise ValueError(cfg)
if cfg['configurationItemStatus'] in ('ResourceDeleted',):
deletes[cfg['resourceId']] = cfg['configurationItemCaptureTime']
continue
eni = cfg['configuration']
if 'attachment' not in eni or cfg['resourceId'] in rids:
skipped += 1
continue
rids.add(cfg['resourceId'])
rtype, rid = resource_info(eni)
rows.append((
eni['networkInterfaceId'],
eni['privateIpAddress'],
cfg['awsAccountId'],
rid,
rtype,
eni['subnetId'],
REGION_KEY[cfg['awsRegion']],
eni['attachment'].get('attachTime') or cfg['configurationItemCaptureTime'],
None))
log.debug(
"Records:%d Insert:%d Deletes:%d Skipped:%d Discovered:%d Deleted:%d Ok:%d",
stats['Records'], len(rows), len(deletes), skipped,
stats['RecordResourceDiscovered'], stats['RecordResourceDeleted'],
stats['RecordOK'])
if rows:
for idx, r in enumerate(rows):
if r[0] in deletes:
rows[idx] = list(r)
rows[idx][-1] = deletes[r[0]]
del deletes[r[0]]
try:
cursor.executemany(
'''insert into enis values (?, ?, ?, ?, ?, ?, ?, ?, ?)''', rows)
except Exception:
log.error("Error inserting enis account:%s rows:%d",
cfg['awsAccountId'], len(rows))
stats['RowCount'] += len(rows)
# result = cursor.execute('select count(distinct ip_address) from enis').fetchone()
stats['SkipCount'] = skipped
stats['IndexTime'] = int(time.time() - t)
return stats
def chunks(iterable, size=50):
"""Break an iterable into lists of size"""
batch = []
for n in iterable:
batch.append(n)
if len(batch) % size == 0:
yield batch
batch = []
if batch:
yield batch
RESOURCE_MAPPING = {
'Instance': 'AWS::EC2::Instance',
'LoadBalancer': 'AWS::ElasticLoadBalancing',
'NetworkInterface': 'AWS::EC2::NetworkInterface',
'Volume': 'AWS::EC2::Volume',
'Bucket': 'AWS::S3::Bucket'
}
RESOURCE_FILE_INDEXERS = {
'Instance': index_ec2_files,
'NetworkInterface': index_eni_files,
'LoadBalancer': index_elb_files,
'Volume': index_ebs_files,
'Bucket': index_s3_files
}
@click.group()
def cli():
"""AWS Network Resource Database"""
@cli.command('worker')
@click.option('--queue')
@click.option('--s3-key')
@click.option('--period', default=60, type=click.INT)
@click.option('--verbose', default=False, is_flag=True)
def worker_config(queue, s3_key, period, verbose):
"""daemon queue worker for config notifications"""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('s3transfer').setLevel(logging.WARNING)
queue, region = get_queue(queue)
factory = SessionFactory(region)
session = factory()
client = session.client('sqs')
messages = MessageIterator(client, queue, timeout=20)
for m in messages:
msg = unwrap(m)
if 'configurationItemSummary' in msg:
rtype = msg['configurationItemSummary']['resourceType']
else:
rtype = msg['configurationItem']['resourceType']
if rtype not in RESOURCE_MAPPING.values():
log.info("skipping %s" % rtype)
messages.ack(m)
log.info("message received %s", m)
def get_queue(queue):
if queue.startswith('https://queue.amazonaws.com'):
region = 'us-east-1'
queue_url = queue
elif queue.startswith('https://sqs.'):
region = queue.split('.', 2)[1]
queue_url = queue
elif queue.startswith('arn:sqs'):
queue_arn_split = queue.split(':', 5)
region = queue_arn_split[3]
owner_id = queue_arn_split[4]
queue_name = queue_arn_split[5]
queue_url = "https://sqs.%s.amazonaws.com/%s/%s" % (
region, owner_id, queue_name)
return queue_url, region
@cli.command('list-app-resources')
@click.option('--app')
@click.option('--env')
@click.option('--cmdb')
@click.option('--start')
@click.option('--end')
@click.option('--tz')
@click.option(
'-r', '--resources', multiple=True,
type=click.Choice(['Instance', 'LoadBalancer', 'Volume']))
def list_app_resources(
app, env, resources, cmdb, start, end, tz):
"""Analyze flow log records for application and generate metrics per period"""
logging.basicConfig(level=logging.INFO)
start, end = get_dates(start, end, tz)
all_resources = []
for rtype_name in resources:
rtype = Resource.get_type(rtype_name)
resources = rtype.get_resources(cmdb, start, end, app, env)
all_resources.extend(resources)
print(json.dumps(all_resources, indent=2))
@cli.command('load-resources')
@click.option('--bucket', required=True, help="Config Bucket")
@click.option('--prefix', required=True, help="Config Bucket Prefix")
@click.option('--region', required=True, help="Load Config for Region")
@click.option('--account-config', type=click.File('rb'), required=True)
@click.option('-a', '--accounts', multiple=True)
@click.option('--assume', help="Assume role")
@click.option('--start')
@click.option('--end')
@click.option('-r', '--resources', multiple=True,
type=click.Choice(list(RESOURCE_FILE_INDEXERS.keys())))
@click.option('--store', type=click.Path())
@click.option('-f', '--db')
@click.option('-v', '--verbose', is_flag=True)
@click.option('--debug', is_flag=True)
def load_resources(bucket, prefix, region, account_config, accounts,
assume, start, end, resources, store, db, verbose, debug):
"""load resources into resource database."""
logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
logging.getLogger('botocore').setLevel(logging.WARNING)
logging.getLogger('s3transfer').setLevel(logging.WARNING)
start = date_parse(start)
end = date_parse(end)
if not resources:
resources = ['NetworkInterface', 'Instance', 'LoadBalancer']
account_map = {}
data = yaml.safe_load(account_config.read())
for a in data.get('accounts', ()):
if accounts and (a['name'] in accounts or a['account_id'] in accounts):
account_map[a['account_id']] = a
elif not accounts:
account_map[a['account_id']] = a
account_ids = list(account_map)
executor = ProcessPoolExecutor
if debug:
from c7n.executor import MainThreadExecutor
MainThreadExecutor.async = False
executor = MainThreadExecutor
stats = Counter()
t = time.time()
with executor(max_workers=multiprocessing.cpu_count()) as w:
futures = {}
for a in account_ids:
for r in resources:
futures[w.submit(
process_account_resources, a, bucket, prefix,
region, store, start, end, r)] = (a, r)
indexer = RESOURCE_FILE_INDEXERS[r]
for f in as_completed(futures):
a, r = futures[f]
if f.exception():
log.error("account:%s error:%s", a, f.exception())
continue
files, dl_stats = f.result()
idx_stats = indexer(db, resource_config_iter(files))
log.info(
"loaded account:%s files:%d bytes:%s events:%d resources:%d idx-time:%d dl-time:%d",
account_map[a]['name'], len(files),
human_size(dl_stats['DownloadSize'] + dl_stats['CacheSize']),
idx_stats['Records'],
idx_stats['RowCount'],
idx_stats['IndexTime'],
dl_stats['FetchTime'])
stats.update(dl_stats)
stats.update(idx_stats)
log.info("Loaded %d resources across %d accounts in %0.2f",
stats['RowCount'], len(account_ids), time.time() - t)
if __name__ == '__main__':
try:
cli()
except Exception:
import pdb, traceback, sys
traceback.print_exc()
pdb.post_mortem(sys.exc_info()[-1])
|
apache-2.0
| -6,660,086,870,212,036,000
| 33.309423
| 100
| 0.540051
| false
| 4.058902
| true
| false
| false
|
jjdmol/LOFAR
|
LTA/LTAIngest/dav/webdav/acp/Acl.py
|
1
|
10978
|
# pylint: disable-msg=W0622
#
# Copyright 2008 German Aerospace Center (DLR)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ACL object handling according to WebDAV ACP specification.
"""
from webdav.acp.Ace import ACE
from webdav import Constants
from webdav.Connection import WebdavError
from davlib import XML_DOC_HEADER
__version__ = "$LastChangedRevision$"
class ACL(object):
"""
This class provides access to Access Control List funcionality
as specified in the WebDAV ACP.
@ivar aces: ACEs in ACL
@type aces: C{list} of L{ACE} objects
@ivar withInherited: Flag indicating whether ACL contains inherited ACEs.
@type withInherited: C{bool}
"""
# restrict instance variables
__slots__ = ('aces', 'withInherited')
def __init__(self, domroot=None, aces=None):
"""
Constructor should be called with either no parameters (create blank ACE),
or one parameter (a DOM tree or ACE list).
@param domroot: A DOM tree (default: None).
@type domroot: L{webdav.WebdavResponse.Element} object
@param aces: ACE objects (default: None)
@type aces: C{list} of L{ACE} objects
@raise WebdavError: When non-valid parameters are passed a L{WebdavError} is raised.
"""
self.withInherited = None
self.aces = []
if domroot:
for child in domroot.children:
if child.name == Constants.TAG_ACE and child.ns == Constants.NS_DAV:
self.addAce(ACE(child))
else:
# This shouldn't happen, someone screwed up with the params ...
raise WebdavError('Non-ACE tag handed to ACL constructor: ' + child.ns + child.name)
elif isinstance(aces, list) or isinstance(aces, tuple):
self.addAces(aces)
elif domroot == None and aces == None:
# no param ==> blank object
pass
else:
# This shouldn't happen, someone screwed up with the params ...
raise WebdavError('non-valid parameters handed to ACL constructor')
def __cmp__(self, other):
if not isinstance(other, ACL):
return 1
if self.withInherited == other.withInherited:
equal = 1
for ace in self.aces:
inList = 0
for otherAce in other.aces:
if ace == otherAce:
inList = 1
if inList == 0:
equal = 0
return not equal
else:
return 1
def __repr__(self):
repr = '<class ACL: '
if self.withInherited:
repr += 'with inherited, '
first = 1
repr += 'aces: ['
for ace in self.aces:
if first:
repr += '%s' % ace
first = 0
else:
repr += ', %s' % ace
return '%s]>' % (repr)
def copy(self, other):
'''Copy an ACL object.
@param other: Another ACL to copy.
@type other: L{ACL} object
@raise WebdavError: When an object that is not an L{ACL} is passed
a L{WebdavError} is raised.
'''
if not isinstance(other, ACL):
raise WebdavError('Non-ACL object passed to copy method: %s' % other.__class__)
self.withInherited = other.withInherited
if other.aces:
self.addAces(other.aces)
def toXML(self):
"""
Returns ACL content as a string of valid XML as described in WebDAV ACP.
"""
aclTag = 'D:' + Constants.TAG_ACL
return XML_DOC_HEADER +\
'<' + aclTag + ' xmlns:D="DAV:">' + reduce(lambda xml, ace: xml + ace.toXML() + '\n', [''] + self.aces) +\
'</' + aclTag + '>'
def addAce(self, ace):
'''
Adds the passed ACE object to list if it's not in it, yet.
@param ace: An ACE.
@type ace: L{ACE} object
'''
newAce = ACE()
newAce.copy(ace)
# only add it if it's not in the list, yet ...
inList = 0
for element in self.aces:
if element == ace:
inList = 1
if not inList:
self.aces.append(newAce)
def addAces(self, aces):
'''Adds the list of passed ACE objects to list.
@param aces: ACEs
@type aces: sequence of L{ACE} objects
'''
for ace in aces:
self.addAce(ace)
def delAce(self, ace):
'''Deletes the passed ACE object from list.
@param ace: An ACE.
@type ace: L{ACE} object
@raise WebdavError: When the ACE to be deleted is not within the ACL
a L{WebdavError} is raised.
'''
# find where it is and delete it ...
count = 0
index = 0
for element in self.aces:
count += 1
if element == ace:
index = count
if index:
self.aces.pop(index - 1)
else:
raise WebdavError('ACE to be deleted not in list: %s.' % ace)
def delAces(self, aces):
'''Deletes the list of passed ACE objects from list.
@param aces: ACEs
@type aces: sequence of L{ACE} objects
'''
for ace in aces:
self.delAce(ace)
def delPrincipalsAces(self, principal):
"""
Deletes all ACEs in ACL by given principal.
@param principal: A principal.
@type principal: L{Principal} object
"""
# find where it is and delete it ...
index = 0
while index < len(self.aces):
if self.aces[index].principal.principalURL == principal.principalURL:
self.aces.pop(index)
else:
index += 1
def joinGrantDeny(self):
"""
Returns a "refined" ACL of the ACL for ease of use in the UI.
The purpose is to post the user an ACE that can contain both, granted
and denied, privileges. So possible pairs of grant and deny ACEs are joined
to return them in one ACE. This resulting ACE then of course IS NOT valid
for setting ACLs anymore. They will have to be reconverted to yield valid
ACLs for the ACL method.
@return: A (non-valid) ACL that contains both grant and deny clauses in an ACE.
@rtype: L{ACL} object
"""
joinedAces = {}
for ace in self.aces:
if not ace.principal.principalURL is None:
principalKey = ace.principal.principalURL
elif not ace.principal.property is None:
principalKey = ace.principal.property
else:
principalKey = None
if ace.inherited:
principalKey = ace.inherited + ":" + principalKey
if principalKey in joinedAces:
joinedAces[principalKey].addGrantDenies(ace.grantDenies)
else:
joinedAces[principalKey] = ACE()
joinedAces[principalKey].copy(ace)
newAcl = ACL()
newAcl.addAces(joinedAces.values())
return newAcl
def splitGrantDeny(self):
"""
Returns a "refined" ACL of the ACL for ease of use in the UI.
The purpose is to post the user an ACE that can contain both, granted
and denied, privileges. So possible joined grant and deny clauses in ACEs
splitted to return them in separate ACEs. This resulting ACE then is valid
for setting ACLs again. This method is to be seen in conjunction with the
method joinGrantDeny as it reverts its effect.
@return: A valid ACL that contains only ACEs with either grant or deny clauses.
@rtype: L{ACL} object
"""
acesGrant = {}
acesDeny = {}
for ace in self.aces:
for grantDeny in ace.grantDenies:
if grantDeny.isGrant():
if ace.principal.principalURL in acesGrant:
ace.addGrantDeny(grantDeny)
else:
acesGrant[ace.principal.principalURL] = ACE()
acesGrant[ace.principal.principalURL].copy(ace)
acesGrant[ace.principal.principalURL].grantDenies = []
acesGrant[ace.principal.principalURL].addGrantDeny(grantDeny)
else:
if ace.principal.principalURL in acesDeny:
ace.addGrantDeny(grantDeny)
else:
acesDeny[ace.principal.principalURL] = ACE()
acesDeny[ace.principal.principalURL].copy(ace)
acesDeny[ace.principal.principalURL].grantDenies = []
acesDeny[ace.principal.principalURL].addGrantDeny(grantDeny)
newAcl = ACL()
newAcl.addAces(acesGrant.values())
newAcl.addAces(acesDeny.values())
return newAcl
def isValid(self):
"""
Returns true (1) if all contained ACE objects are valid,
otherwise false (0) is returned.
@return: Validity of ACL.
@rtype: C{bool}
"""
valid = 1
if len(self.aces):
for ace in self.aces:
if not ace.isValid():
valid = 0
return valid
def stripAces(self, inherited=True, protected=True):
"""
Returns an ACL object with all ACEs stripped that are inherited
and/or protected.
@param inherited: Flag to indicate whether inherited ACEs should
be stripped (default: True).
@type inherited: C{bool}
@param protected: Flag to indicate whether protected ACEs should
be stripped (default: True).
@type protected: C{bool}
@return: An ACL without the stripped ACEs.
@rtype: L{ACL} object
"""
newAcl = ACL()
if len(self.aces):
for ace in self.aces:
keep = 1
if inherited and ace.inherited:
keep = 0
elif protected and ace.protected:
keep = 0
if keep:
newAcl.addAce(ace)
return newAcl
|
gpl-3.0
| 5,891,104,285,362,545,000
| 34.299035
| 118
| 0.55092
| false
| 4.081041
| false
| false
| false
|
thundernet8/WRGameVideos-API
|
venv/lib/python2.7/site-packages/flask_jsonpify.py
|
1
|
2543
|
from flask import current_app, json, request
def __pad(strdata):
""" Pads `strdata` with a Request's callback argument, if specified, or does
nothing.
"""
if request.args.get('callback'):
return "%s(%s);" % (request.args.get('callback'), strdata)
else:
return strdata
def __mimetype():
if request.args.get('callback'):
return 'application/javascript'
else:
return 'application/json'
def __dumps(*args, **kwargs):
""" Serializes `args` and `kwargs` as JSON. Supports serializing an array
as the top-level object, if it is the only argument.
"""
indent = None
if (current_app.config.get('JSONIFY_PRETTYPRINT_REGULAR', False)
and not request.is_xhr):
indent = 2
return json.dumps(args[0] if len(args) is 1 else dict(*args, **kwargs),
indent=indent)
def jsonpify(*args, **kwargs):
"""Creates a :class:`~flask.Response` with the JSON or JSON-P
representation of the given arguments with an `application/json`
or `application/javascript` mimetype, respectively. The arguments
to this function are the same as to the :class:`dict` constructor,
but also accept an array. If a `callback` is specified in the
request arguments, the response is JSON-Padded.
Example usage::
@app.route('/_get_current_user')
def get_current_user():
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
GET /_get_current_user:
This will send a JSON response like this to the browser::
{
"username": "admin",
"email": "admin@localhost",
"id": 42
}
or, if a callback is specified,
GET /_get_current_user?callback=displayUsers
Will result in a JSON response like this to the browser::
displayUsers({
"username": "admin",
"email": "admin@localhost",
"id": 42
});
This requires Python 2.6 or an installed version of simplejson. For
security reasons only objects are supported toplevel. For more
information about this, have a look at :ref:`json-security`.
.. versionadded:: 0.2
"""
return current_app.response_class(__pad(__dumps(*args, **kwargs)),
mimetype=__mimetype())
jsonify = jsonpify # allow override of Flask's jsonify.
|
gpl-2.0
| -717,886,847,209,968,100
| 29.395062
| 80
| 0.583956
| false
| 4.231281
| false
| false
| false
|
taoliu/taolib
|
Scripts/ce_histone_matrix.py
|
1
|
17749
|
#!/usr/bin/env python
# Time-stamp: <2010-09-08 02:38:38 Tao Liu>
"""Module Description
Copyright (c) 2008 Tao Liu <taoliu@jimmy.harvard.edu>
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD License (see the file COPYING included with
the distribution).
@status: experimental
@version: $Revision$
@author: Tao Liu
@contact: taoliu@jimmy.harvard.edu
"""
# ------------------------------------
# python modules
# ------------------------------------
import os
import sys
import re
import csv
import logging
from optparse import OptionParser
import reportlab
import Bio
from taolib.CoreLib.FeatIO import WigTrackI
from taolib.CoreLib.BasicStat.Func import mean,median,std
# ------------------------------------
# constants
# ------------------------------------
logging.basicConfig(level=20,
format='%(levelname)-5s @ %(asctime)s: %(message)s ',
datefmt='%a, %d %b %Y %H:%M:%S',
stream=sys.stderr,
filemode="w"
)
error = logging.critical # function alias
warn = logging.warning
debug = logging.debug
info = logging.info
# ------------------------------------
# Misc functions
# ------------------------------------
def andfilter ( cvsfile, write_func, *args ):
"""
"""
argv = args[0]
if len(argv) < 2:
sys.stderr.write("Need two extra arguments for 'organize', e.g. command: <1,2,3> <4,5,6> means the first 1,2,3 will be used as dependent variables/response, and 4,5,6 will be used as independent variables/terms/predictors.\n")
sys.exit()
responses_num = map(int,argv[0].split(","))
predictors_num = map(int,argv[1].split(","))
fields = cvsfile.fieldnames
responses_label = map(lambda x:"res."+fields[x],responses_num)
predictors_label = map(lambda x:"pre."+fields[x],predictors_num)
responses_name = map(lambda x:fields[x],responses_num)
predictors_name = map(lambda x:fields[x],predictors_num)
#write_func( "#%s\t%s\n" \
# % ( ",".join(map( lambda x:str(x[0])+":"+str(x[1]) , zip(responses_num,responses_name) )),
# ",".join(map( lambda x:str(x[0])+":"+str(x[1]) , zip(predictors_num,predictors_name) ))) )
write_func( "%s\t%s\n" \
% ( ",".join(map( lambda x:str(x) , responses_name )),
",".join(map( lambda x:str(x) , predictors_name ))) )
for l in cvsfile:
# for responses
t_str_list = []
for t in responses_name:
t_str_list.append(l.setdefault(t,"NA"))
# for predictors
v_str_list = []
for v in predictors_name:
v_str_list.append(l.setdefault(v,"NA"))
write_func( "\t".join( (",".join(t_str_list),",".join(v_str_list)) ) )
write_func( "\n" )
def combcall2draw ( cvsfile, write_func, *args ):
"""User specifies several columns to consider, this tool will call
regions where either of the column is above its threshold.
"""
argv = args[0]
if len(argv) < 6:
sys.stderr.write("Need 6 extra arguments for 'combcall2draw', options <loc column> <score column1[,score column2,...]> <cutoff1[,cutoff2,cutoff3]> <min length> <max gap> <pdf filename>\ne.g. command: <0> <1,2,3> <0.5,0.6,0.7> <10000> <2000> <a.pdf>, means to use the first column as genome coordinations to call enriched regions from the combinition of #1, #2 and #3, the thresholds to call enriched region are 0.5 for column 1, 0.6 for column 2 and 0.7 for column 3, the minimum length of region is 10k, and the maximum gap to link two nearby regions is 2k. Then the figure will be saved in a.pdf.\n")
sys.exit()
cor_column = cvsfile.fieldnames[int(argv[0])]
var_columns = map(lambda x:cvsfile.fieldnames[int(x)],argv[1].split(","))
cutoffs = map(float,argv[2].split(","))
min_len = int(argv[3])
max_gap = int(argv[4])
wtrack = WigTrackI() # combined track containing 1 if either of track is above cutoff
add_func = wtrack.add_loc
for l in cvsfile:
cor = l.setdefault(cor_column,None)
if not cor or cor =="NA":
continue
for i in range(len(var_columns)):
var_column = var_columns[i]
cutoff = cutoffs[i]
var = l.setdefault(var_column,None)
if var and var != "NA" and float(var) > cutoff:
(chrom,start,end) = cor.split(".")
add_func(chrom,int(start),1.1)
break
wtrack.span = int(end)-int(start)
bpeaks = wtrack.call_peaks(cutoff=1.0,min_length=min_len,max_gap=max_gap)
#f = argv[5]
fhd = open(argv[5].replace("pdf","bed"),"w")
fhd.write(bpeaks.tobed())
from Bio.Graphics import BasicChromosome
from reportlab.lib.colors import gray, black, white
entries = [("chrI", 15072419),
("chrII", 15279316),
("chrIII", 13783681),
("chrIV", 17493784),
("chrV", 20919398),
("chrX", 17718852)]
max_length = max([x[1] for x in entries])
chr_diagram = BasicChromosome.Organism()
for name, length in entries:
cur_chromosome = BasicChromosome.Chromosome(name)
#Set the length, adding and extra 20 percent for the tolomeres:
cur_chromosome.scale_num = max_length * 1.1
# Add an opening telomere
start = BasicChromosome.TelomereSegment()
start.scale = 0.05 * max_length
start.fill_color=gray
cur_chromosome.add(start)
#Add a body - using bp as the scale length here.
try:
cpeaks = bpeaks.peaks[name]
except:
cpeaks = []
body_regions = []
last_pos = 0
for p in cpeaks:
body_regions.append( (p[0]-last_pos,white) ) # outside regions
body_regions.append( (p[1]-p[0],black) ) # enriched regions
last_pos = p[1]
assert p[1] < length
body_regions.append( (length-last_pos,white) ) # last part
for b,c in body_regions:
body = BasicChromosome.ChromosomeSegment()
body.fill_color= c
body.scale = b
cur_chromosome.add(body)
#Add a closing telomere
end = BasicChromosome.TelomereSegment(inverted=True)
end.scale = 0.05 * max_length
end.fill_color=gray
cur_chromosome.add(end)
#This chromosome is done
chr_diagram.add(cur_chromosome)
chr_diagram.draw(argv[5], "Highlight regions in Caenorhabditis elegans" )
def call1draw ( cvsfile, write_func, *args ):
"""Call regions, then plot it in chromosome figure.
A combination of drawchrom and call1
"""
argv = args[0]
if len(argv) < 6:
sys.stderr.write("Need 6 extra arguments for 'call1draw', options <loc column> <score column> <cutoff> <min length> <max gap> <pdf filename>\ne.g. command: <0> <1> <0.5> <10000> <2000> <a.pdf>, means to use the first column as genome coordinations to call enriched regions from the second column, the threshold to call enriched region is 0.5, the minimum length of region is 10k, and the maximum gap to link two nearby regions is 2k. Then the figure will be saved in a.pdf.\n")
sys.exit()
cor_column = cvsfile.fieldnames[int(argv[0])]
var_column = cvsfile.fieldnames[int(argv[1])]
cutoff = float(argv[2])
min_len = int(argv[3])
max_gap = int(argv[4])
wtrack = WigTrackI()
add_func = wtrack.add_loc
for l in cvsfile:
cor = l.setdefault(cor_column,None)
var = l.setdefault(var_column,None)
if cor and var and cor != "NA" and var != "NA":
(chrom,start,end) = cor.split(".")
add_func(chrom,int(start),float(var))
wtrack.span = int(end)-int(start)
bpeaks = wtrack.call_peaks(cutoff=cutoff,min_length=min_len,max_gap=max_gap)
fhd = open(argv[5].replace("pdf","bed"),"w")
fhd.write(bpeaks.tobed())
from Bio.Graphics import BasicChromosome
from reportlab.lib.colors import gray, black, white
entries = [("chrI", 15072419),
("chrII", 15279316),
("chrIII", 13783681),
("chrIV", 17493784),
("chrV", 20919398),
("chrX", 17718852)]
max_length = max([x[1] for x in entries])
chr_diagram = BasicChromosome.Organism()
for name, length in entries:
cur_chromosome = BasicChromosome.Chromosome(name)
#Set the length, adding and extra 20 percent for the tolomeres:
cur_chromosome.scale_num = max_length * 1.1
# Add an opening telomere
start = BasicChromosome.TelomereSegment()
start.scale = 0.05 * max_length
start.fill_color=gray
cur_chromosome.add(start)
#Add a body - using bp as the scale length here.
try:
cpeaks = bpeaks.peaks[name]
except:
cpeaks = []
body_regions = []
last_pos = 0
for p in cpeaks:
body_regions.append( (p[0]-last_pos,white) ) # outside regions
body_regions.append( (p[1]-p[0],black) ) # enriched regions
last_pos = p[1]
assert p[1] < length
body_regions.append( (length-last_pos,white) ) # last part
for b,c in body_regions:
body = BasicChromosome.ChromosomeSegment()
body.fill_color= c
body.scale = b
cur_chromosome.add(body)
#Add a closing telomere
end = BasicChromosome.TelomereSegment(inverted=True)
end.scale = 0.05 * max_length
end.fill_color=gray
cur_chromosome.add(end)
#This chromosome is done
chr_diagram.add(cur_chromosome)
chr_diagram.draw(argv[5], "%s regions in Caenorhabditis elegans" % (var_column) )
def drawchrom ( cvsfile, write_func, *args ):
"""Draw CE chromosome tool.
Doesn't need any parameters.
"""
from Bio.Graphics import BasicChromosome
from reportlab.lib.colors import gray, black
entries = [("chrI", 15072419),
("chrII", 15279316),
("chrIII", 13783681),
("chrIV", 17493784),
("chrV", 20919398),
("chrX", 17718852)]
max_length = max([x[1] for x in entries])
chr_diagram = BasicChromosome.Organism()
for name, length in entries:
cur_chromosome = BasicChromosome.Chromosome(name)
#Set the length, adding and extra 20 percent for the tolomeres:
cur_chromosome.scale_num = max_length * 1.1
# Add an opening telomere
start = BasicChromosome.TelomereSegment()
start.scale = 0.05 * max_length
start.fill_color=black
cur_chromosome.add(start)
#Add a body - using bp as the scale length here.
body = BasicChromosome.ChromosomeSegment()
body.fill_color=gray
body.scale = length
cur_chromosome.add(body)
#Add a closing telomere
end = BasicChromosome.TelomereSegment(inverted=True)
end.scale = 0.05 * max_length
end.fill_color=black
cur_chromosome.add(end)
#This chromosome is done
chr_diagram.add(cur_chromosome)
chr_diagram.draw("simple_chrom.pdf", "Caenorhabditis elegans" )
def summary ( cvsfile, write_func, *args ):
"""Show the column names.
"""
fsnames = cvsfile.fieldnames
data_dict = {}
for f in fsnames:
data_dict[f]=[]
#print "\n".join(map( lambda x:":".join(map(str,x)) ,enumerate(fsnames)) )
for l in cvsfile:
for f in fsnames:
v = l.setdefault(f,None)
if v and v!="NA":
data_dict[f].append(v)
write_func( "colnum:colname\tsum,mean,median,std,cutoff\n" )
for (i,f) in enumerate(fsnames):
try:
v_array = map(float,data_dict[f])
v_sum = "%.2f" % sum(v_array)
v_mean = "%.2f" % mean(v_array)
v_median = "%.2f" % median(v_array)
v_std = "%.2f" % std(v_array, float(v_mean))
v_cutoff = "%.2f" % (float(v_mean)+float(v_std))
except ValueError:
(v_sum,v_mean,v_median,v_std,v_cutoff)=["NA"]*5
write_func( "%d:%s\t%s,%s,%s,%s,%s\n" % (i,f,v_sum,v_mean,v_median,v_std,v_cutoff ))
def organize ( cvsfile, write_func, *args ):
"""Re-organize the columns for data-mining.
"""
argv = args[0]
if len(argv) < 2:
sys.stderr.write("Need two extra arguments for 'organize', e.g. command: <1,2,3> <4,5,6> means the first 1,2,3 will be used as dependent variables/response, and 4,5,6 will be used as independent variables/terms/predictors.\n")
sys.exit()
responses_num = map(int,argv[0].split(","))
predictors_num = map(int,argv[1].split(","))
fields = cvsfile.fieldnames
responses_label = map(lambda x:"res."+fields[x],responses_num)
predictors_label = map(lambda x:"pre."+fields[x],predictors_num)
responses_name = map(lambda x:fields[x],responses_num)
predictors_name = map(lambda x:fields[x],predictors_num)
#write_func( "#%s\t%s\n" \
# % ( ",".join(map( lambda x:str(x[0])+":"+str(x[1]) , zip(responses_num,responses_name) )),
# ",".join(map( lambda x:str(x[0])+":"+str(x[1]) , zip(predictors_num,predictors_name) ))) )
write_func( "%s\t%s\n" \
% ( ",".join(map( lambda x:str(x) , responses_name )),
",".join(map( lambda x:str(x) , predictors_name ))) )
for l in cvsfile:
# for responses
t_str_list = []
for t in responses_name:
t_str_list.append(l.setdefault(t,"NA"))
# for predictors
v_str_list = []
for v in predictors_name:
v_str_list.append(l.setdefault(v,"NA"))
write_func( "\t".join( (",".join(t_str_list),",".join(v_str_list)) ) )
write_func( "\n" )
def call1 (cvsfile, write_func, *args ):
"""Call enrich regions from certain column
"""
argv = args[0]
if len(argv) < 5:
sys.stderr.write("Need 5 extra arguments for 'call', options <loc column> <score column> <cutoff> <min length> <max gap>\ne.g. command: <0> <1> <0.5> <10000> <2000>, means to use the first column as genome coordinations to call enriched regions from the second column, the threshold to call enriched region is 0.5, the minimum length of region is 10k, and the maximum gap to link two nearby regions is 2k.\n")
sys.exit()
cor_column = cvsfile.fieldnames[int(argv[0])]
var_column = cvsfile.fieldnames[int(argv[1])]
cutoff = float(argv[2])
min_len = int(argv[3])
max_gap = int(argv[4])
wtrack = WigTrackI()
add_func = wtrack.add_loc
for l in cvsfile:
cor = l.setdefault(cor_column,None)
var = l.setdefault(var_column,None)
if cor and var and cor != "NA" and var != "NA":
(chrom,start,end) = cor.split(".")
add_func(chrom,int(start),float(var))
wtrack.span = int(end)-int(start)
write_func( "# regions called from %s:%s\n" % (argv[1],var_column) )
bpeaks = wtrack.call_peaks(cutoff=cutoff,min_length=min_len,max_gap=max_gap)
write_func( bpeaks.tobed() )
# ------------------------------------
# Classes
# ------------------------------------
# ------------------------------------
# Main function
# ------------------------------------
def main():
usage = "usage: %prog [options]"
description = "Script to analyze C. elegans histone marks data matrix."
optparser = OptionParser(version="%prog 0.1",description=description,usage=usage,add_help_option=False)
optparser.add_option("-h","--help",action="help",help="Show this help message and exit.")
optparser.add_option("-i","--ifile",dest="ifile",type="string",
help="input file")
optparser.add_option("-o","--ofile",dest="ofile",
help="output file, default: stdout")
(options,args) = optparser.parse_args()
command_list = {"summary":summary,
"organize":organize,
"call1":call1,
"drawchrom":drawchrom,
"call1draw":call1draw,
"combcall2draw":combcall2draw,
}
command_des = {"summary":"Show the column names.",
"organize":"Re-organize the file for data-mining.",
"call1":"Call enriched regions for certain column.",
"drawchrom":"Draw ce chromosomes.",
"call1draw":"Call enriched regions and then draw chromosome figures.",
"combcall2draw":"Call enriched regions where any of the tracks is above threshold and draw them on chromosome figures.",
}
if not options.ifile or not args:
optparser.print_help()
sys.exit()
if options.ofile:
write_func = open(options.ofile,"w").write
else:
write_func = sys.stdout.write
if command_list.has_key(args[0]):
com = command_list[args[0]]
com_args = args[1:]
else:
optparser.print_help()
sys.stderr.write("Avialable Commands:\n\n")
for c in command_list.keys():
sys.stderr.write(c+": "+command_des[c]+"\n")
sys.exit()
cvsfilereader = csv.DictReader(open(options.ifile,"r"),delimiter="\t")
# run commands
com(cvsfilereader,write_func,com_args)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
sys.stderr.write("User interrupt me! ;-) See you!\n")
sys.exit(0)
|
bsd-3-clause
| -3,209,012,394,225,596,000
| 38.267699
| 610
| 0.57423
| false
| 3.391745
| false
| false
| false
|
antechrestos/cf-python-client
|
main/cloudfoundry_client/v2/service_brokers.py
|
1
|
1120
|
from cloudfoundry_client.v2.entities import EntityManager
class ServiceBrokerManager(EntityManager):
def __init__(self, target_endpoint, client):
super(ServiceBrokerManager, self).__init__(target_endpoint, client, '/v2/service_brokers')
def create(self, broker_url, broker_name, auth_username, auth_password, space_guid=None):
request = self._request(broker_url=broker_url, name=broker_name,
auth_username=auth_username, auth_password=auth_password)
request['space_guid'] = space_guid
return super(ServiceBrokerManager, self)._create(request)
def update(self, broker_guid, broker_url=None, broker_name=None, auth_username=None, auth_password=None):
request = self._request()
request['broker_url'] = broker_url
request['name'] = broker_name
request['auth_username'] = auth_username
request['auth_password'] = auth_password
return super(ServiceBrokerManager, self)._update(broker_guid, request)
def remove(self, broker_guid):
super(ServiceBrokerManager, self)._remove(broker_guid)
|
apache-2.0
| -4,444,524,997,635,367,400
| 47.695652
| 109
| 0.68125
| false
| 3.971631
| false
| false
| false
|
Comunitea/CMNT_004_15
|
project-addons/custom_account/models/payment.py
|
1
|
3019
|
# Copyright 2019 Omar Castiñeira, Comunitea Servicios Tecnológicos S.L.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api
class PaymentOrderLine(models.Model):
_inherit = 'account.payment.line'
_order = 'partner_name'
partner_name = fields.Char(related='partner_id.name', store=True)
@api.model
def create(self, vals):
partner_bank_id = vals.get('partner_bank_id')
move_line_id = vals.get('move_line_id')
partner_id = vals.get('partner_id')
order_id = vals.get('order_id')
if order_id:
order = self.env['account.payment.order'].browse(order_id)
if order.payment_method_id.mandate_required and not \
vals.get('mandate_id'):
if move_line_id:
line = self.env['account.move.line'].browse(move_line_id)
if line.invoice_id and \
line.invoice_id.type == 'out_invoice' and \
line.invoice_id.mandate_id:
if line.invoice_id.mandate_id.state == 'valid':
vals.update({
'mandate_id': line.invoice_id.mandate_id.id,
'partner_bank_id':
line.invoice_id.mandate_id.partner_bank_id.id})
if partner_bank_id and not vals.get('mandate_id'):
mandates = self.env['account.banking.mandate'].search_read(
[('partner_bank_id', '=', partner_bank_id),
('state', '=', 'valid')], ['id'])
if mandates:
vals['mandate_id'] = mandates[0]['id']
else:
banking_mandate_valid = \
self.env['account.banking.mandate'].\
search_read([('partner_id', '=', partner_id),
('state', '=', 'valid')],
['id', 'partner_bank_id'])
if banking_mandate_valid:
vals.update({
'mandate_id': banking_mandate_valid[0]['id'],
'partner_bank_id':
banking_mandate_valid[0]['partner_bank_id'][0],
})
return super().create(vals)
class BankPaymentLine(models.Model):
_inherit = "bank.payment.line"
mandate_id = fields.Many2one("account.banking.mandate", "Mandate",
related="payment_line_ids.mandate_id",
readonly=True)
mandate_scheme = fields.Selection([('CORE', 'Basic (CORE)'),
('B2B', 'Enterprise (B2B)')],
string='Scheme', readonly=True,
related="mandate_id.scheme")
|
agpl-3.0
| -3,272,857,600,221,413,000
| 44.712121
| 79
| 0.46006
| false
| 4.196106
| false
| false
| false
|
project-owner/Peppy
|
ui/container.py
|
1
|
6297
|
# Copyright 2016-2021 Peppy Player peppy.player@gmail.com
#
# This file is part of Peppy Player.
#
# Peppy Player 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.
#
# Peppy Player is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Peppy Player. If not, see <http://www.gnu.org/licenses/>.
from ui.component import Component
class Container(Component):
""" This container class keeps the list of components and executes group methods on them """
def __init__(self, util, bounding_box=None, background=None, visible=True, content=None, image_filename=None):
""" Initializer
:param util: utility object
:param bounding_box: container bounding box
:param background: container background color
:param visible: visibility flag, True - visible, False - invisible
"""
if content:
cnt = content
else:
cnt = bounding_box
Component.__init__(self, util, c=cnt, bb=bounding_box, bgr=background, v=visible)
self.components = list()
if image_filename:
self.image_filename = image_filename
self.exit_top_y = self.exit_bottom_y = self.exit_left_x = self.exit_right_x = None
def add_component(self, component):
""" Add component to the container
:param component: component to add
"""
self.components.append(component)
def set_parent_screen(self, scr):
""" Add parent screen
:param scr: parent screen
"""
if self.is_empty(): return
self.parent_screen = scr
for c in self.components:
if c:
c.parent_screen = scr
def draw(self):
""" Draw all components in container. Doesn't draw invisible container. """
if not self.visible: return
Component.draw(self)
if self.is_empty(): return
for comp in self.components:
if comp: comp.draw()
def draw_area(self, bb):
if not self.visible: return
Component.draw(self, bb)
def is_empty(self):
""" Check if container has components
:return: True - container doesn't have components, False - container has components
"""
return not hasattr(self, "components")
def clean_draw_update(self):
""" Clean, draw and update container """
self.clean()
self.draw()
self.update()
def handle_event(self, event):
""" Handle container event. Don't handle event if container is invisible.
:param event: the event to handle
"""
if not self.visible or len(self.components) == 0: return
for i in range(len(self.components) - 1, -1, -1):
try:
comp = self.components[i]
if not hasattr(comp, "handle_event"):
continue
if getattr(comp, "popup", None) == True:
if comp.visible == True:
comp.handle_event(event)
break
else:
comp.handle_event(event)
except:
pass
def set_current(self, state=None):
""" Set container as current. Used by screens
:param state: button state (if any)
"""
pass
def set_visible(self, flag):
""" Set container visible/invisible. Set all components in container visible/invisible.
:param flag: True - visible, False - invisible
"""
Component.set_visible(self, flag)
if self.is_empty(): return
for comp in self.components:
if not comp: continue
if getattr(comp, "popup", None) == True:
if not comp.visible:
continue
else:
comp.set_visible(flag)
def refresh(self):
""" Refresh container. Used for periodical updates for example for animation.
This method will be called from the main event loop.
"""
if not self.visible: return
for comp in self.components:
try:
comp.refresh()
except AttributeError:
pass
def is_selected(self):
""" Check if conatiner has selected component
:return: True - container has selected component, False - doesn't have
"""
s = False
for c in self.components:
if c and getattr(c, "selected", False):
s = True
break
return s
def items_per_line(self, width):
""" Return the number of items in line for specified screen width
:param width: screen width
:return: number of items per line
"""
if width <= 102:
return 1
elif width <= 203:
return 2
elif width <= 304:
return 3
elif width <= 405:
return 4
elif width <= 506:
return 5
else:
return 6
def add_button_observers(self, button, update_observer, redraw_observer=None, press=True, release=True):
""" Add button observers
:param button: button to observer
:param update_observer: observer for updating the button
:param redraw_observer: observer to redraw the whole screen
"""
if press and update_observer: button.add_press_listener(update_observer)
if release and update_observer: button.add_release_listener(update_observer)
if redraw_observer and redraw_observer:
button.add_release_listener(redraw_observer)
button.redraw_observer = redraw_observer
|
gpl-3.0
| -7,975,863,792,035,716,000
| 31.626943
| 114
| 0.570907
| false
| 4.623348
| false
| false
| false
|
ooici/marine-integrations
|
mi/dataset/driver/hypm/ctd/driver.py
|
1
|
1597
|
"""
@package mi.dataset.driver.hypm.ctd.driver
@file marine-integrations/mi/dataset/driver/hypm/ctd/driver.py
@author Bill French
@brief Driver for the hypm/ctd
Release notes:
initial release
"""
__author__ = 'Bill French'
__license__ = 'Apache 2.0'
from mi.core.log import get_logger ; log = get_logger()
from mi.dataset.dataset_driver import SimpleDataSetDriver
from mi.dataset.parser.ctdpf import CtdpfParser
from mi.dataset.parser.ctdpf import CtdpfParserDataParticle
from mi.dataset.harvester import SingleDirectoryHarvester
class HypmCTDPFDataSetDriver(SimpleDataSetDriver):
@classmethod
def stream_config(cls):
return [CtdpfParserDataParticle.type()]
def _build_parser(self, parser_state, infile):
config = self._parser_config
config.update({
'particle_module': 'mi.dataset.parser.ctdpf',
'particle_class': 'CtdpfParserDataParticle'
})
log.debug("MYCONFIG: %s", config)
self._parser = CtdpfParser(
config,
parser_state,
infile,
self._save_parser_state,
self._data_callback,
self._sample_exception_callback
)
return self._parser
def _build_harvester(self, driver_state):
"""
Build and return the harvester
"""
self._harvester = SingleDirectoryHarvester(
self._harvester_config,
driver_state,
self._new_file_callback,
self._modified_file_callback,
self._exception_callback
)
return self._harvester
|
bsd-2-clause
| 1,017,401,072,070,529,700
| 27.017544
| 62
| 0.639324
| false
| 3.802381
| true
| false
| false
|
cmunk/protwis
|
api/views.py
|
1
|
32974
|
from django.shortcuts import render
from rest_framework import views, generics, viewsets
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser, FileUploadParser
from rest_framework.renderers import JSONRenderer
from django.template.loader import render_to_string
from django.db.models import Q
from django.conf import settings
from interaction.models import ResidueFragmentInteraction
from mutation.models import MutationRaw
from protein.models import Protein, ProteinConformation, ProteinFamily, Species, ProteinSegment
from residue.models import Residue, ResidueGenericNumber, ResidueNumberingScheme, ResidueGenericNumberEquivalent
from structure.models import Structure
from structure.assign_generic_numbers_gpcr import GenericNumbering
from api.serializers import (ProteinSerializer, ProteinFamilySerializer, SpeciesSerializer, ResidueSerializer,
ResidueExtendedSerializer, StructureSerializer,
StructureLigandInteractionSerializer,
MutationSerializer)
from api.renderers import PDBRenderer
from common.alignment import Alignment
from common.definitions import *
from drugs.models import Drugs
import json, os
from io import StringIO
from Bio.PDB import PDBIO
from collections import OrderedDict
# FIXME add
# getMutations
# numberPDBfile
import coreapi
from urllib.parse import urlparse
from urllib.parse import urljoin
from rest_framework import renderers, response, schemas
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import response, schemas
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='GPCRdb API')
class ProteinDetail(generics.RetrieveAPIView):
"""
Get a single protein instance by entry name
\n/protein/{entry_name}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
"""
queryset = Protein.objects.filter(sequence_type__slug="wt").prefetch_related('family', 'species', 'source', 'residue_numbering_scheme', 'genes')
serializer_class = ProteinSerializer
lookup_field = 'entry_name'
class ProteinByAccessionDetail(ProteinDetail):
"""
Get a single protein instance by accession
\n/protein/accession/{accession}/
\n{accession} is a protein identifier from Uniprot, e.g. P07550
"""
lookup_field = 'accession'
class ProteinFamilyList(generics.ListAPIView):
"""
Get a list of protein families
\n/proteinfamily/
"""
queryset = ProteinFamily.objects.all().prefetch_related('parent')
serializer_class = ProteinFamilySerializer
class ProteinFamilyDetail(generics.RetrieveAPIView):
"""
Get a single protein family instance
\n/proteinfamily/{slug}/
\n{slug} is a protein family identifier, e.g. 001_001_001
"""
queryset = ProteinFamily.objects.all().prefetch_related("parent")
serializer_class = ProteinFamilySerializer
lookup_field = 'slug'
class ProteinFamilyChildrenList(generics.ListAPIView):
"""
Get a list of child families of a protein family
\n/proteinfamily/children/{slug}/
\n{slug} is a protein family identifier, e.g. 001_001_001
"""
serializer_class = ProteinFamilySerializer
def get_queryset(self):
family = self.kwargs.get('slug')
queryset = ProteinFamily.objects.all().prefetch_related("parent")
return queryset.filter(parent__slug=family)
class ProteinFamilyDescendantList(generics.ListAPIView):
"""
Get a list of descendant families of a protein family
\n/proteinfamily/descendants/{slug}/
\n{slug} is a protein family identifier, e.g. 001_001_001
"""
serializer_class = ProteinFamilySerializer
def get_queryset(self):
family = self.kwargs.get('slug')
queryset = ProteinFamily.objects.all().prefetch_related("parent")
return queryset.filter(Q(slug__startswith=family) & ~Q(slug=family))
class ProteinsInFamilyList(generics.ListAPIView):
"""
Get a list of proteins in a protein family
\n/proteinfamily/proteins/{slug}/
\n{slug} is a protein family identifier, e.g. 001_001_001
"""
serializer_class = ProteinSerializer
def get_queryset(self):
queryset = Protein.objects.all()
family = self.kwargs.get('slug')
return queryset.filter(sequence_type__slug='wt', family__slug__startswith=family)\
.prefetch_related('family', 'species', 'source', 'residue_numbering_scheme', 'genes')
class ProteinsInFamilySpeciesList(generics.ListAPIView):
"""
Get a list of proteins in a protein family
\n/proteinfamily/proteins/{slug}/{species}
\n{slug} is a protein family identifier, e.g. 001_001_001
\n{latin_name} is a species identifier from Uniprot, e.g. Homo sapiens
"""
serializer_class = ProteinSerializer
def get_queryset(self):
queryset = Protein.objects.all()
family = self.kwargs.get('slug')
species = self.kwargs.get('latin_name')
return queryset.filter(sequence_type__slug='wt', family__slug__startswith=family,
species__latin_name=species).prefetch_related('family',
'species', 'source', 'residue_numbering_scheme', 'genes')
class ResiduesList(generics.ListAPIView):
"""
Get a list of residues of a protein
\n/residues/{entry_name}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
"""
serializer_class = ResidueSerializer
def get_queryset(self):
queryset = Residue.objects.all()
#protein_conformation__protein__sequence_type__slug='wt',
return queryset.filter(
protein_conformation__protein__entry_name=self.kwargs.get('entry_name')).prefetch_related('display_generic_number','protein_segment','alternative_generic_numbers')
class ResiduesExtendedList(ResiduesList):
"""
Get a list of residues of a protein, including alternative generic numbers
\n/residues/extended/{entry_name}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
"""
serializer_class = ResidueExtendedSerializer
class SpeciesList(generics.ListAPIView):
"""
Get a list of species
\n/species/
"""
queryset = Species.objects.all()
serializer_class = SpeciesSerializer
class SpeciesDetail(generics.RetrieveAPIView):
"""
Get a single species instance
\n/species/{latin_name}/
\n{latin_name} is a species identifier from Uniprot, e.g. Homo sapiens
"""
queryset = Species.objects.all()
serializer_class = SpeciesSerializer
lookup_field = 'latin_name'
class NumberPDBStructureView(views.APIView):
"""
WRITEME
"""
pass
class StructureList(views.APIView):
"""
Get a list of structures
\n/structure/
"""
def get(self, request, pdb_code=None, entry_name=None, representative=None):
if pdb_code:
structures = Structure.objects.filter(pdb_code__index=pdb_code)
elif entry_name and representative:
structures = Structure.objects.filter(protein_conformation__protein__parent__entry_name=entry_name,
representative=True)
elif entry_name:
structures = Structure.objects.filter(protein_conformation__protein__parent__entry_name=entry_name)
elif representative:
structures = Structure.objects.filter(representative=True)
else:
structures = Structure.objects.all()
structures = structures.exclude(refined=True).prefetch_related('protein_conformation__protein__parent__species', 'pdb_code',
'protein_conformation__protein__parent__family', 'protein_conformation__protein__parent__species',
'publication__web_link', 'structureligandinteraction_set__ligand__properities', 'structure_type',
'structureligandinteraction_set__ligand__properities__ligand_type',
'structureligandinteraction_set__ligand_role')
# structures = self.get_structures(pdb_code, entry_name, representative)
# convert objects to a list of dictionaries
# normal serializers can not be used because of abstraction of tables (e.g. protein_conformation)
s = []
for structure in structures:
# essential fields
structure_data = {
'pdb_code': structure.pdb_code.index,
'protein': structure.protein_conformation.protein.parent.entry_name,
'family': structure.protein_conformation.protein.parent.family.slug,
'species': structure.protein_conformation.protein.parent.species.latin_name,
'preferred_chain': structure.preferred_chain,
'resolution': structure.resolution,
'publication_date': structure.publication_date,
'type': structure.structure_type.name,
'state': structure.state.name,
'distance': structure.distance,
}
# publication
if structure.publication:
structure_data['publication'] = structure.publication.web_link.__str__()
else:
structure_data['publication'] = None
# ligand
ligands = []
for interaction in structure.structureligandinteraction_set.filter(annotated=True):
ligand = {}
if interaction.ligand.name:
ligand['name'] = interaction.ligand.name
if interaction.ligand.properities.ligand_type and interaction.ligand.properities.ligand_type.name:
ligand['type'] = interaction.ligand.properities.ligand_type.name
if interaction.ligand_role and interaction.ligand_role.name:
ligand['function'] = interaction.ligand_role.name
if ligand:
ligands.append(ligand)
structure_data['ligands'] = ligands
s.append(structure_data)
# if a structure is selected, return a single dict rather then a list of dicts
if len(s) == 1:
s = s[0]
return Response(s)
def get_structures(self, pdb_code=None, representative=None):
return Structure.objects.all()
class RepresentativeStructureList(StructureList):
"""
Get a list of representative structures (one for each protein and activation state)
\n/structure/representative/
"""
class StructureListProtein(StructureList):
"""
Get a list of structures of a protein
\n/structure/protein/{entry_name}
"""
class RepresentativeStructureListProtein(StructureList):
"""
Get a list of representative structures of a protein (one for each activation state)
\n/structure/protein/{entry_name}/representative/
"""
class StructureDetail(StructureList):
"""
Get a single structure instance
\n/structure/{pdb_code}/
\n{pdb_code} is a structure identifier from the Protein Data Bank, e.g. 2RH1
"""
def get_structures(self, pdb_code=None, representative=None):
return Structure.objects.filter(pdb_code__index=pdb_code)
class FamilyAlignment(views.APIView):
"""
Get a full sequence alignment of a protein family including a consensus sequence
\n/alignment/family/{slug}/
\n{slug} is a protein family identifier, e.g. 001_001_001
"""
def get(self, request, slug=None, segments=None, latin_name=None, statistics=False):
if slug is not None:
# Check for specific species
if latin_name is not None:
ps = Protein.objects.filter(sequence_type__slug='wt', source__id=1, family__slug__startswith=slug,
species__latin_name=latin_name)
else:
ps = Protein.objects.filter(sequence_type__slug='wt', source__id=1, family__slug__startswith=slug)
# take the numbering scheme from the first protein
#s_slug = Protein.objects.get(entry_name=ps[0]).residue_numbering_scheme_id
s_slug = ps[0].residue_numbering_scheme_id
protein_family = ps[0].family.slug[:3]
gen_list = []
segment_list = []
if segments is not None:
input_list = segments.split(",")
# fetch a list of all segments
protein_segments = ProteinSegment.objects.filter(partial=False).values_list('slug', flat=True)
for s in input_list:
# add to segment list
if s in protein_segments:
segment_list.append(s)
# get generic numbering object for generic positions
else:
# make sure the query works for all positions
gen_object = ResidueGenericNumberEquivalent.objects.get(label=s, scheme__id=s_slug)
gen_object.properties = {}
gen_list.append(gen_object)
# fetch all complete protein_segments
ss = ProteinSegment.objects.filter(slug__in=segment_list, partial=False)
else:
ss = ProteinSegment.objects.filter(partial=False)
if int(protein_family) < 100:
ss = [ s for s in ss if s.proteinfamily == 'GPCR']
elif protein_family == "100":
ss = [ s for s in ss if s.proteinfamily == 'Gprotein']
elif protein_family == "200":
ss = [ s for s in ss if s.proteinfamily == 'Arrestin']
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from selection into the alignment
a.load_proteins(ps)
# load generic numbers and TMs seperately
if gen_list:
a.load_segments(gen_list)
a.load_segments(ss)
# build the alignment data matrix
a.build_alignment()
a.calculate_statistics()
residue_list = []
for aa in a.full_consensus:
residue_list.append(aa.amino_acid)
# render the fasta template as string
response = render_to_string('alignment/alignment_fasta.html', {'a': a}).split("\n")
# convert the list to a dict
ali_dict = OrderedDict({})
for row in response:
if row.startswith(">"):
k = row[1:]
else:
ali_dict[k] = row
k = False
ali_dict['CONSENSUS'] = ''.join(residue_list)
# render statistics for output
if statistics == True:
feat = {}
for i, feature in enumerate(AMINO_ACID_GROUPS):
feature_stats = a.feature_stats[i]
feature_stats_clean = []
for d in feature_stats:
sub_list = [x[0] for x in d]
feature_stats_clean.append(sub_list) # remove feature frequencies
# print(feature_stats_clean)
feat[feature] = [item for sublist in feature_stats_clean for item in sublist]
for i, AA in enumerate(AMINO_ACIDS):
feature_stats = a.amino_acid_stats[i]
feature_stats_clean = []
for d in feature_stats:
sub_list = [x[0] for x in d]
feature_stats_clean.append(sub_list) # remove feature frequencies
# print(feature_stats_clean)
feat[AA] = [item for sublist in feature_stats_clean for item in sublist]
ali_dict["statistics"] = feat
return Response(ali_dict)
class FamilyAlignmentPartial(FamilyAlignment):
"""
Get a partial sequence alignment of a protein family
\n/alignment/family/{slug}/{segments}/
\n{slug} is a protein family identifier, e.g. 001_001_001
\n{segments} is a comma separated list of protein segment identifiers and/ or
generic GPCRdb numbers, e.g. TM2,TM3,ECL2,4x50
"""
class FamilyAlignmentSpecies(FamilyAlignment):
"""
Get a full sequence alignment of a protein family
\n/alignment/family/{slug}//{species}
\n{slug} is a protein family identifier, e.g. 001_001_001
\n{species} is a species identifier from Uniprot, e.g. Homo sapiens
"""
class FamilyAlignmentPartialSpecies(FamilyAlignment):
"""
Get a partial sequence alignment of a protein family
\n/alignment/family/{slug}/{segments}/{species}
\n{slug} is a protein family identifier, e.g. 001_001_001
\n{segments} is a comma separated list of protein segment identifiers and/ or
generic GPCRdb numbers, e.g. TM2,TM3,ECL2,4x50
\n{species} is a species identifier from Uniprot, e.g. Homo sapiens
"""
class ProteinSimilaritySearchAlignment(views.APIView):
"""
Get a segment sequence alignment of two or more proteins ranked by similarity
\n/alignment/similarity/{proteins}/{segments}/
\n{proteins} is a comma separated list of protein identifiers, e.g. adrb2_human,5ht2a_human,cxcr4_human,
where the first protein is the query protein and the following the proteins to compare it to
\n{segments} is a comma separated list of protein segment identifiers and/ or
generic GPCRdb numbers, e.g. TM2,TM3,ECL2,4x50
"""
def get(self, request, proteins=None, segments=None):
if proteins is not None:
protein_list = proteins.split(",")
# first in API should be reference
ps = Protein.objects.filter(sequence_type__slug='wt', entry_name__in=protein_list[1:])
reference = Protein.objects.filter(sequence_type__slug='wt', entry_name__in=[protein_list[0]])
# take the numbering scheme from the first protein
s_slug = Protein.objects.get(entry_name=protein_list[0]).residue_numbering_scheme_id
protein_family = ps[0].family.slug[:3]
gen_list = []
segment_list = []
if segments is not None:
input_list = segments.split(",")
# fetch a list of all segments
protein_segments = ProteinSegment.objects.filter(partial=False).values_list('slug', flat=True)
for s in input_list:
# add to segment list
if s in protein_segments:
segment_list.append(s)
# get generic numbering object for generic positions
else:
# make sure the query works for all positions
gen_object = ResidueGenericNumberEquivalent.objects.get(label=s, scheme__id=s_slug)
gen_object.properties = {}
gen_list.append(gen_object)
# fetch all complete protein_segments
ss = ProteinSegment.objects.filter(slug__in=segment_list, partial=False)
else:
ss = ProteinSegment.objects.filter(partial=False)
if int(protein_family) < 100:
ss = [ s for s in ss if s.proteinfamily == 'GPCR']
elif protein_family == "100":
ss = [ s for s in ss if s.proteinfamily == 'Gprotein']
elif protein_family == "200":
ss = [ s for s in ss if s.proteinfamily == 'Arrestin']
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from API into the alignment
a.load_reference_protein(reference[0])
a.load_proteins(ps)
# load generic numbers and TMs seperately
if gen_list:
a.load_segments(gen_list)
a.load_segments(ss)
# build the alignment data matrix
a.build_alignment()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity()
# render the fasta template as string
response = render_to_string('alignment/alignment_fasta.html', {'a': a}).split("\n")
# convert the list to a dict
ali_dict = {}
k = False
num = 0
for i, row in enumerate(response):
if row.startswith(">"):
k = row[1:]
elif k:
# add the query as 100 identical/similar to the beginning (like on the website)
if num == 0:
a.proteins[num].identity = 100
a.proteins[num].similarity = 100
# order dict after custom list
keyorder = ["similarity","identity","AA"]
ali_dict[k] = {"AA": row, "identity": int(str(a.proteins[num].identity).replace(" ","")),
"similarity": int(str(a.proteins[num].similarity).replace(" ",""))}
ali_dict[k] = OrderedDict(sorted(ali_dict[k].items(), key=lambda t: keyorder.index(t[0])))
num+=1
k = False
ali_dict_ordered = OrderedDict(sorted(ali_dict.items(), key=lambda x: x[1]['similarity'], reverse=True))
return Response(ali_dict_ordered)
class ProteinAlignment(views.APIView):
"""
Get a full sequence alignment of two or more proteins
\n/alignment/protein/{proteins}/
\n{proteins} is a comma separated list of protein identifiers, e.g. adrb2_human,5ht2a_human
"""
def get(self, request, proteins=None, segments=None, statistics=False):
if proteins is not None:
protein_list = proteins.split(",")
ps = Protein.objects.filter(sequence_type__slug='wt', entry_name__in=protein_list)
# take the numbering scheme from the first protein
#s_slug = Protein.objects.get(entry_name=protein_list[0]).residue_numbering_scheme_id
s_slug = ps[0].residue_numbering_scheme_id
protein_family = ps[0].family.slug[:3]
gen_list = []
segment_list = []
if segments is not None:
input_list = segments.split(",")
# fetch a list of all segments
protein_segments = ProteinSegment.objects.filter(partial=False).values_list('slug', flat=True)
for s in input_list:
# add to segment list
if s in protein_segments:
segment_list.append(s)
# get generic numbering object for generic positions
else:
gen_object = ResidueGenericNumberEquivalent.objects.get(label=s, scheme__id=s_slug)
gen_object.properties = {}
gen_list.append(gen_object)
# fetch all complete protein_segments
ss = ProteinSegment.objects.filter(slug__in=segment_list, partial=False)
else:
ss = ProteinSegment.objects.filter(partial=False)
if int(protein_family) < 100:
ss = [ s for s in ss if s.proteinfamily == 'GPCR']
elif protein_family == "100":
ss = [ s for s in ss if s.proteinfamily == 'Gprotein']
elif protein_family == "200":
ss = [ s for s in ss if s.proteinfamily == 'Arrestin']
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from selection into the alignment
a.load_proteins(ps)
# load generic numbers and TMs seperately
if gen_list:
a.load_segments(gen_list)
a.load_segments(ss)
# build the alignment data matrix
a.build_alignment()
# calculate statistics
if statistics == True:
a.calculate_statistics()
# render the fasta template as string
response = render_to_string('alignment/alignment_fasta.html', {'a': a}).split("\n")
# convert the list to a dict
ali_dict = {}
k = False
for row in response:
if row.startswith(">"):
k = row[1:]
elif k:
ali_dict[k] = row
k = False
# render statistics for output
if statistics == True:
feat = {}
for i, feature in enumerate(AMINO_ACID_GROUPS):
feature_stats = a.feature_stats[i]
feature_stats_clean = []
for d in feature_stats:
sub_list = [x[0] for x in d]
feature_stats_clean.append(sub_list) # remove feature frequencies
# print(feature_stats_clean)
feat[feature] = [item for sublist in feature_stats_clean for item in sublist]
for i, AA in enumerate(AMINO_ACIDS):
feature_stats = a.amino_acid_stats[i]
feature_stats_clean = []
for d in feature_stats:
sub_list = [x[0] for x in d]
feature_stats_clean.append(sub_list) # remove feature frequencies
# print(feature_stats_clean)
feat[AA] = [item for sublist in feature_stats_clean for item in sublist]
ali_dict["statistics"] = feat
return Response(ali_dict)
class ProteinAlignmentStatistics(ProteinAlignment):
"""
Add a /statics at the end of an alignment in order to
receive an additional residue property statistics output e.g.:
\n/alignment/protein/{proteins}/{segments}/statistics
\n{proteins} is a comma separated list of protein identifiers, e.g. adrb2_human,5ht2a_human
\n{segments} is a comma separated list of protein segment identifiers and/ or
generic GPCRdb numbers, e.g. TM2,TM3,ECL2,4x50
"""
class ProteinAlignmentPartial(ProteinAlignment):
"""
Get a partial sequence alignment of two or more proteins
\n/alignment/protein/{proteins}/{segments}/
\n{proteins} is a comma separated list of protein identifiers, e.g. adrb2_human,5ht2a_human
\n{segments} is a comma separated list of protein segment identifiers and/ or
generic GPCRdb numbers, e.g. TM2,TM3,ECL2,4x50
"""
class StructureTemplate(views.APIView):
"""
Get the most similar structure template for a protein using a 7TM alignment
\n/structure/template/{entry_name}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
"""
def get(self, request, entry_name=None, segments=None):
if entry_name is not None:
ref = Protein.objects.get(sequence_type__slug='wt', entry_name=entry_name)
structures = Structure.objects.order_by('protein_conformation__protein__parent', 'state',
'resolution').distinct('protein_conformation__protein__parent', 'state')
ps = []
for structure in structures:
ps.append(structure.protein_conformation.protein.parent)
if segments is not None:
input_list = segments.split(",")
ss = ProteinSegment.objects.filter(slug__in=input_list, partial=False)
else:
ss = ProteinSegment.objects.filter(partial=False, category='helix')
# create an alignment object
a = Alignment()
a.show_padding = False
# load data from selection into the alignment
a.load_reference_protein(ref)
a.load_proteins(ps)
a.load_segments(ss)
# build the alignment data matrix
a.build_alignment()
# calculate identity and similarity of each row compared to the reference
a.calculate_similarity()
# return the entry_name of the closest template
return Response(a.proteins[1].protein.entry_name)
class StructureTemplatePartial(StructureTemplate):
"""
Get the most similar structure template for a protein using a partial alignment
\n/structure/template/{entry_name}/{segments}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
\n{segments} is a comma separated list of protein segment identifiers, e.g. TM3,TM5,TM6
"""
class StructureAssignGenericNumbers(views.APIView):
"""
Assign generic residue numbers (Ballesteros-Weinstein and GPCRdb schemes) to an uploaded pdb file.
\n/structure/assign_generic_numbers\n
e.g.
curl -X POST -F "pdb_file=@myfile.pdb" http://gpcrdb.org/services/structure/assign_generic_numbers
"""
parser_classes = (FileUploadParser,)
renderer_classes = (PDBRenderer, )
def post(self, request):
root, ext = os.path.splitext(request.FILES['pdb_file'].name)
generic_numbering = GenericNumbering(StringIO(request.FILES['pdb_file'].file.read().decode('UTF-8',"ignore")))
out_struct = generic_numbering.assign_generic_numbers()
out_stream = StringIO()
io = PDBIO()
io.set_structure(out_struct)
io.save(out_stream)
print(len(out_stream.getvalue()))
# filename="{}_GPCRdb.pdb".format(root)
return Response(out_stream.getvalue())
class StructureSequenceParser(views.APIView):
"""
Analyze the uploaded pdb structure listing auxiliary proteins, mutations, deletions and insertions.
\n/structure/structure/parse_pdb\n
e.g.
curl -X POST -F "pdb_file=@myfile.pdb" http://gpcrdb.org/services/structure/parse_pdb
"""
parser_classes = (FileUploadParser,)
renderer_classes =(JSONRenderer)
def post(self, request):
root, ext = os.path.splitext(request.FILES['pdb_file'].name)
header = parse_pdb_header(request.FILES['pdb_file'])
parser = SequenceParser(request.FILES['pdb_file'])
json_data = OrderedDict()
json_data["header"] = header
json_data.update(parser.get_fusions())
json_data.update(parser.get_mutations())
json_data.update(parser.get_deletions())
return Response(json_data)
class StructureLigandInteractions(generics.ListAPIView):
"""
Get a list of interactions between structure and ligand
\n/structure/{pdb_code}/interaction/
\n{pdb_code} is a structure identifier from the Protein Data Bank, e.g. 2RH1
"""
serializer_class = StructureLigandInteractionSerializer
def get_queryset(self):
queryset = ResidueFragmentInteraction.objects.all()
queryset = queryset.prefetch_related('structure_ligand_pair__structure__pdb_code',
'interaction_type',
'fragment__residue__generic_number',
'fragment__residue__display_generic_number',
)
queryset = queryset.exclude(interaction_type__type='hidden').order_by('fragment__residue__sequence_number')
slug = self.kwargs.get('pdb_code')
return queryset.filter(structure_ligand_pair__structure__pdb_code__index=slug,
structure_ligand_pair__annotated=True)
class MutantList(generics.ListAPIView):
"""
Get a list of mutants of single protein instance by entry name
\n/mutant/{entry_name}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
"""
serializer_class = MutationSerializer
def get_queryset(self):
queryset = MutationRaw.objects.all()
return queryset.filter(protein=self.kwargs.get('entry_name'))
class DrugList(views.APIView):
"""
Get a list of drugs for a single protein instance by entry name
\n/drugs/{proteins}/
\n{entry_name} is a protein identifier from Uniprot, e.g. adrb2_human
"""
def get(self, request, entry_name=None):
drugs = Drugs.objects.filter(target__entry_name=entry_name).distinct()
druglist = []
for drug in drugs:
drugname = drug.name
drugtype = drug.drugtype
clinical = drug.clinicalstatus
phasedate = drug.phasedate
if clinical != '-':
status = drug.status + ' (' + drug.clinicalstatus + ', ' + phasedate + ')'
else:
status = drug.status
approval = drug.approval
indication = drug.indication
moa = drug.moa
novelty = drug.novelty
druglist.append({'name':drugname, 'approval': approval, 'indication': indication, 'status':status, 'drugtype':drugtype, 'moa':moa, 'novelty': novelty})
return Response(druglist)
|
apache-2.0
| -7,819,170,572,501,628,000
| 38.48982
| 175
| 0.611724
| false
| 4.041922
| false
| false
| false
|
Djabx/mgd
|
mgdpck/writters/cbz.py
|
1
|
1116
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
'''
A cbz writter
'''
from mgdpck import actions
import os
import mimetypes
import zipfile
class CbzWritter(actions.AbsWritter):
@classmethod
def get_name(cls):
return 'cbz'
def __init__(self, outdir):
self.outdir = outdir
self.out = None
def done(self):
if self.out:
self.out.close()
def export_book(self, lsb, chapter_min, chapter_max):
self.out_file = os.path.join(self.outdir, "{0.book.short_name}_{1.num:>03}_{2.num:>03}.cbz".format(lsb, chapter_min, chapter_max))
self.out = zipfile.ZipFile(self.out_file, "w", compression=zipfile.ZIP_DEFLATED)
def export_cover(self, lsb):
cv_path = "{0:>03}_{0:>03}_{1}{2}".format(0, 'cover',
mimetypes.guess_extension(lsb.image.mimetype))
self.out.writestr(cv_path, lsb.image.content)
def export_chapter(self, ch):
pass
def export_page(self, pa):
pa_path = "{0.chapter.num:>03}_{0.num:>03}{1}".format(pa,
mimetypes.guess_extension(pa.image.mimetype))
self.out.writestr(pa_path, pa.image.content)
actions.register_writter(CbzWritter)
|
apache-2.0
| 603,414,583,288,958,700
| 21.32
| 134
| 0.654122
| false
| 2.883721
| false
| false
| false
|
RicardoJohann/frappe
|
frappe/utils/goal.py
|
1
|
4641
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from six.moves import xrange
def get_monthly_results(goal_doctype, goal_field, date_col, filter_str, aggregation = 'sum'):
'''Get monthly aggregation values for given field of doctype'''
# TODO: move to ORM?
if(frappe.conf.db_type == 'postgres'):
month_year_format_query = '''to_char("{}", 'MM-YYYY')'''.format(date_col)
else:
month_year_format_query = 'date_format(`{}`, "%m-%Y")'.format(date_col)
conditions = ('where ' + filter_str) if filter_str else ''
results = frappe.db.sql('''SELECT {aggregation}(`{goal_field}`) AS {goal_field},
{month_year_format_query} AS month_year
FROM `{table_name}` {conditions}
GROUP BY month_year'''
.format(
aggregation=aggregation,
goal_field=goal_field,
month_year_format_query=month_year_format_query,
table_name="tab" + goal_doctype,
conditions=conditions
), as_dict=True)
month_to_value_dict = {}
for d in results:
month_to_value_dict[d['month_year']] = d[goal_field]
return month_to_value_dict
@frappe.whitelist()
def get_monthly_goal_graph_data(title, doctype, docname, goal_value_field, goal_total_field, goal_history_field,
goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum"):
'''
Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype
:param title: Graph title
:param doctype: doctype of graph doc
:param docname: of the doc to set the graph in
:param goal_value_field: goal field of doctype
:param goal_total_field: current month value field of doctype
:param goal_history_field: cached history field
:param goal_doctype: doctype the goal is based on
:param goal_doctype_link: doctype link field in goal_doctype
:param goal_field: field from which the goal is calculated
:param filter_str: where clause condition
:param aggregation: a value like 'count', 'sum', 'avg'
:return: dict of graph data
'''
from frappe.utils.formatters import format_value
import json
meta = frappe.get_meta(doctype)
doc = frappe.get_doc(doctype, docname)
goal = doc.get(goal_value_field)
formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc)
current_month_value = doc.get(goal_total_field)
formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc)
from frappe.utils import today, getdate, formatdate, add_months
current_month_year = formatdate(today(), "MM-yyyy")
history = doc.get(goal_history_field)
try:
month_to_value_dict = json.loads(history) if history and '{' in history else None
except ValueError:
month_to_value_dict = None
if month_to_value_dict is None:
doc_filter = (goal_doctype_link + " = '" + docname + "'") if doctype != goal_doctype else ''
if filter_str:
doc_filter += ' and ' + filter_str if doc_filter else filter_str
month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation)
frappe.db.set_value(doctype, docname, goal_history_field, json.dumps(month_to_value_dict))
month_to_value_dict[current_month_year] = current_month_value
months = []
months_formatted = []
values = []
values_formatted = []
for i in range(0, 12):
date_value = add_months(today(), -i)
month_value = formatdate(date_value, "MM-yyyy")
month_word = getdate(date_value).strftime('%b')
month_year = getdate(date_value).strftime('%B') + ', ' + getdate(date_value).strftime('%Y')
months.insert(0, month_word)
months_formatted.insert(0, month_year)
if month_value in month_to_value_dict:
val = month_to_value_dict[month_value]
else:
val = 0
values.insert(0, val)
values_formatted.insert(0, format_value(val, meta.get_field(goal_total_field), doc))
y_markers = []
summary_values = [
{
'title': _("This month"),
'color': '#ffa00a',
'value': formatted_value
}
]
if float(goal) > 0:
y_markers = [
{
'label': _("Goal"),
'lineType': "dashed",
'value': goal
},
]
summary_values += [
{
'title': _("Goal"),
'color': '#5e64ff',
'value': formatted_goal
},
{
'title': _("Completed"),
'color': '#28a745',
'value': str(int(round(float(current_month_value)/float(goal)*100))) + "%"
}
]
data = {
'title': title,
# 'subtitle':
'data': {
'datasets': [
{
'values': values,
'formatted': values_formatted
}
],
'labels': months,
'yMarkers': y_markers
},
'summary': summary_values,
}
return data
|
mit
| 6,556,498,908,767,743,000
| 29.333333
| 112
| 0.676578
| false
| 3.023453
| false
| false
| false
|
nmarincic/numbasom
|
numbasom/numbasom.py
|
1
|
8667
|
from numba import jit
import numpy as np
import math
import collections
from timeit import default_timer as timer
@jit(nopython=True)
def normalize(data, min_val=0, max_val=1):
no_vectors, dim = data.shape
D = np.empty((no_vectors,dim), dtype=np.float64)
inf = 1.7976931348623157e+308
min_arr = np.empty(dim, dtype=np.float64)
min_arr[:] = inf
max_arr = np.empty(dim, dtype=np.float64)
max_arr[:] = -inf
diff = np.empty(dim, dtype=np.float64)
for vec in range(no_vectors):
for d in range(dim):
val = data[vec,d]
if val < min_arr[d]:
min_arr[d] = val
if val > max_arr[d]:
max_arr[d] = val
for d in range(dim):
diff[d] = max_arr[d] - min_arr[d]
for i in range(no_vectors):
for j in range(dim):
if diff[j] != 0:
D[i,j] = (data[i, j] - min_arr[j]) / diff[j]
else:
D[i,j] = 0
return D
@jit(nopython=True)
def normalize_with_mutate(data, min_val=0, max_val=1):
no_vectors, dim = data.shape
#D = np.empty((no_vectors,dim), dtype=np.float64)
inf = 1.7976931348623157e+308
min_arr = np.empty(dim, dtype=np.float64)
min_arr[:] = inf
max_arr = np.empty(dim, dtype=np.float64)
max_arr[:] = -inf
diff = np.empty(dim, dtype=np.float64)
for vec in range(no_vectors):
for d in range(dim):
val = data[vec,d]
if val < min_arr[d]:
min_arr[d] = val
if val > max_arr[d]:
max_arr[d] = val
for d in range(dim):
diff[d] = max_arr[d] - min_arr[d]
for i in range(no_vectors):
for j in range(dim):
data[i,j] = (data[i, j] - min_arr[j]) / diff[j]
def pairwise(X):
M = X.shape[0]
N = X.shape[1]
D = np.empty((M, M), dtype=np.float64)
for i in range(M):
for j in range(M):
d = 0.0
for k in range(N):
tmp = X[i, k] - X[j, k]
d += tmp * tmp
D[i, j] = np.sqrt(d)
return D
def pairwise_squared(X):
M = X.shape[0]
N = X.shape[1]
# type will depend on the size of the matrix
D = np.empty((M, M), dtype=np.uint32)
for i in range(M):
for j in range(M):
d = 0.0
for k in range(N):
tmp = X[i, k] - X[j, k]
d += tmp * tmp
D[i, j] = d
return D
@jit(nopython=True)
def random_lattice(som_size, dimensionality):
X, Y, Z = som_size[0], som_size[1], dimensionality
D = np.empty((X,Y,Z), dtype=np.float64)
for x in range(X):
for y in range(Y):
for z in range(Z):
D[x,y,z] = np.random.random()
return D
@jit
def get_all_BMU_indexes(BMU, X, Y):
BMUx, BMUy = BMU[0], BMU[1]
BMU2x, BMU3x, BMU4x = BMU[0], BMU[0], BMU[0]
BMU2y, BMU3y, BMU4y = BMU[1], BMU[1], BMU[1]
if BMUx > X / 2:
BMU2x = BMUx - X
else:
BMU2x = BMUx + X
if BMUy > Y / 2:
BMU3y = BMUy - Y
else:
BMU3y = BMUy + Y
BMU4x = BMU2x
BMU4y = BMU3y
return BMU, (BMU2x, BMU2y), (BMU3x, BMU3y), (BMU4x, BMU4y)
@jit(nopython=True)
def som_calc(som_size, num_iterations, data_scaled, is_torus=False):
#data_scaled = normalize(data)
initial_radius = (max(som_size[0],som_size[1])/2)**2
time_constant = num_iterations/math.log(initial_radius)
start_lrate = 0.1
lattice = random_lattice(som_size, data_scaled.shape[1])
datalen = len(data_scaled)
X, Y, Z = lattice.shape
for current_iteration in range(num_iterations):
current_radius = initial_radius * math.exp(-current_iteration/time_constant)
current_lrate = start_lrate * math.exp(-current_iteration/num_iterations)
rand_input = np.random.randint(datalen)
rand_vector = data_scaled[rand_input]
BMU_dist = 1.7976931348623157e+308
BMU = (0,0)
for x in range(X):
for y in range(Y):
d = 0.0
for z in range(Z):
val = lattice[x,y,z]-rand_vector[z]
valsqr = val * val
d += valsqr
if d < BMU_dist:
BMU_dist = d
BMU = (x,y)
if is_torus:
BMUs = get_all_BMU_indexes(BMU, X, Y)
for BMU in BMUs:
adapt(lattice, rand_vector, BMU, current_radius, current_lrate)
else:
adapt(lattice, rand_vector, BMU, current_radius, current_lrate)
return lattice
@jit(nopython=True)
def adapt(lattice, rand_vector, BMU, current_radius, current_lrate):
X, Y, Z = lattice.shape
for x in range(X):
for y in range(Y):
a = x-BMU[0]
b = y-BMU[1]
d = a*a + b*b
if d < current_radius:
up = d * d
down = current_radius * current_radius
res = -up / (2 * down)
influence = math.exp(res)
for z in range(Z):
diff = (rand_vector[z] - lattice[x,y,z]) * influence * current_lrate
lattice[x,y,z] += diff
@jit(nopython=True)
def euclidean(vec1, vec2):
L = vec1.shape[0]
dist = 0
for l in range(L):
val = vec2[l] - vec1[l]
valsqr = val * val
dist += valsqr
return math.sqrt(dist)
@jit(nopython=True)
def euclidean_squared(vec1, vec2):
L = vec1.shape[0]
dist = 0
for l in range(L):
val = vec2[l] - vec1[l]
valsqr = val * val
dist += valsqr
return dist
@jit(nopython=True)
def u_matrix(lattice):
X, Y, Z = lattice.shape
u_values = np.empty((X,Y), dtype=np.float64)
for y in range(Y):
for x in range(X):
current = lattice[x,y]
dist = 0
num_neigh = 0
# left
if x-1 >= 0:
#middle
vec = lattice[x-1,y]
dist += euclidean(current, vec)
num_neigh += 1
if y - 1 >= 0:
#sup
vec = lattice[x-1, y-1]
dist += euclidean(current, vec)
num_neigh += 1
if y + 1 < Y:
# down
vec = lattice[x-1,y+1]
dist += euclidean(current, vec)
num_neigh += 1
# middle
if y - 1 >= 0:
# up
vec = lattice[x,y-1]
dist += euclidean(current, vec)
num_neigh += 1
# down
if y + 1 < Y:
vec = lattice[x,y+1]
dist += euclidean(current, vec)
num_neigh += 1
# right
if x + 1 < X:
# middle
vec = lattice[x+1,y]
dist += euclidean(current, vec)
num_neigh += 1
if y - 1 >= 0:
#up
vec = lattice[x+1,y-1]
dist += euclidean(current, vec)
num_neigh += 1
if y + 1 < lattice.shape[1]:
# down
vec = lattice[x+1,y+1]
dist += euclidean(current, vec)
num_neigh += 1
u_values[x,y] = dist / num_neigh
return u_values
def project_on_som(data, lattice, additional_list=None, data_scaled=False):
start = timer()
if data_scaled:
data_scaled = data
else:
data_scaled = normalize(data)
#create all keys
projected = collections.defaultdict(list)
X, Y, Z = lattice.shape
for x in range(X):
for y in range(Y):
projected[(x,y)]
# fill keys
for index, vec in enumerate(data_scaled):
winning_cell, wi = find_closest(index, vec, lattice)
projected[winning_cell].append(wi)
if additional_list:
final = {key: [additional_list[v] for v in value] for key, value in projected.items()}
else:
final = {key: [data[v] for v in value] for key, value in projected.items()}
end = timer()
print("Projecting on SOM took: %f seconds." %(end - start))
return final
@jit(nopython=True)
def find_closest_data_index(lattice_vec, data):
min_val = 1.7976931348623157e+308
winning_index = -1
data_len = len(data)
for i in range(data_len):
data_point = data[i]
dist = euclidean_squared(lattice_vec,data_point)
if dist < min_val:
min_val = dist
winning_index = i
return winning_index
def lattice_closest_vectors(data, lattice, additional_list=None, data_scaled=False):
start = timer()
if data_scaled:
data_scaled = data
else:
data_scaled = normalize(data)
X, Y, Z = lattice.shape
# create dictionary
projected = {}
# fill keys
for x in range(X):
for y in range(Y):
lattice_vec = lattice[x,y]
winning_index = find_closest_data_index(lattice_vec, data_scaled)
if additional_list:
projected[(x,y)] = [additional_list[winning_index]]
else:
projected[(x,y)] = data[winning_index]
end = timer()
print("Finding closest data points took: %f seconds." %(end - start))
return projected
@jit(nopython=True)
def find_closest(index, vec, lattice):
X, Y, Z = lattice.shape
min_val = 1.7976931348623157e+308
win_index = -1
win_cell = (-1,-1)
for x in range(X):
for y in range(Y):
dist = euclidean_squared(vec, lattice[x,y])
if dist < min_val:
min_val = dist
win_index = index
win_cell = (x,y)
return win_cell, win_index
def som(som_size, num_iterations, data, is_torus=False, is_scaled=False):
data_scaled = data
if not is_scaled:
start = timer()
data_scaled = normalize(data)
end = timer()
print("Data scaling took: %f seconds." %(end - start))
start = timer()
lattice = som_calc(som_size, num_iterations, data_scaled, is_torus)
end = timer()
print("SOM training took: %f seconds." %(end - start))
return lattice
def save_lattice(lattice, filename):
np.save(filename, lattice)
print ("SOM lattice saved at %s" %filename)
def load_lattice(filename):
lattice = np.load(filename)
print ("SOM lattice loaded from %s" %filename)
return lattice
|
mit
| 1,146,145,510,830,641,200
| 22.81044
| 88
| 0.621207
| false
| 2.410178
| false
| false
| false
|
Buchhold/QLever
|
misc/move_language_into_relation.py
|
1
|
1046
|
import argparse
import sys
__author__ = 'buchholb'
parser = argparse.ArgumentParser()
parser.add_argument('--nt',
type=str,
help='n-triple file.',
required=True)
def writeNtFileToStdout(nt):
for line in open(nt):
cols = line.strip('\n').split('\t')
if len(cols) != 4 or cols[3] != '.':
print('Ignoring malformed line: ' + line, file=sys.stderr)
else:
lang_start = cols[2].rfind('"@');
if lang_start > 0 and cols[2].rfind('"', lang_start + 1) == -1:
lang = cols[2][lang_start + 2:]
if cols[1][-1] == '>':
cols[1] = cols[1][:-1] + '.' + lang + '>'
else:
cols[1] += ('.' + lang)
cols[2] = cols[2][:lang_start + 1]
print('\t'.join([cols[0], cols[1], cols[2], '.']))
def main():
args = vars(parser.parse_args())
nt = args['nt']
writeNtFileToStdout(nt)
if __name__ == '__main__':
main()
|
apache-2.0
| 8,025,750,356,437,480,000
| 26.526316
| 75
| 0.448375
| false
| 3.521886
| false
| false
| false
|
google-research/language
|
language/xsp/model/constants.py
|
1
|
1574
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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.
"""Contains constants required for the model."""
# TODO(alanesuhr): These are used in convert_to_tf_examples.py.
# Use these constants instead of strings there.
# These constants define the keys used for the TFRecords.
COPIABLE_INPUT_KEY = 'copiable_input'
ALIGNED_KEY = 'utterance_schema_alignment'
SEGMENT_ID_KEY = 'segment_ids'
FOREIGN_KEY_KEY = 'indicates_foreign_key'
SOURCE_WORDPIECES_KEY = 'source_wordpieces'
SOURCE_LEN_KEY = 'source_len'
LANGUAGE_KEY = 'language'
REGION_KEY = 'region'
TAG_KEY = 'tag'
OUTPUT_TYPE_KEY = 'type'
WEIGHT_KEY = 'weight'
TARGET_ACTION_TYPES_KEY = 'target_action_types'
TARGET_ACTION_IDS_KEY = 'target_action_ids'
TARGET_LEN_KEY = 'target_len'
SCORES_KEY = 'scores'
# Symbol IDs.
TARGET_START_SYMBOL_ID = 2
TARGET_END_SYMBOL_ID = 1
PAD_SYMBOL_ID = 0
GENERATE_ACTION = 1
COPY_ACTION = 2
NUM_RESERVED_OUTPUT_SYMBOLS = 3
PREDICTED_ACTION_TYPES = 'predicted_action_types'
PREDICTED_ACTION_IDS = 'predicted_action_ids'
|
apache-2.0
| -5,873,433,957,893,586,000
| 30.48
| 74
| 0.747776
| false
| 3.238683
| false
| false
| false
|
cangermueller/deepcpg
|
deepcpg/data/dna.py
|
1
|
2502
|
"""Functions for representing DNA sequences."""
from __future__ import division
from __future__ import print_function
from collections import OrderedDict
import numpy as np
from six.moves import range
# Mapping of nucleotides to integers
CHAR_TO_INT = OrderedDict([('A', 0), ('T', 1), ('G', 2), ('C', 3), ('N', 4)])
# Mapping of integers to nucleotides
INT_TO_CHAR = {v: k for k, v in CHAR_TO_INT.items()}
def get_alphabet(special=False, reverse=False):
"""Return char->int alphabet.
Parameters
----------
special: bool
If `True`, remove special 'N' character.
reverse: bool
If `True`, return int->char instead of char->int alphabet.
Returns
-------
OrderedDict
DNA alphabet.
"""
alpha = OrderedDict(CHAR_TO_INT)
if not special:
del alpha['N']
if reverse:
alpha = {v: k for k, v in alpha.items()}
return alpha
def char_to_int(seq):
"""Translate chars of single sequence `seq` to ints.
Parameters
----------
seq: str
DNA sequence.
Returns
-------
list
Integer-encoded `seq`.
"""
return [CHAR_TO_INT[x] for x in seq.upper()]
def int_to_char(seq, join=True):
"""Translate ints of single sequence `seq` to chars.
Parameters
----------
seq: list
Integers of sequences
join: bool
If `True` joint characters to `str`.
Returns
-------
If `join=True`, `str`, otherwise list of chars.
"""
t = [INT_TO_CHAR[x] for x in seq]
if join:
t = ''.join(t)
return t
def int_to_onehot(seqs, dim=4):
"""One-hot encodes array of integer sequences.
Takes array [nb_seq, seq_len] of integer sequence end encodes them one-hot.
Special nucleotides (int > 4) will be encoded as [0, 0, 0, 0].
Paramters
---------
seqs: :class:`numpy.ndarray`
[nb_seq, seq_len] :class:`numpy.ndarray` of integer sequences.
dim: int
Number of nucleotides
Returns
-------
:class:`numpy.ndarray`
[nb_seq, seq_len, dim] :class:`numpy.ndarray` of one-hot encoded
sequences.
"""
seqs = np.atleast_2d(np.asarray(seqs))
n = seqs.shape[0]
l = seqs.shape[1]
enc_seqs = np.zeros((n, l, dim), dtype='int8')
for i in range(dim):
t = seqs == i
enc_seqs[t, i] = 1
return enc_seqs
def onehot_to_int(seqs, axis=-1):
"""Translates one-hot sequences to integer sequences."""
return seqs.argmax(axis=axis)
|
mit
| -3,484,228,904,838,836,700
| 22.383178
| 79
| 0.583933
| false
| 3.460581
| false
| false
| false
|
pynamodb/PynamoDB
|
tests/test_discriminator.py
|
1
|
6828
|
import pytest
from pynamodb.attributes import DiscriminatorAttribute
from pynamodb.attributes import DynamicMapAttribute
from pynamodb.attributes import ListAttribute
from pynamodb.attributes import MapAttribute
from pynamodb.attributes import NumberAttribute
from pynamodb.attributes import UnicodeAttribute
from pynamodb.models import Model
class_name = lambda cls: cls.__name__
class TypedValue(MapAttribute):
_cls = DiscriminatorAttribute(attr_name = 'cls')
name = UnicodeAttribute()
class NumberValue(TypedValue, discriminator=class_name):
value = NumberAttribute()
class StringValue(TypedValue, discriminator=class_name):
value = UnicodeAttribute()
class RenamedValue(TypedValue, discriminator='custom_name'):
value = UnicodeAttribute()
class DiscriminatorTestModel(Model, discriminator='Parent'):
class Meta:
host = 'http://localhost:8000'
table_name = 'test'
hash_key = UnicodeAttribute(hash_key=True)
value = TypedValue()
values = ListAttribute(of=TypedValue)
type = DiscriminatorAttribute()
class ChildModel(DiscriminatorTestModel, discriminator='Child'):
value = UnicodeAttribute()
class DynamicSubclassedMapAttribute(DynamicMapAttribute):
string_attr = UnicodeAttribute()
class DynamicMapDiscriminatorTestModel(Model, discriminator='Parent'):
class Meta:
host = 'http://localhost:8000'
table_name = 'test'
hash_key = UnicodeAttribute(hash_key=True)
value = DynamicSubclassedMapAttribute(default=dict)
type = DiscriminatorAttribute()
class DynamicMapDiscriminatorChildTestModel(DynamicMapDiscriminatorTestModel, discriminator='Child'):
value = UnicodeAttribute()
class TestDiscriminatorAttribute:
def test_serialize(self):
dtm = DiscriminatorTestModel()
dtm.hash_key = 'foo'
dtm.value = StringValue(name='foo', value='Hello')
dtm.values = [NumberValue(name='bar', value=5), RenamedValue(name='baz', value='World')]
assert dtm.serialize() == {
'hash_key': {'S': 'foo'},
'type': {'S': 'Parent'},
'value': {'M': {'cls': {'S': 'StringValue'}, 'name': {'S': 'foo'}, 'value': {'S': 'Hello'}}},
'values': {'L': [
{'M': {'cls': {'S': 'NumberValue'}, 'name': {'S': 'bar'}, 'value': {'N': '5'}}},
{'M': {'cls': {'S': 'custom_name'}, 'name': {'S': 'baz'}, 'value': {'S': 'World'}}}
]}
}
def test_deserialize(self):
item = {
'hash_key': {'S': 'foo'},
'type': {'S': 'Parent'},
'value': {'M': {'cls': {'S': 'StringValue'}, 'name': {'S': 'foo'}, 'value': {'S': 'Hello'}}},
'values': {'L': [
{'M': {'cls': {'S': 'NumberValue'}, 'name': {'S': 'bar'}, 'value': {'N': '5'}}},
{'M': {'cls': {'S': 'custom_name'}, 'name': {'S': 'baz'}, 'value': {'S': 'World'}}}
]}
}
dtm = DiscriminatorTestModel.from_raw_data(item)
assert dtm.hash_key == 'foo'
assert dtm.value.value == 'Hello'
assert dtm.values[0].value == 5
assert dtm.values[1].value == 'World'
def test_condition_expression(self):
condition = DiscriminatorTestModel.value._cls == RenamedValue
placeholder_names, expression_attribute_values = {}, {}
expression = condition.serialize(placeholder_names, expression_attribute_values)
assert expression == "#0.#1 = :0"
assert placeholder_names == {'value': '#0', 'cls': '#1'}
assert expression_attribute_values == {':0': {'S': 'custom_name'}}
def test_multiple_discriminator_values(self):
class TestAttribute(MapAttribute, discriminator='new_value'):
cls = DiscriminatorAttribute()
TestAttribute.cls.register_class(TestAttribute, 'old_value')
# ensure the first registered value is used during serialization
assert TestAttribute.cls.get_discriminator(TestAttribute) == 'new_value'
assert TestAttribute.cls.serialize(TestAttribute) == 'new_value'
# ensure the second registered value can be used to deserialize
assert TestAttribute.cls.deserialize('old_value') == TestAttribute
assert TestAttribute.cls.deserialize('new_value') == TestAttribute
def test_multiple_discriminator_classes(self):
with pytest.raises(ValueError):
# fail when attempting to register a class with an existing discriminator value
class RenamedValue2(TypedValue, discriminator='custom_name'):
pass
class TestDiscriminatorModel:
def test_serialize(self):
cm = ChildModel()
cm.hash_key = 'foo'
cm.value = 'bar'
cm.values = []
assert cm.serialize() == {
'hash_key': {'S': 'foo'},
'type': {'S': 'Child'},
'value': {'S': 'bar'},
'values': {'L': []}
}
def test_deserialize(self):
item = {
'hash_key': {'S': 'foo'},
'type': {'S': 'Child'},
'value': {'S': 'bar'},
'values': {'L': []}
}
cm = DiscriminatorTestModel.from_raw_data(item)
assert isinstance(cm, ChildModel)
assert cm.hash_key == 'foo'
assert cm.value == 'bar'
class TestDynamicDiscriminatorModel:
def test_serialize_parent(self):
m = DynamicMapDiscriminatorTestModel()
m.hash_key = 'foo'
m.value.string_attr = 'foostr'
m.value.bar_attribute = 3
assert m.serialize() == {
'hash_key': {'S': 'foo'},
'type': {'S': 'Parent'},
'value': {'M': {'string_attr': {'S': 'foostr'}, 'bar_attribute': {'N': '3'}}},
}
def test_deserialize_parent(self):
item = {
'hash_key': {'S': 'foo'},
'type': {'S': 'Parent'},
'value': {
'M': {'string_attr': {'S': 'foostr'}, 'bar_attribute': {'N': '3'}}
}
}
m = DynamicMapDiscriminatorTestModel.from_raw_data(item)
assert m.hash_key == 'foo'
assert m.value
assert m.value.string_attr == 'foostr'
assert m.value.bar_attribute == 3
def test_serialize_child(self):
m = DynamicMapDiscriminatorChildTestModel()
m.hash_key = 'foo'
m.value = 'string val'
assert m.serialize() == {
'hash_key': {'S': 'foo'},
'type': {'S': 'Child'},
'value': {'S': 'string val'}
}
def test_deserialize_child(self):
item = {
'hash_key': {'S': 'foo'},
'type': {'S': 'Child'},
'value': {'S': 'string val'}
}
m = DynamicMapDiscriminatorChildTestModel.from_raw_data(item)
assert m.hash_key == 'foo'
assert m.value == 'string val'
|
mit
| -3,047,368,666,517,998,000
| 33.836735
| 105
| 0.57645
| false
| 3.776549
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.