input
stringlengths
0
1.96k
context
stringlengths
1.23k
257k
answers
listlengths
1
5
length
int32
399
40.5k
dataset
stringclasses
10 values
language
stringclasses
5 values
all_classes
listlengths
_id
stringlengths
48
48
/** * Copyright (C) 2010 Orbeon, Inc. * * This program 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 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. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xml; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.util.SecureUtils; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; import javax.xml.transform.Source; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.security.MessageDigest; /** * This digester is based on some existing public document (not sure which). There are some * changes though. It is not clear anymore why we used that document as a base, as this is * purely internal. * * The bottom line is that the digest should change whenever the infoset of the source XML * document changes. */ public class DigestContentHandler implements XMLReceiver { private static final int ELEMENT_CODE = Node.ELEMENT_NODE; private static final int ATTRIBUTE_CODE = Node.ATTRIBUTE_NODE; private static final int TEXT_CODE = Node.TEXT_NODE; private static final int PROCESSING_INSTRUCTION_CODE = Node.PROCESSING_INSTRUCTION_NODE; private static final int NAMESPACE_CODE = 0XAA01; // some code that is none of the above private static final int COMMENT_CODE = 0XAA02; // some code that is none of the above /** * 4/6/2005 d : Previously we were using String.getBytes( "UnicodeBigUnmarked" ). ( Believe * the code was copied from RFC 2803 ). This first tries to get a java.nio.Charset with * the name if this fails it uses a sun.io.CharToByteConverter. * Now in the case of "UnicodeBigUnmarked" there is no such Charset so a * CharToByteConverter, utf-16be, is used. Unfortunately this negative lookup is expensive. * ( Costing us a full second in the 50thread/512MB test. ) * The solution, of course, is just to use get the appropriate Charset and hold on to it. */ private static final Charset utf16BECharset = Charset.forName("UTF-16BE"); /** * Encoder has state and therefore cannot be shared across threads. */ private final CharsetEncoder charEncoder = utf16BECharset.newEncoder(); private java.nio.CharBuffer charBuff = java.nio.CharBuffer.allocate(64); private java.nio.ByteBuffer byteBuff = java.nio.ByteBuffer.allocate(128); private final MessageDigest digest = SecureUtils.defaultMessageDigest(); /** * Compute a digest for a SAX source. */ public static byte[] getDigest(Source source) { final DigestContentHandler digester = new DigestContentHandler(); TransformerUtils.sourceToSAX(source, digester); return digester.getResult(); } private void ensureCharBuffRemaining(final int size) { if (charBuff.remaining() < size) { final int cpcty = (charBuff.capacity() + size) * 2; final java.nio.CharBuffer newChBuf = java.nio.CharBuffer.allocate(cpcty); newChBuf.put(charBuff); charBuff = newChBuf; } } private void updateWithCharBuf() { final int reqSize = (int) charEncoder.maxBytesPerChar() * charBuff.position(); if (byteBuff.capacity() < reqSize) { byteBuff = java.nio.ByteBuffer.allocate(2 * reqSize); } // Make ready for read charBuff.flip(); final CoderResult cr = charEncoder.encode(charBuff, byteBuff, true); try { if (cr.isError()) cr.throwException(); // Make ready for read byteBuff.flip(); final byte[] byts = byteBuff.array(); final int len = byteBuff.remaining(); final int strt = byteBuff.arrayOffset(); digest.update(byts, strt, len); } catch (final CharacterCodingException e) { throw new OXFException(e); } catch (java.nio.BufferOverflowException e) { throw new OXFException(e); } catch (java.nio.BufferUnderflowException e) { throw new OXFException(e); } finally { // Make ready for write charBuff.clear(); byteBuff.clear(); } } private void updateWith(final String s) { addToCharBuff(s); updateWithCharBuf(); } private void updateWith(final char[] chArr, final int ofst, final int len) { ensureCharBuffRemaining(len); charBuff.put(chArr, ofst, len); updateWithCharBuf(); } private void addToCharBuff(final char c) { ensureCharBuffRemaining(1); charBuff.put(c); } private void addToCharBuff(final String s) { final int size = s.length(); ensureCharBuffRemaining(size); charBuff.put(s); } public byte[] getResult() { return digest.digest(); } public void setDocumentLocator(Locator locator) { } public void startDocument() throws SAXException { charBuff.clear(); byteBuff.clear(); charEncoder.reset(); } public void endDocument() throws SAXException { } public void startPrefixMapping(String prefix, String uri) throws SAXException { digest.update((byte) ((NAMESPACE_CODE >> 24) & 0xff)); digest.update((byte) ((NAMESPACE_CODE >> 16) & 0xff)); digest.update((byte) ((NAMESPACE_CODE >> 8) & 0xff)); digest.update((byte) (NAMESPACE_CODE & 0xff)); updateWith(prefix); digest.update((byte) 0); digest.update((byte) 0); updateWith(uri); digest.update((byte) 0); digest.update((byte) 0); } public void endPrefixMapping(String prefix) throws SAXException { } public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { digest.update((byte) ((ELEMENT_CODE >> 24) & 0xff)); digest.update((byte) ((ELEMENT_CODE >> 16) & 0xff)); digest.update((byte) ((ELEMENT_CODE >> 8) & 0xff)); digest.update((byte) (ELEMENT_CODE & 0xff)); addToCharBuff('{'); addToCharBuff(namespaceURI); addToCharBuff('}'); addToCharBuff(localName); updateWithCharBuf(); digest.update((byte) 0); digest.update((byte) 0); int attCount = atts.getLength(); digest.update((byte) ((attCount >> 24) & 0xff)); digest.update((byte) ((attCount >> 16) & 0xff)); digest.update((byte) ((attCount >> 8) & 0xff)); digest.update((byte) (attCount & 0xff)); for (int i = 0; i < attCount; i++) { digest.update((byte) ((ATTRIBUTE_CODE >> 24) & 0xff)); digest.update((byte) ((ATTRIBUTE_CODE >> 16) & 0xff)); digest.update((byte) ((ATTRIBUTE_CODE >> 8) & 0xff)); digest.update((byte) (ATTRIBUTE_CODE & 0xff)); final String attURI = atts.getURI(i); final String attNam = atts.getLocalName(i); addToCharBuff('{'); addToCharBuff(attURI); addToCharBuff('}'); addToCharBuff(attNam); updateWithCharBuf(); digest.update((byte) 0); digest.update((byte) 0); final String val = atts.getValue(i); updateWith(val); } } public void endElement(String namespaceURI, String localName, String qName) throws SAXException { } public void characters(char ch[], int start, int length) throws SAXException { digest.update((byte) ((TEXT_CODE >> 24) & 0xff)); digest.update((byte) ((TEXT_CODE >> 16) & 0xff)); digest.update((byte) ((TEXT_CODE >> 8) & 0xff));
[ " digest.update((byte) (TEXT_CODE & 0xff));" ]
865
lcc
java
null
d130622298f175eb038e14cf3cab0d504c020de19bc3eab8
"""Tools for use in AppleEvent clients and servers: conversion between AE types and python types pack(x) converts a Python object to an AEDesc object unpack(desc) does the reverse coerce(x, wanted_sample) coerces a python object to another python object """ # # This code was originally written by Guido, and modified/extended by Jack # to include the various types that were missing. The reference used is # Apple Event Registry, chapter 9. # import struct import string import types from string import strip from types import * from Carbon import AE from Carbon.AppleEvents import * import MacOS import Carbon.File import StringIO import aetypes from aetypes import mkenum, ObjectSpecifier import os # These ones seem to be missing from AppleEvents # (they're in AERegistry.h) #typeColorTable = 'clrt' #typeDrawingArea = 'cdrw' #typePixelMap = 'cpix' #typePixelMapMinus = 'tpmm' #typeRotation = 'trot' #typeTextStyles = 'tsty' #typeStyledText = 'STXT' #typeAEText = 'tTXT' #typeEnumeration = 'enum' # # Some AE types are immedeately coerced into something # we like better (and which is equivalent) # unpacker_coercions = { typeComp : typeFloat, typeColorTable : typeAEList, typeDrawingArea : typeAERecord, typeFixed : typeFloat, typeExtended : typeFloat, typePixelMap : typeAERecord, typeRotation : typeAERecord, typeStyledText : typeAERecord, typeTextStyles : typeAERecord, }; # # Some python types we need in the packer: # AEDescType = AE.AEDescType FSSType = Carbon.File.FSSpecType FSRefType = Carbon.File.FSRefType AliasType = Carbon.File.AliasType def packkey(ae, key, value): if hasattr(key, 'which'): keystr = key.which elif hasattr(key, 'want'): keystr = key.want else: keystr = key ae.AEPutParamDesc(keystr, pack(value)) def pack(x, forcetype = None): """Pack a python object into an AE descriptor""" if forcetype: if type(x) is StringType: return AE.AECreateDesc(forcetype, x) else: return pack(x).AECoerceDesc(forcetype) if x == None: return AE.AECreateDesc('null', '') if isinstance(x, AEDescType): return x if isinstance(x, FSSType): return AE.AECreateDesc('fss ', x.data) if isinstance(x, FSRefType): return AE.AECreateDesc('fsrf', x.data) if isinstance(x, AliasType): return AE.AECreateDesc('alis', x.data) if isinstance(x, IntType): return AE.AECreateDesc('long', struct.pack('l', x)) if isinstance(x, FloatType): return AE.AECreateDesc('doub', struct.pack('d', x)) if isinstance(x, StringType): return AE.AECreateDesc('TEXT', x) if isinstance(x, UnicodeType): data = x.encode('utf16') if data[:2] == '\xfe\xff': data = data[2:] return AE.AECreateDesc('utxt', data) if isinstance(x, ListType): list = AE.AECreateList('', 0) for item in x: list.AEPutDesc(0, pack(item)) return list if isinstance(x, DictionaryType): record = AE.AECreateList('', 1) for key, value in x.items(): packkey(record, key, value) #record.AEPutParamDesc(key, pack(value)) return record if type(x) == types.ClassType and issubclass(x, ObjectSpecifier): # Note: we are getting a class object here, not an instance return AE.AECreateDesc('type', x.want) if hasattr(x, '__aepack__'): return x.__aepack__() if hasattr(x, 'which'): return AE.AECreateDesc('TEXT', x.which) if hasattr(x, 'want'): return AE.AECreateDesc('TEXT', x.want) return AE.AECreateDesc('TEXT', repr(x)) # Copout def unpack(desc, formodulename=""): """Unpack an AE descriptor to a python object""" t = desc.type if unpacker_coercions.has_key(t): desc = desc.AECoerceDesc(unpacker_coercions[t]) t = desc.type # This is a guess by Jack.... if t == typeAEList: l = [] for i in range(desc.AECountItems()): keyword, item = desc.AEGetNthDesc(i+1, '****') l.append(unpack(item, formodulename)) return l if t == typeAERecord: d = {} for i in range(desc.AECountItems()): keyword, item = desc.AEGetNthDesc(i+1, '****') d[keyword] = unpack(item, formodulename) return d if t == typeAEText: record = desc.AECoerceDesc('reco') return mkaetext(unpack(record, formodulename)) if t == typeAlias: return Carbon.File.Alias(rawdata=desc.data) # typeAppleEvent returned as unknown if t == typeBoolean: return struct.unpack('b', desc.data)[0] if t == typeChar: return desc.data if t == typeUnicodeText: return unicode(desc.data, 'utf16') # typeColorTable coerced to typeAEList # typeComp coerced to extended # typeData returned as unknown # typeDrawingArea coerced to typeAERecord if t == typeEnumeration: return mkenum(desc.data) # typeEPS returned as unknown if t == typeFalse: return 0 if t == typeFloat: data = desc.data return struct.unpack('d', data)[0] if t == typeFSS: return Carbon.File.FSSpec(rawdata=desc.data) if t == typeFSRef: return Carbon.File.FSRef(rawdata=desc.data) if t == typeInsertionLoc: record = desc.AECoerceDesc('reco') return mkinsertionloc(unpack(record, formodulename)) # typeInteger equal to typeLongInteger if t == typeIntlText: script, language = struct.unpack('hh', desc.data[:4]) return aetypes.IntlText(script, language, desc.data[4:]) if t == typeIntlWritingCode: script, language = struct.unpack('hh', desc.data) return aetypes.IntlWritingCode(script, language) if t == typeKeyword: return mkkeyword(desc.data) if t == typeLongInteger: return struct.unpack('l', desc.data)[0] if t == typeLongDateTime: a, b = struct.unpack('lL', desc.data) return (long(a) << 32) + b if t == typeNull: return None if t == typeMagnitude: v = struct.unpack('l', desc.data) if v < 0: v = 0x100000000L + v return v if t == typeObjectSpecifier: record = desc.AECoerceDesc('reco') # If we have been told the name of the module we are unpacking aedescs for, # we can attempt to create the right type of python object from that module. if formodulename: return mkobjectfrommodule(unpack(record, formodulename), formodulename) return mkobject(unpack(record, formodulename)) # typePict returned as unknown # typePixelMap coerced to typeAERecord # typePixelMapMinus returned as unknown # typeProcessSerialNumber returned as unknown if t == typeQDPoint: v, h = struct.unpack('hh', desc.data) return aetypes.QDPoint(v, h) if t == typeQDRectangle: v0, h0, v1, h1 = struct.unpack('hhhh', desc.data) return aetypes.QDRectangle(v0, h0, v1, h1) if t == typeRGBColor: r, g, b = struct.unpack('hhh', desc.data) return aetypes.RGBColor(r, g, b) # typeRotation coerced to typeAERecord # typeScrapStyles returned as unknown # typeSessionID returned as unknown if t == typeShortFloat: return struct.unpack('f', desc.data)[0] if t == typeShortInteger: return struct.unpack('h', desc.data)[0] # typeSMFloat identical to typeShortFloat # typeSMInt indetical to typeShortInt # typeStyledText coerced to typeAERecord if t == typeTargetID: return mktargetid(desc.data) # typeTextStyles coerced to typeAERecord # typeTIFF returned as unknown if t == typeTrue: return 1 if t == typeType: return mktype(desc.data, formodulename) # # The following are special # if t == 'rang': record = desc.AECoerceDesc('reco') return mkrange(unpack(record, formodulename)) if t == 'cmpd': record = desc.AECoerceDesc('reco') return mkcomparison(unpack(record, formodulename)) if t == 'logi': record = desc.AECoerceDesc('reco') return mklogical(unpack(record, formodulename)) return mkunknown(desc.type, desc.data) def coerce(data, egdata): """Coerce a python object to another type using the AE coercers""" pdata = pack(data) pegdata = pack(egdata) pdata = pdata.AECoerceDesc(pegdata.type) return unpack(pdata) # # Helper routines for unpack # def mktargetid(data): sessionID = getlong(data[:4]) name = mkppcportrec(data[4:4+72]) location = mklocationnamerec(data[76:76+36]) rcvrName = mkppcportrec(data[112:112+72]) return sessionID, name, location, rcvrName def mkppcportrec(rec): namescript = getword(rec[:2]) name = getpstr(rec[2:2+33]) portkind = getword(rec[36:38]) if portkind == 1: ctor = rec[38:42] type = rec[42:46] identity = (ctor, type) else: identity = getpstr(rec[38:38+33]) return namescript, name, portkind, identity def mklocationnamerec(rec): kind = getword(rec[:2]) stuff = rec[2:] if kind == 0: stuff = None if kind == 2: stuff = getpstr(stuff) return kind, stuff def mkunknown(type, data): return aetypes.Unknown(type, data) def getpstr(s): return s[1:1+ord(s[0])] def getlong(s): return (ord(s[0])<<24) | (ord(s[1])<<16) | (ord(s[2])<<8) | ord(s[3]) def getword(s): return (ord(s[0])<<8) | (ord(s[1])<<0) def mkkeyword(keyword): return aetypes.Keyword(keyword) def mkrange(dict):
[ " return aetypes.Range(dict['star'], dict['stop'])" ]
1,045
lcc
python
null
6632f438b48e38612c7af5be064f73e8a4b86ead00fbda69
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace CalendarSyncPlus.Web.WebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) {
[ " if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))" ]
1,053
lcc
csharp
null
6cde737d77f75e2d7bba19ebf78653bae352413d2a95770b
#This file is part of Tryton. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. import gtk import parser import gettext import gobject from itertools import islice, cycle from tryton.common import MODELACCESS from tryton.common.date_widget import DateEntry _ = gettext.gettext class TreeView(gtk.TreeView): def __init__(self): super(TreeView, self).__init__() self.cells = {} def next_column(self, path, column=None, _sign=1): columns = self.get_columns() if column is None: column = columns[-1 * _sign] model = self.get_model() record = model.get_value(model.get_iter(path), 0) if _sign < 0: columns.reverse() current_idx = columns.index(column) + 1 for column in islice(cycle(columns), current_idx, len(columns) + current_idx): if not column.name: continue field = record[column.name] field.state_set(record, states=('readonly', 'invisible')) invisible = field.get_state_attrs(record).get('invisible', False) readonly = field.get_state_attrs(record).get('readonly', False) if not (invisible or readonly): break return column def prev_column(self, path, column=None): return self.next_column(path, column=column, _sign=-1) class EditableTreeView(TreeView): leaving_record_events = (gtk.keysyms.Up, gtk.keysyms.Down, gtk.keysyms.Return) leaving_events = leaving_record_events + (gtk.keysyms.Tab, gtk.keysyms.ISO_Left_Tab, gtk.keysyms.KP_Enter) def __init__(self, position): super(EditableTreeView, self).__init__() self.editable = position def on_quit_cell(self, current_record, fieldname, value, callback=None): field = current_record[fieldname] cell = self.cells[fieldname] # The value has not changed and is valid ... do nothing. if value == cell.get_textual_value(current_record) \ and field.validate(current_record): if callback: callback() return try: cell.value_from_text(current_record, value, callback=callback) except parser.UnsettableColumn: return def on_open_remote(self, current_record, fieldname, create, value, entry=None, callback=None): cell = self.cells[fieldname] if value != cell.get_textual_value(current_record) or not value: changed = True else: changed = False try: cell.open_remote(current_record, create, changed, value, callback=callback) except NotImplementedError: pass def on_create_line(self): access = MODELACCESS[self.screen.model_name] model = self.get_model() if not access['create'] or (self.screen.size_limit is not None and (len(model) >= self.screen.size_limit >= 0)): return if self.editable == 'top': method = model.prepend else: method = model.append new_record = model.group.new() res = method(new_record) return res def set_cursor(self, path, focus_column=None, start_editing=False): self.grab_focus() if focus_column and (focus_column._type in ('boolean')): start_editing = False super(EditableTreeView, self).set_cursor(path, focus_column, start_editing) def set_value(self): path, column = self.get_cursor() model = self.get_model() if not path or not column or not column.name: return True record = model.get_value(model.get_iter(path), 0) field = record[column.name] if hasattr(field, 'editabletree_entry'): entry = field.editabletree_entry if isinstance(entry, gtk.Entry): txt = entry.get_text() else: txt = entry.get_active_text() self.on_quit_cell(record, column.name, txt) return True def on_keypressed(self, entry, event): path, column = self.get_cursor() model = self.get_model() record = model.get_value(model.get_iter(path), 0) leaving = False if event.keyval == gtk.keysyms.Right: if isinstance(entry, gtk.Entry): if entry.get_position() >= \ len(entry.get_text().decode('utf-8')) \ and not entry.get_selection_bounds(): leaving = True else: leaving = True elif event.keyval == gtk.keysyms.Left: if isinstance(entry, gtk.Entry): if entry.get_position() <= 0 \ and not entry.get_selection_bounds(): leaving = True else: leaving = True if event.keyval in self.leaving_events or leaving: if isinstance(entry, gtk.Entry): if isinstance(entry, DateEntry): entry.date_get() txt = entry.get_text() else: txt = entry.get_active_text() keyval = event.keyval entry.handler_block(entry.editing_done_id) def callback(): entry.handler_unblock(entry.editing_done_id) field = record[column.name] # Must wait the edited entry came back in valid state if field.validate(record): if (keyval in (gtk.keysyms.Tab, gtk.keysyms.KP_Enter) or (keyval == gtk.keysyms.Right and leaving)): gobject.idle_add(self.set_cursor, path, self.next_column(path, column), True) elif (keyval == gtk.keysyms.ISO_Left_Tab or (keyval == gtk.keysyms.Left and leaving)): gobject.idle_add(self.set_cursor, path, self.prev_column(path, column), True) elif keyval in self.leaving_record_events: fields = self.cells.keys() if not record.validate(fields): invalid_fields = record.invalid_fields col = None for col in self.get_columns(): if col.name in invalid_fields: break gobject.idle_add(self.set_cursor, path, col, True) return if ((self.screen.pre_validate and not record.pre_validate()) or (not self.screen.parent and not record.save())): gobject.idle_add(self.set_cursor, path, column, True) return entry.handler_block(entry.editing_done_id) if keyval == gtk.keysyms.Up: self._key_up(path, model, column) elif keyval == gtk.keysyms.Down: self._key_down(path, model, column) elif keyval == gtk.keysyms.Return: if self.editable == 'top': new_path = self._key_up(path, model) else: new_path = self._key_down(path, model) gobject.idle_add(self.set_cursor, new_path, self.next_column(new_path), True) entry.handler_unblock(entry.editing_done_id) else: gobject.idle_add(self.set_cursor, path, column, True) self.on_quit_cell(record, column.name, txt, callback=callback) return True elif event.keyval in (gtk.keysyms.F3, gtk.keysyms.F2): if isinstance(entry, gtk.Entry): value = entry.get_text() else:
[ " value = entry.get_active_text()" ]
586
lcc
python
null
716049fd0d1692b85479651b13974c96045e6d05f8fe7fe3
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.management.subsystems; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanReference; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.ManagedList; import org.springframework.core.Ordered; import org.springframework.core.PriorityOrdered; /** * A {@link BeanFactoryPostProcessor} that upgrades old-style Spring overrides that add location paths to the * <code>repository-properties</code> or <code>hibernateConfigProperties</code> beans to instead add these paths to the * <code>global-properties</code> bean. To avoid the warning messages output by this class, new property overrides * should be added to alfresco-global.properties without overriding any bean definitions. * * @author dward */ public class LegacyConfigPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered { /** The name of the bean that, in new configurations, holds all properties */ private static final String BEAN_NAME_GLOBAL_PROPERTIES = "global-properties"; /** The name of the bean that expands repository properties. These should now be defaulted from global-properties. */ private static final String BEAN_NAME_REPOSITORY_PROPERTIES = "repository-properties"; /** The name of the bean that holds hibernate properties. These should now be overriden by global-properties. */ private static final String BEAN_NAME_HIBERNATE_PROPERTIES = "hibernateConfigProperties"; /** The name of the property on a Spring property loader that holds a list of property file location paths. */ private static final String PROPERTY_LOCATIONS = "locations"; /** The name of the property on a Spring property loader that holds a local property map. */ private static final String PROPERTY_PROPERTIES = "properties"; /** The logger. */ private static Log logger = LogFactory.getLog(LegacyConfigPostProcessor.class); /* * (non-Javadoc) * @see * org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework. * beans.factory.config.ConfigurableListableBeanFactory) */ @SuppressWarnings("unchecked") public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { try { // Look up the global-properties bean and its locations list MutablePropertyValues globalProperties = beanFactory.getBeanDefinition( LegacyConfigPostProcessor.BEAN_NAME_GLOBAL_PROPERTIES).getPropertyValues(); PropertyValue pv = globalProperties.getPropertyValue(LegacyConfigPostProcessor.PROPERTY_LOCATIONS); Collection<Object> globalPropertyLocations; Object value; // Use the locations list if there is one, otherwise associate a new empty list if (pv != null && (value = pv.getValue()) != null && value instanceof Collection) { globalPropertyLocations = (Collection<Object>) value; } else { globalPropertyLocations = new ManagedList(10); globalProperties .addPropertyValue(LegacyConfigPostProcessor.PROPERTY_LOCATIONS, globalPropertyLocations); } // Move location paths added to repository-properties MutablePropertyValues repositoryProperties = processLocations(beanFactory, globalPropertyLocations, LegacyConfigPostProcessor.BEAN_NAME_REPOSITORY_PROPERTIES, new String[] { "classpath:alfresco/version.properties" }); // Fix up additional properties to enforce correct order of precedence repositoryProperties.addPropertyValue("ignoreUnresolvablePlaceholders", Boolean.TRUE); repositoryProperties.addPropertyValue("localOverride", Boolean.FALSE); repositoryProperties.addPropertyValue("valueSeparator", null); repositoryProperties.addPropertyValue("systemPropertiesModeName", "SYSTEM_PROPERTIES_MODE_NEVER"); // Move location paths added to hibernateConfigProperties MutablePropertyValues hibernateProperties = processLocations(beanFactory, globalPropertyLocations, LegacyConfigPostProcessor.BEAN_NAME_HIBERNATE_PROPERTIES, new String[] { "classpath:alfresco/domain/hibernate-cfg.properties", "classpath*:alfresco/enterprise/cache/hibernate-cfg.properties" }); // Fix up additional properties to enforce correct order of precedence hibernateProperties.addPropertyValue("localOverride", Boolean.TRUE); // Because Spring gets all post processors in one shot, the bean may already have been created. Let's try to // fix it up! PropertyPlaceholderConfigurer repositoryConfigurer = (PropertyPlaceholderConfigurer) beanFactory .getSingleton(LegacyConfigPostProcessor.BEAN_NAME_REPOSITORY_PROPERTIES); if (repositoryConfigurer != null) { // Reset locations list repositoryConfigurer.setLocations(null); // Invalidate cached merged bean definitions ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition( LegacyConfigPostProcessor.BEAN_NAME_REPOSITORY_PROPERTIES, beanFactory .getBeanDefinition(LegacyConfigPostProcessor.BEAN_NAME_REPOSITORY_PROPERTIES)); // Reconfigure the bean according to its new definition beanFactory.configureBean(repositoryConfigurer, LegacyConfigPostProcessor.BEAN_NAME_REPOSITORY_PROPERTIES); } } catch (NoSuchBeanDefinitionException e) { // Ignore and continue } } /** * Given a bean name (assumed to implement {@link org.springframework.core.io.support.PropertiesLoaderSupport}) * checks whether it already references the <code>global-properties</code> bean. If not, 'upgrades' the bean by * appending all additional resources it mentions in its <code>locations</code> property to * <code>globalPropertyLocations</code>, except for those resources mentioned in <code>newLocations</code>. A * reference to <code>global-properties</code> will then be added and the resource list in * <code>newLocations<code> will then become the new <code>locations</code> list for the bean. * * @param beanFactory * the bean factory * @param globalPropertyLocations * the list of global property locations to be appended to * @param beanName * the bean name * @param newLocations * the new locations to be set on the bean * @return the mutable property values */ @SuppressWarnings("unchecked") private MutablePropertyValues processLocations(ConfigurableListableBeanFactory beanFactory, Collection<Object> globalPropertyLocations, String beanName, String[] newLocations) { // Get the bean an check its existing properties value MutablePropertyValues beanProperties = beanFactory.getBeanDefinition(beanName).getPropertyValues(); PropertyValue pv = beanProperties.getPropertyValue(LegacyConfigPostProcessor.PROPERTY_PROPERTIES); Object value; // If the properties value already references the global-properties bean, we have nothing else to do. Otherwise, // we have to 'upgrade' the bean definition. if (pv == null || (value = pv.getValue()) == null || !(value instanceof BeanReference) || ((BeanReference) value).getBeanName().equals(LegacyConfigPostProcessor.BEAN_NAME_GLOBAL_PROPERTIES)) { // Convert the array of new locations to a managed list of type string values, so that it is // compatible with a bean definition Collection<Object> newLocationList = new ManagedList(newLocations.length); if (newLocations != null && newLocations.length > 0) { for (String preserveLocation : newLocations) { newLocationList.add(new TypedStringValue(preserveLocation)); } } // If there is currently a locations list, process it pv = beanProperties.getPropertyValue(LegacyConfigPostProcessor.PROPERTY_LOCATIONS); if (pv != null && (value = pv.getValue()) != null && value instanceof Collection) { Collection<Object> locations = (Collection<Object>) value; // Compute the set of locations that need to be added to globalPropertyLocations (preserving order) and // warn about each Set<Object> addedLocations = new LinkedHashSet<Object>(locations); addedLocations.removeAll(globalPropertyLocations); addedLocations.removeAll(newLocationList); for (Object location : addedLocations) { LegacyConfigPostProcessor.logger.warn("Legacy configuration detected: adding " + (location instanceof TypedStringValue ? ((TypedStringValue) location).getValue() : location.toString()) + " to global-properties definition"); globalPropertyLocations.add(location); } } // Ensure the bean now references global-properties beanProperties.addPropertyValue(LegacyConfigPostProcessor.PROPERTY_PROPERTIES, new RuntimeBeanReference( LegacyConfigPostProcessor.BEAN_NAME_GLOBAL_PROPERTIES)); // Ensure the new location list is now set on the bean
[ " if (newLocationList.size() > 0)" ]
961
lcc
java
null
daa27a5d67ba9d011a6296ae7e7effeac588540b3e61d3e5
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Nimbis Services, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # DOCUMENTATION = """ module: htpasswd version_added: "1.3" short_description: manage user files for basic authentication description: - Add and remove username/password entries in a password file using htpasswd. - This is used by web servers such as Apache and Nginx for basic authentication. options: path: required: true aliases: [ dest, destfile ] description: - Path to the file that contains the usernames and passwords name: required: true aliases: [ username ] description: - User name to add or remove password: required: false description: - Password associated with user. - Must be specified if user does not exist yet. crypt_scheme: required: false choices: ["apr_md5_crypt", "des_crypt", "ldap_sha1", "plaintext"] default: "apr_md5_crypt" description: - Encryption scheme to be used. state: required: false choices: [ present, absent ] default: "present" description: - Whether the user entry should be present or not create: required: false choices: [ "yes", "no" ] default: "yes" description: - Used with C(state=present). If specified, the file will be created if it does not already exist. If set to "no", will fail if the file does not exist notes: - "This module depends on the I(passlib) Python library, which needs to be installed on all target systems." - "On Debian, Ubuntu, or Fedora: install I(python-passlib)." - "On RHEL or CentOS: Enable EPEL, then install I(python-passlib)." requires: [ passlib>=1.6 ] author: "Lorin Hochstein (@lorin)" """ EXAMPLES = """ # Add a user to a password file and ensure permissions are set - htpasswd: path=/etc/nginx/passwdfile name=janedoe password=9s36?;fyNp owner=root group=www-data mode=0640 # Remove a user from a password file - htpasswd: path=/etc/apache2/passwdfile name=foobar state=absent """ import os import tempfile from distutils.version import StrictVersion try: from passlib.apache import HtpasswdFile import passlib except ImportError: passlib_installed = False else: passlib_installed = True def create_missing_directories(dest): destpath = os.path.dirname(dest) if not os.path.exists(destpath): os.makedirs(destpath) def present(dest, username, password, crypt_scheme, create, check_mode): """ Ensures user is present Returns (msg, changed) """ if not os.path.exists(dest): if not create: raise ValueError('Destination %s does not exist' % dest) if check_mode: return ("Create %s" % dest, True) create_missing_directories(dest) if StrictVersion(passlib.__version__) >= StrictVersion('1.6'): ht = HtpasswdFile(dest, new=True, default_scheme=crypt_scheme) else: ht = HtpasswdFile(dest, autoload=False, default=crypt_scheme) if getattr(ht, 'set_password', None): ht.set_password(username, password) else: ht.update(username, password) ht.save() return ("Created %s and added %s" % (dest, username), True) else: if StrictVersion(passlib.__version__) >= StrictVersion('1.6'): ht = HtpasswdFile(dest, new=False, default_scheme=crypt_scheme) else: ht = HtpasswdFile(dest, default=crypt_scheme) found = None if getattr(ht, 'check_password', None): found = ht.check_password(username, password) else: found = ht.verify(username, password) if found: return ("%s already present" % username, False) else: if not check_mode: if getattr(ht, 'set_password', None): ht.set_password(username, password) else: ht.update(username, password) ht.save() return ("Add/update %s" % username, True) def absent(dest, username, check_mode): """ Ensures user is absent Returns (msg, changed) """ if not os.path.exists(dest): raise ValueError("%s does not exists" % dest) if StrictVersion(passlib.__version__) >= StrictVersion('1.6'): ht = HtpasswdFile(dest, new=False) else: ht = HtpasswdFile(dest) if username not in ht.users(): return ("%s not present" % username, False) else: if not check_mode: ht.delete(username) ht.save() return ("Remove %s" % username, True) def check_file_attrs(module, changed, message): file_args = module.load_file_common_arguments(module.params) if module.set_fs_attributes_if_different(file_args, False): if changed: message += " and " changed = True message += "ownership, perms or SE linux context changed" return message, changed def main(): arg_spec = dict( path=dict(required=True, aliases=["dest", "destfile"]), name=dict(required=True, aliases=["username"]), password=dict(required=False, default=None), crypt_scheme=dict(required=False, default=None), state=dict(required=False, default="present"), create=dict(type='bool', default='yes'), ) module = AnsibleModule(argument_spec=arg_spec, add_file_common_args=True, supports_check_mode=True) path = module.params['path'] username = module.params['name'] password = module.params['password'] crypt_scheme = module.params['crypt_scheme'] state = module.params['state'] create = module.params['create'] check_mode = module.check_mode if not passlib_installed: module.fail_json(msg="This module requires the passlib Python library") # Check file for blank lines in effort to avoid "need more than 1 value to unpack" error. try: f = open(path, "r") except IOError: # No preexisting file to remove blank lines from f = None else: try:
[ " lines = f.readlines()" ]
744
lcc
python
null
a32e9a8e3ff6ea4c2599a33d5345c01decf2e4c9913e970a
#region license /* MediaFoundationLib - Provide access to MediaFoundation interfaces via .NET Copyright (C) 2007 http://mfnet.sourceforge.net This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #endregion // This entire file only exists to work around bugs in Media Foundation. The core problem // is that there are some objects in MF that don't correctly support QueryInterface. In c++ // this isn't a problem, since if you tell c++ that something is a pointer to an interface, // it just believes you. In fact, that's one of the places where c++ gets its performance: // it doesn't check anything. // In .Net, it checks. And the way it checks is that every time it receives an interfaces // from unmanaged code, it does a couple of QI calls on it. First it does a QI for IUnknown. // Second it does a QI for the specific interface it is supposed to be (ie IMFMediaSink or // whatever). // Since c++ *doesn't* check, oftentimes the first people to even try to call QI on some of // MF's objects are c# programmers. And, not surprisingly, sometimes the first time code is // run, it doesn't work correctly. // The only way you can work around it is to change the definition of the method from // IMFMediaSink (or whatever interface MF is trying to pass you) to IntPtr. Of course, // that limits what you can do with it. You can't call methods on an IntPtr. // Something to keep in mind is that while the work-around involves changing the interface, // the problem isn't in the interface, it is in the object that implements the inteface. // This means that while the inteface may experience problems on one object, it may work // correctly on another object. If you are unclear on the differences between an interface // and an object, it's time to hit the books. // In W7, MS has fixed a few of these issues that were reported in Vista. The problem // is that even if they are fixed in W7, if your program also needs to run on Vista, you // still have to use the work-arounds. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Security; using MediaFoundation.Misc; using MediaFoundation.EVR; namespace MediaFoundation.Alt { #region Bugs in Vista and W7 [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("FA993888-4383-415A-A930-DD472A8CF6F7")] public interface IMFGetServiceAlt { [PreserveSig] int GetService( [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IntPtr ppvObject ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("FA993889-4383-415A-A930-DD472A8CF6F7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMFTopologyServiceLookupAlt { [PreserveSig] int LookupService( [In] MFServiceLookupType type, [In] int dwIndex, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.SysInt)] IntPtr[] ppvObjects, [In, Out] ref int pnObjects ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("FA99388A-4383-415A-A930-DD472A8CF6F7"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMFTopologyServiceLookupClientAlt { [PreserveSig] int InitServicePointers( IntPtr pLookup ); [PreserveSig] int ReleaseServicePointers(); } #endregion #region Bugs in Vista that appear to be fixed in W7 public class MFExternAlt { [DllImport("MFPlat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity] public static extern int MFCreateEventQueue( out IMFMediaEventQueueAlt ppMediaEventQueue ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("2CD0BD52-BCD5-4B89-B62C-EADC0C031E7D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMFMediaEventGeneratorAlt { [PreserveSig] int GetEvent( [In] MFEventFlag dwFlags, [MarshalAs(UnmanagedType.Interface)] out IMFMediaEvent ppEvent ); [PreserveSig] int BeginGetEvent( //[In, MarshalAs(UnmanagedType.Interface)] IMFAsyncCallback pCallback, IntPtr pCallback, [In, MarshalAs(UnmanagedType.IUnknown)] object o ); [PreserveSig] int EndGetEvent( //IMFAsyncResult pResult, IntPtr pResult, out IMFMediaEvent ppEvent ); [PreserveSig] int QueueEvent( [In] MediaEventType met, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidExtendedType, [In] int hrStatus, [In, MarshalAs(UnmanagedType.LPStruct)] ConstPropVariant pvValue ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("D182108F-4EC6-443F-AA42-A71106EC825F")] public interface IMFMediaStreamAlt : IMFMediaEventGeneratorAlt { #region IMFMediaEventGeneratorAlt methods [PreserveSig] new int GetEvent( [In] MFEventFlag dwFlags, [MarshalAs(UnmanagedType.Interface)] out IMFMediaEvent ppEvent ); [PreserveSig] new int BeginGetEvent( //[In, MarshalAs(UnmanagedType.Interface)] IMFAsyncCallback pCallback, IntPtr p1, [In, MarshalAs(UnmanagedType.IUnknown)] object o ); [PreserveSig] new int EndGetEvent( //IMFAsyncResult pResult, IntPtr pResult, out IMFMediaEvent ppEvent ); [PreserveSig] new int QueueEvent( [In] MediaEventType met, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidExtendedType, [In] int hrStatus, [In, MarshalAs(UnmanagedType.LPStruct)] ConstPropVariant pvValue ); #endregion [PreserveSig] int GetMediaSource( [MarshalAs(UnmanagedType.Interface)] out IMFMediaSource ppMediaSource ); [PreserveSig] int GetStreamDescriptor( [MarshalAs(UnmanagedType.Interface)] out IMFStreamDescriptor ppStreamDescriptor ); [PreserveSig] int RequestSample( [In, MarshalAs(UnmanagedType.IUnknown)] object pToken ); } [ComImport, System.Security.SuppressUnmanagedCodeSecurity, Guid("36F846FC-2256-48B6-B58E-E2B638316581"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMFMediaEventQueueAlt { [PreserveSig] int GetEvent( [In] MFEventFlag dwFlags, [MarshalAs(UnmanagedType.Interface)] out IMFMediaEvent ppEvent ); [PreserveSig] int BeginGetEvent( IntPtr pCallBack, //[In, MarshalAs(UnmanagedType.Interface)] IMFAsyncCallback pCallback, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnkState ); [PreserveSig] int EndGetEvent( IntPtr p1, //[In, MarshalAs(UnmanagedType.Interface)] IMFAsyncResult pResult, [MarshalAs(UnmanagedType.Interface)] out IMFMediaEvent ppEvent ); [PreserveSig] int QueueEvent( [In, MarshalAs(UnmanagedType.Interface)] IMFMediaEvent pEvent ); [PreserveSig] int QueueEventParamVar( [In] MediaEventType met, [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidExtendedType, [In, MarshalAs(UnmanagedType.Error)] int hrStatus, [In, MarshalAs(UnmanagedType.LPStruct)] ConstPropVariant pvValue ); [PreserveSig] int QueueEventParamUnk( [In] MediaEventType met,
[ " [In, MarshalAs(UnmanagedType.LPStruct)] Guid guidExtendedType," ]
848
lcc
csharp
null
0101b11c0d92563f34753effab4ccc713d10d886c00ee990
/* * Copyright (C) 2018. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any 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, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at support@openlattice.com * */ package com.openlattice.datastore.directory.controllers; import com.auth0.client.mgmt.ManagementAPI; import com.auth0.exception.Auth0Exception; import com.auth0.json.mgmt.users.User; import com.codahale.metrics.annotation.Timed; import com.openlattice.assembler.Assembler; import com.openlattice.authorization.*; import com.openlattice.authorization.securable.SecurableObjectType; import com.openlattice.directory.MaterializedViewAccount; import com.openlattice.directory.PrincipalApi; import com.openlattice.directory.UserDirectoryService; import com.openlattice.directory.pojo.Auth0UserBasic; import com.openlattice.directory.pojo.DirectedAclKeys; import com.openlattice.organization.roles.Role; import com.openlattice.organizations.HazelcastOrganizationService; import com.openlattice.organizations.roles.SecurePrincipalsManager; import com.openlattice.users.Auth0SyncService; import com.openlattice.users.Auth0UtilsKt; import org.springframework.http.MediaType; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.annotation.*; import javax.inject.Inject; import java.util.EnumSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.Preconditions.checkNotNull; @RestController @RequestMapping( PrincipalApi.CONTROLLER ) public class PrincipalDirectoryController implements PrincipalApi, AuthorizingComponent { @Inject private DbCredentialService dbCredService; @Inject private UserDirectoryService userDirectoryService; @Inject private SecurePrincipalsManager spm; @Inject private AuthorizationManager authorizations; @Inject private ManagementAPI managementApi; @Inject private Auth0SyncService syncService; @Inject private HazelcastOrganizationService organizationService; @Inject private Assembler assembler; @Timed @Override @RequestMapping( method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE ) public SecurablePrincipal getSecurablePrincipal( @RequestBody Principal principal ) { AclKey aclKey = spm.lookup( principal ); if ( !principal.getType().equals( PrincipalType.USER ) ) { ensureReadAccess( aclKey ); } return spm.getSecurablePrincipal( aclKey ); } @Timed @Override @RequestMapping( path = USERS, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE ) public Map<String, User> getAllUsers() { return userDirectoryService.getAllUsers(); } @Timed @Override @RequestMapping( path = { ROLES + CURRENT }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE ) public Set<SecurablePrincipal> getCurrentRoles() { return Principals.getCurrentPrincipals() .stream() .filter( principal -> principal.getType().equals( PrincipalType.ROLE ) ) .map( spm::lookup ) .filter( Objects::nonNull ) .map( aclKey -> spm.getSecurablePrincipal( aclKey ) ) .collect( Collectors.toSet() ); } @Timed @Override @RequestMapping( path = ROLES, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE ) public Map<AclKey, Role> getAvailableRoles() { return authorizations.getAuthorizedObjectsOfType( Principals.getCurrentPrincipals(), SecurableObjectType.Role, EnumSet.of( Permission.READ ) ) .map( AclKey::new ) .collect( Collectors .toMap( Function.identity(), aclKey -> (Role) spm.getSecurablePrincipal( aclKey ) ) ); } @Timed @Override @RequestMapping( path = USERS + USER_ID_PATH, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE ) public User getUser( @PathVariable( USER_ID ) String userId ) { ensureAdminAccess(); return userDirectoryService.getUser( userId ); } @Timed @Override @RequestMapping( path = SYNC, method = RequestMethod.GET ) public Void syncCallingUser() { /* * Important note: getCurrentUser() reads the principal id directly from auth token. * * This is safe since token has been validated and has an auth0 assigned unique id. * * It is very important that this is the *first* call for a new user. */ Principal principal = checkNotNull( Principals.getCurrentUser() ); try { final var user = Auth0UtilsKt.getUser( managementApi, principal.getId() ); syncService.syncUser( user ); } catch ( IllegalArgumentException | Auth0Exception e ) { throw new BadCredentialsException( "Unable to retrieve user profile information from auth0", e ); } return null; } @Timed @Override @RequestMapping( path = DB, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE ) public MaterializedViewAccount getMaterializedViewAccount() { return dbCredService.getDbCredential( Principals.getCurrentSecurablePrincipal() ); } @Timed @Override @RequestMapping( path = DB + CREDENTIAL, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE ) public MaterializedViewAccount regenerateCredential() { var sp = Principals.getCurrentSecurablePrincipal(); return assembler.rollIntegrationAccount( sp.getId(), sp.getPrincipalType() ); } @Timed @Override @GetMapping( path = USERS + SEARCH + SEARCH_QUERY_PATH, produces = MediaType.APPLICATION_JSON_VALUE ) public Map<String, Auth0UserBasic> searchAllUsers( @PathVariable( SEARCH_QUERY ) String searchQuery ) { String wildcardSearchQuery = searchQuery + "*"; return userDirectoryService.searchAllUsers( wildcardSearchQuery ); } @Timed @Override @GetMapping( path = USERS + SEARCH_EMAIL + EMAIL_SEARCH_QUERY_PATH, produces = MediaType.APPLICATION_JSON_VALUE ) public Map<String, Auth0UserBasic> searchAllUsersByEmail( @PathVariable( SEARCH_QUERY ) String emailSearchQuery ) { // to search by an exact email, the search query must be in this format: email.raw:"hristo@openlattice.com" // https://auth0.com/docs/api/management/v2/user-search#search-by-email String exactEmailSearchQuery = "email.raw:\"" + emailSearchQuery + "\""; return userDirectoryService.searchAllUsers( exactEmailSearchQuery ); } @Override public AuthorizationManager getAuthorizationManager() { return authorizations; } @Timed @Override @PostMapping( path = UPDATE, consumes = MediaType.APPLICATION_JSON_VALUE ) public Void addPrincipalToPrincipal( @RequestBody DirectedAclKeys directedAclKeys ) {
[ " ensureWriteAccess( directedAclKeys.getTarget() );" ]
695
lcc
java
null
be8b544961199f01b0f2942229db2d1da0ff394e0ca9e9eb
#!/usr/bin/env python """Pluggable module for tests that verify NOTIFY bodies. Copyright (C) 2015, Digium, Inc. John Bigelow <jbigelow@digium.com> This program is free software, distributed under the terms of the GNU General Public License Version 2. """ import sys import logging import xml.etree.ElementTree as ET import re sys.path.append('lib/python') from asterisk.pcap import VOIPListener from twisted.internet import reactor LOGGER = logging.getLogger(__name__) class BodyCheck(VOIPListener): """SIP notify listener and expected results generator. A test module that observes incoming SIP notifies and generates the expected results for the body of each. """ def __init__(self, module_config, test_object): """Constructor Arguments: module_config Dictionary containing test configuration test_object The test object for the running test. """ self.set_pcap_defaults(module_config) VOIPListener.__init__(self, module_config, test_object) self.test_object = test_object self.token = test_object.create_fail_token("Haven't handled all " "expected NOTIFY packets.") self.expected_config = module_config['expected_body'] self.expected_notifies = int(module_config['expected_notifies']) self.body_type = module_config['expected_body_type'] self.notify_count = 0 if self.body_type.upper() not in ('PIDF', 'XPIDF'): msg = "Body type of '{0}' not supported." raise Exception(msg.format(self.body_type)) if self.expected_config.get('namespaces') is not None: if self.expected_config['namespaces'].get('default') is None: msg = "Namespaces configuration does not include a 'default'." raise Exception(msg) # Add calback for SIP packets self.add_callback('SIP', self.packet_handler) def gen_expected_data(self): """Generate expected data results. Generates a single dictionary containing the expected results for a body. Returns: Dictionary of expected results. """ expected_data = {} # Use full tags if we have namespaces. if self.expected_config.get('namespaces') is not None: full_tags = self.gen_full_tags() else: full_tags = self.expected_config['tags'] # Get expected attributes corresponding to the notify body received. attribs = self.expected_config['attributes'][self.notify_count - 1] text = self.expected_config.get('text') # Get expected text corresponding to the notify body received. if text is not None: text = text[self.notify_count - 1] # Build dict of the expected results for full_tag in full_tags: expected_data[full_tag] = {} for tag in attribs.keys(): if tag not in full_tag: continue expected_data[full_tag]['attribs'] = attribs[tag] try: for tag in text.keys(): if tag not in full_tag: continue expected_data[full_tag]['text'] = text[tag] except AttributeError: pass return expected_data def gen_full_tags(self): """Generate fully qualified element tags. This generates fully qualified element tags by prefixing the tag name with it's corresponding namespace that is enclosed in curly braces. This is so our expected tags will properly match ElementTree tags. The format for an Element tag is: {<namespace>}<tag name> Returns: List of full tag names. """ full_tags = [] namespaces = self.expected_config['namespaces'] for tag in self.expected_config['tags']: try: prefix, tag = tag.split(':') namespace = '{' + namespaces[prefix] + '}' except ValueError: namespace = '{' + namespaces['default'] + '}' except KeyError as keyerr: msg = "Key {0} not found in namespace configuration for tag." raise Exception(msg.format(keyerr)) full_tags.append("{0}{1}".format(namespace, tag)) return full_tags def set_pcap_defaults(self, module_config): """Set default PcapListener config that isn't explicitly overridden. Arguments: module_config Dict of module configuration """ pcap_defaults = {'device': 'lo', 'snaplen': 2000, 'bpf-filter': 'udp port 5061', 'debug-packets': False, 'buffer-size': 4194304, 'register-observer': True} for name, value in pcap_defaults.items(): module_config[name] = module_config.get(name, value) def packet_handler(self, packet): """Handle incoming SIP packets and verify contents. Check to see if a packet is a NOTIFY packet with the expected body type. If so then verify the body in the packet against the expected results. Arguments: packet Incoming SIP Packet """ LOGGER.debug('Received SIP packet') if 'NOTIFY' not in packet.request_line: LOGGER.debug('Ignoring packet, not a NOTIFY.') return if packet.body.packet_type != self.body_type.upper(): msg = "Ignoring packet, NOTIFY does not contain a '{0}' body type." LOGGER.warn(msg.format(self.body_type.upper())) return self.notify_count += 1 # Generate dict of expected results for this notify body and validate # the body using it. expected = self.gen_expected_data() validator = Validator(self.test_object, packet, expected) if not validator.verify_body(): LOGGER.error('Body validation failed.') return info_msg = "Body #{0} validated successfully." LOGGER.info(info_msg.format(self.notify_count)) if self.notify_count == self.expected_notifies: self.test_object.remove_fail_token(self.token) self.test_object.set_passed(True) self.test_object.stop_reactor() class Validator(object): """Validate a PIDF/XPIDF body against a set of expected data.""" def __init__(self, test_object, packet, expected_data): """Constructor Arguments: test_object The test object for the running test. packet A packet containing a SIP NOTIFY with a pidf or xpidf body. """ super(Validator, self).__init__() self.test_object = test_object self.packet = packet self.body_types = ('PIDF', 'XPIDF') self.expected_data = expected_data def verify_body(self): """Verify a PIDF/XPIDF body. This uses XML ElementTree to parse the PIDF/XPIDF body. It verifies that the XML is not malformed and verifies the elements match what is expected. This will fail the test and stop the reactor if the body type is not recognized or if the body could not be parsed. Returns: True if body type is supported, body is successfully parsed, and body matches what is expected. False otherwise. """ if self.packet.body.packet_type not in self.body_types: msg = "Unrecognized body type of '{0}'" self.fail_test(msg.format(self.packet.body.packet_type)) return False # Attempt to parse the body try: root = ET.fromstring(self.packet.body.xml) except Exception as ex: self.fail_test("Exception when parsing body XML: %s" % ex) return False # Verify top-level elements and their children for element in root.findall('.'): if not self.verify_element(element): return False return True def verify_element(self, element): """Verify the element matches what is expected. This verifies the tag, attributes, text, and extra text of an element. If child elements are found this will call back into itself to verify them. Arguments: element Element object. Returns: True if the element matches what is expected. False otherwise. """ # Verify tag, attributes, text, and extra text of the element. if not self.verify_tag(element): return False if not self.verify_attributes(element): return False if not self.verify_text(element): return False if not self.verify_extra_text(element): return False # Find child elements
[ " children = element.findall('*')" ]
861
lcc
python
null
f8f3e51eaf0b5e82798c164612594b613eff07183067e54c
"""Simple implementation of the Level 1 DOM. Namespaces and other minor Level 2 features are also supported. parse("foo.xml") parseString("<foo><bar/></foo>") Todo: ===== * convenience methods for getting elements and text. * more testing * bring some of the writer and linearizer code into conformance with this interface * SAX 2 namespaces """ import sys import xml.dom from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE, domreg from xml.dom.minicompat import * from xml.dom.xmlbuilder import DOMImplementationLS, DocumentLS # This is used by the ID-cache invalidation checks; the list isn't # actually complete, since the nodes being checked will never be the # DOCUMENT_NODE or DOCUMENT_FRAGMENT_NODE. (The node being checked is # the node being added or removed, not the node being modified.) # _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE, xml.dom.Node.ENTITY_REFERENCE_NODE) class Node(xml.dom.Node): namespaceURI = None # this is non-null only for elements and attributes parentNode = None ownerDocument = None nextSibling = None previousSibling = None prefix = EMPTY_PREFIX # non-null only for NS elements and attributes def __nonzero__(self): return True def toxml(self, encoding = None): return self.toprettyxml("", "", encoding) def toprettyxml(self, indent="\t", newl="\n", encoding = None): # indent = the indentation string to prepend, per level # newl = the newline string to append writer = _get_StringIO() if encoding is not None: import codecs # Can't use codecs.getwriter to preserve 2.0 compatibility writer = codecs.lookup(encoding)[3](writer) if self.nodeType == Node.DOCUMENT_NODE: # Can pass encoding only to document, to put it into XML header self.writexml(writer, "", indent, newl, encoding) else: self.writexml(writer, "", indent, newl) return writer.getvalue() def hasChildNodes(self): if self.childNodes: return True else: return False def _get_childNodes(self): return self.childNodes def _get_firstChild(self): if self.childNodes: return self.childNodes[0] def _get_lastChild(self): if self.childNodes: return self.childNodes[-1] def insertBefore(self, newChild, refChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(newChild.childNodes): self.insertBefore(c, refChild) ### The DOM does not clearly specify what to return in this case return newChild if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: try: index = self.childNodes.index(refChild) except ValueError: raise xml.dom.NotFoundErr() if newChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None newChild.parentNode = self return newChild def appendChild(self, node): if node.nodeType == self.DOCUMENT_FRAGMENT_NODE: for c in tuple(node.childNodes): self.appendChild(c) ### The DOM does not clearly specify what to return in this case return node if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) elif node.nodeType in _nodeTypes_with_children: _clear_id_cache(self) if node.parentNode is not None: node.parentNode.removeChild(node) _append_child(self, node) node.nextSibling = None return node def replaceChild(self, newChild, oldChild): if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE: refChild = oldChild.nextSibling self.removeChild(oldChild) return self.insertBefore(newChild, refChild) if newChild.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(newChild), repr(self))) if newChild is oldChild: return if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) try: index = self.childNodes.index(oldChild) except ValueError: raise xml.dom.NotFoundErr() self.childNodes[index] = newChild newChild.parentNode = self oldChild.parentNode = None if (newChild.nodeType in _nodeTypes_with_children or oldChild.nodeType in _nodeTypes_with_children): _clear_id_cache(self) newChild.nextSibling = oldChild.nextSibling newChild.previousSibling = oldChild.previousSibling oldChild.nextSibling = None oldChild.previousSibling = None if newChild.previousSibling: newChild.previousSibling.nextSibling = newChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild return oldChild def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() if oldChild.nextSibling is not None: oldChild.nextSibling.previousSibling = oldChild.previousSibling if oldChild.previousSibling is not None: oldChild.previousSibling.nextSibling = oldChild.nextSibling oldChild.nextSibling = oldChild.previousSibling = None if oldChild.nodeType in _nodeTypes_with_children: _clear_id_cache(self) oldChild.parentNode = None return oldChild def normalize(self): L = [] for child in self.childNodes: if child.nodeType == Node.TEXT_NODE: if not child.data: # empty text node; discard if L: L[-1].nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = child.previousSibling child.unlink() elif L and L[-1].nodeType == child.nodeType: # collapse text node node = L[-1] node.data = node.data + child.data node.nextSibling = child.nextSibling if child.nextSibling: child.nextSibling.previousSibling = node child.unlink() else: L.append(child) else: L.append(child) if child.nodeType == Node.ELEMENT_NODE: child.normalize() self.childNodes[:] = L def cloneNode(self, deep): return _clone_node(self, deep, self.ownerDocument or self) def isSupported(self, feature, version): return self.ownerDocument.implementation.hasFeature(feature, version) def _get_localName(self): # Overridden in Element and Attr where localName can be Non-Null return None # Node interfaces from Level 3 (WD 9 April 2002) def isSameNode(self, other): return self is other def getInterface(self, feature): if self.isSupported(feature, None): return self else: return None # The "user data" functions use a dictionary that is only present # if some user data has been set, so be careful not to assume it # exists. def getUserData(self, key): try: return self._user_data[key][0] except (AttributeError, KeyError): return None def setUserData(self, key, data, handler): old = None try: d = self._user_data except AttributeError: d = {} self._user_data = d if key in d: old = d[key][0] if data is None: # ignore handlers passed for None handler = None if old is not None: del d[key] else: d[key] = (data, handler) return old def _call_user_data_handler(self, operation, src, dst): if hasattr(self, "_user_data"): for key, (data, handler) in self._user_data.items(): if handler is not None: handler.handle(operation, key, data, src, dst) # minidom-specific API: def unlink(self): self.parentNode = self.ownerDocument = None if self.childNodes: for child in self.childNodes: child.unlink() self.childNodes = NodeList() self.previousSibling = None self.nextSibling = None defproperty(Node, "firstChild", doc="First child node, or None.") defproperty(Node, "lastChild", doc="Last child node, or None.") defproperty(Node, "localName", doc="Namespace-local name of this node.") def _append_child(self, node): # fast path with less checks; usable by DOM builders if careful childNodes = self.childNodes if childNodes: last = childNodes[-1] node.__dict__["previousSibling"] = last last.__dict__["nextSibling"] = node childNodes.append(node) node.__dict__["parentNode"] = self def _in_document(node): # return True iff node is part of a document tree while node is not None: if node.nodeType == Node.DOCUMENT_NODE: return True node = node.parentNode return False def _write_data(writer, data): "Writes datachars to writer." if data: data = data.replace("&", "&amp;").replace("<", "&lt;"). \ replace("\"", "&quot;").replace(">", "&gt;") writer.write(data) def _get_elements_by_tagName_helper(parent, name, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE and \ (name == "*" or node.tagName == name): rc.append(node) _get_elements_by_tagName_helper(node, name, rc) return rc def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc): for node in parent.childNodes: if node.nodeType == Node.ELEMENT_NODE: if ((localName == "*" or node.localName == localName) and (nsURI == "*" or node.namespaceURI == nsURI)): rc.append(node) _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc) return rc class DocumentFragment(Node): nodeType = Node.DOCUMENT_FRAGMENT_NODE nodeName = "#document-fragment" nodeValue = None attributes = None parentNode = None _child_node_types = (Node.ELEMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.NOTATION_NODE) def __init__(self): self.childNodes = NodeList() class Attr(Node): nodeType = Node.ATTRIBUTE_NODE attributes = None ownerElement = None specified = False _is_id = False _child_node_types = (Node.TEXT_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, qName, namespaceURI=EMPTY_NAMESPACE, localName=None, prefix=None): # skip setattr for performance d = self.__dict__ d["nodeName"] = d["name"] = qName d["namespaceURI"] = namespaceURI d["prefix"] = prefix d['childNodes'] = NodeList() # Add the single child node that represents the value of the attr self.childNodes.append(Text()) # nodeValue and value are set elsewhere def _get_localName(self): return self.nodeName.split(":", 1)[-1] def _get_specified(self): return self.specified def __setattr__(self, name, value): d = self.__dict__ if name in ("value", "nodeValue"): d["value"] = d["nodeValue"] = value d2 = self.childNodes[0].__dict__ d2["data"] = d2["nodeValue"] = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) elif name in ("name", "nodeName"): d["name"] = d["nodeName"] = value if self.ownerElement is not None: _clear_id_cache(self.ownerElement) else: d[name] = value def _set_prefix(self, prefix): nsuri = self.namespaceURI if prefix == "xmlns": if nsuri and nsuri != XMLNS_NAMESPACE: raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix for the wrong namespace") d = self.__dict__ d['prefix'] = prefix if prefix is None: newName = self.localName else: newName = "%s:%s" % (prefix, self.localName) if self.ownerElement: _clear_id_cache(self.ownerElement) d['nodeName'] = d['name'] = newName def _set_value(self, value): d = self.__dict__ d['value'] = d['nodeValue'] = value if self.ownerElement: _clear_id_cache(self.ownerElement) self.childNodes[0].data = value def unlink(self): # This implementation does not call the base implementation # since most of that is not needed, and the expense of the # method call is not warranted. We duplicate the removal of # children, but that's all we needed from the base class. elem = self.ownerElement if elem is not None: del elem._attrs[self.nodeName] del elem._attrsNS[(self.namespaceURI, self.localName)] if self._is_id: self._is_id = False elem._magic_id_nodes -= 1 self.ownerDocument._magic_id_count -= 1 for child in self.childNodes: child.unlink() del self.childNodes[:] def _get_isId(self): if self._is_id: return True doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return False info = doc._get_elem_info(elem) if info is None: return False if self.namespaceURI: return info.isIdNS(self.namespaceURI, self.localName) else: return info.isId(self.nodeName) def _get_schemaType(self): doc = self.ownerDocument elem = self.ownerElement if doc is None or elem is None: return _no_type info = doc._get_elem_info(elem) if info is None: return _no_type if self.namespaceURI: return info.getAttributeTypeNS(self.namespaceURI, self.localName) else: return info.getAttributeType(self.nodeName) defproperty(Attr, "isId", doc="True if this attribute is an ID.") defproperty(Attr, "localName", doc="Namespace-local name of this attribute.") defproperty(Attr, "schemaType", doc="Schema type for this attribute.") class NamedNodeMap(object): """The attribute list is a transient interface to the underlying dictionaries. Mutations here will change the underlying element's dictionary. Ordering is imposed artificially and does not reflect the order of attributes as found in an input document. """ __slots__ = ('_attrs', '_attrsNS', '_ownerElement') def __init__(self, attrs, attrsNS, ownerElement): self._attrs = attrs self._attrsNS = attrsNS self._ownerElement = ownerElement def _get_length(self): return len(self._attrs) def item(self, index): try: return self[self._attrs.keys()[index]] except IndexError: return None def items(self): L = [] for node in self._attrs.values(): L.append((node.nodeName, node.value)) return L def itemsNS(self): L = [] for node in self._attrs.values(): L.append(((node.namespaceURI, node.localName), node.value)) return L def has_key(self, key): if isinstance(key, StringTypes): return key in self._attrs else: return key in self._attrsNS def keys(self): return self._attrs.keys() def keysNS(self): return self._attrsNS.keys() def values(self): return self._attrs.values() def get(self, name, value=None): return self._attrs.get(name, value) __len__ = _get_length __hash__ = None # Mutable type can't be correctly hashed def __cmp__(self, other): if self._attrs is getattr(other, "_attrs", None): return 0 else: return cmp(id(self), id(other)) def __getitem__(self, attname_or_tuple): if isinstance(attname_or_tuple, tuple): return self._attrsNS[attname_or_tuple] else: return self._attrs[attname_or_tuple] # same as set def __setitem__(self, attname, value): if isinstance(value, StringTypes): try: node = self._attrs[attname] except KeyError: node = Attr(attname) node.ownerDocument = self._ownerElement.ownerDocument self.setNamedItem(node) node.value = value else: if not isinstance(value, Attr): raise TypeError, "value must be a string or Attr object" node = value self.setNamedItem(node) def getNamedItem(self, name): try: return self._attrs[name] except KeyError: return None def getNamedItemNS(self, namespaceURI, localName): try: return self._attrsNS[(namespaceURI, localName)] except KeyError: return None def removeNamedItem(self, name): n = self.getNamedItem(name) if n is not None: _clear_id_cache(self._ownerElement) del self._attrs[n.nodeName] del self._attrsNS[(n.namespaceURI, n.localName)] if 'ownerElement' in n.__dict__: n.__dict__['ownerElement'] = None return n else: raise xml.dom.NotFoundErr() def removeNamedItemNS(self, namespaceURI, localName): n = self.getNamedItemNS(namespaceURI, localName) if n is not None: _clear_id_cache(self._ownerElement) del self._attrsNS[(n.namespaceURI, n.localName)] del self._attrs[n.nodeName] if 'ownerElement' in n.__dict__: n.__dict__['ownerElement'] = None return n else: raise xml.dom.NotFoundErr() def setNamedItem(self, node): if not isinstance(node, Attr): raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) old = self._attrs.get(node.name) if old: old.unlink() self._attrs[node.name] = node self._attrsNS[(node.namespaceURI, node.localName)] = node node.ownerElement = self._ownerElement _clear_id_cache(node.ownerElement) return old def setNamedItemNS(self, node): return self.setNamedItem(node) def __delitem__(self, attname_or_tuple): node = self[attname_or_tuple] _clear_id_cache(node.ownerElement) node.unlink() def __getstate__(self): return self._attrs, self._attrsNS, self._ownerElement def __setstate__(self, state): self._attrs, self._attrsNS, self._ownerElement = state defproperty(NamedNodeMap, "length", doc="Number of nodes in the NamedNodeMap.") AttributeList = NamedNodeMap class TypeInfo(object): __slots__ = 'namespace', 'name' def __init__(self, namespace, name): self.namespace = namespace self.name = name def __repr__(self): if self.namespace: return "<TypeInfo %r (from %r)>" % (self.name, self.namespace) else: return "<TypeInfo %r>" % self.name def _get_name(self): return self.name def _get_namespace(self): return self.namespace _no_type = TypeInfo(None, None) class Element(Node): nodeType = Node.ELEMENT_NODE nodeValue = None schemaType = _no_type _magic_id_nodes = 0 _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.TEXT_NODE, Node.CDATA_SECTION_NODE, Node.ENTITY_REFERENCE_NODE) def __init__(self, tagName, namespaceURI=EMPTY_NAMESPACE, prefix=None, localName=None): self.tagName = self.nodeName = tagName self.prefix = prefix self.namespaceURI = namespaceURI self.childNodes = NodeList() self._attrs = {} # attributes are double-indexed: self._attrsNS = {} # tagName -> Attribute # URI,localName -> Attribute # in the future: consider lazy generation # of attribute objects this is too tricky # for now because of headaches with # namespaces. def _get_localName(self): return self.tagName.split(":", 1)[-1] def _get_tagName(self): return self.tagName def unlink(self): for attr in self._attrs.values(): attr.unlink() self._attrs = None self._attrsNS = None Node.unlink(self) def getAttribute(self, attname): try: return self._attrs[attname].value except KeyError: return "" def getAttributeNS(self, namespaceURI, localName): try: return self._attrsNS[(namespaceURI, localName)].value except KeyError: return "" def setAttribute(self, attname, value): attr = self.getAttributeNode(attname) if attr is None: attr = Attr(attname) # for performance d = attr.__dict__ d["value"] = d["nodeValue"] = value d["ownerDocument"] = self.ownerDocument self.setAttributeNode(attr) elif value != attr.value: d = attr.__dict__ d["value"] = d["nodeValue"] = value if attr.isId: _clear_id_cache(self) def setAttributeNS(self, namespaceURI, qualifiedName, value): prefix, localname = _nssplit(qualifiedName) attr = self.getAttributeNodeNS(namespaceURI, localname) if attr is None: # for performance attr = Attr(qualifiedName, namespaceURI, localname, prefix) d = attr.__dict__ d["prefix"] = prefix d["nodeName"] = qualifiedName d["value"] = d["nodeValue"] = value d["ownerDocument"] = self.ownerDocument self.setAttributeNode(attr) else: d = attr.__dict__ if value != attr.value: d["value"] = d["nodeValue"] = value if attr.isId: _clear_id_cache(self) if attr.prefix != prefix: d["prefix"] = prefix d["nodeName"] = qualifiedName def getAttributeNode(self, attrname): return self._attrs.get(attrname) def getAttributeNodeNS(self, namespaceURI, localName): return self._attrsNS.get((namespaceURI, localName)) def setAttributeNode(self, attr): if attr.ownerElement not in (None, self): raise xml.dom.InuseAttributeErr("attribute node already owned") old1 = self._attrs.get(attr.name, None) if old1 is not None: self.removeAttributeNode(old1) old2 = self._attrsNS.get((attr.namespaceURI, attr.localName), None) if old2 is not None and old2 is not old1: self.removeAttributeNode(old2) _set_attribute_node(self, attr) if old1 is not attr: # It might have already been part of this node, in which case # it doesn't represent a change, and should not be returned. return old1 if old2 is not attr: return old2 setAttributeNodeNS = setAttributeNode def removeAttribute(self, name): try: attr = self._attrs[name] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNS(self, namespaceURI, localName): try: attr = self._attrsNS[(namespaceURI, localName)] except KeyError: raise xml.dom.NotFoundErr() self.removeAttributeNode(attr) def removeAttributeNode(self, node): if node is None: raise xml.dom.NotFoundErr() try: self._attrs[node.name] except KeyError: raise xml.dom.NotFoundErr() _clear_id_cache(self) node.unlink() # Restore this since the node is still useful and otherwise # unlinked node.ownerDocument = self.ownerDocument removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name): return name in self._attrs def hasAttributeNS(self, namespaceURI, localName): return (namespaceURI, localName) in self._attrsNS def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def __repr__(self): return "<DOM Element: %s at %#x>" % (self.tagName, id(self)) def writexml(self, writer, indent="", addindent="", newl=""): # indent = current indentation # addindent = indentation to add to higher levels # newl = newline string writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() a_names = attrs.keys() a_names.sort() for a_name in a_names: writer.write(" %s=\"" % a_name) _write_data(writer, attrs[a_name].value) writer.write("\"") if self.childNodes: writer.write(">") if (len(self.childNodes) == 1 and self.childNodes[0].nodeType == Node.TEXT_NODE): self.childNodes[0].writexml(writer, '', '', '') else: writer.write(newl) for node in self.childNodes: node.writexml(writer, indent+addindent, addindent, newl) writer.write(indent) writer.write("</%s>%s" % (self.tagName, newl)) else: writer.write("/>%s"%(newl)) def _get_attributes(self): return NamedNodeMap(self._attrs, self._attrsNS, self) def hasAttributes(self): if self._attrs: return True else: return False # DOM Level 3 attributes, based on the 22 Oct 2002 draft def setIdAttribute(self, name): idAttr = self.getAttributeNode(name) self.setIdAttributeNode(idAttr) def setIdAttributeNS(self, namespaceURI, localName): idAttr = self.getAttributeNodeNS(namespaceURI, localName) self.setIdAttributeNode(idAttr) def setIdAttributeNode(self, idAttr): if idAttr is None or not self.isSameNode(idAttr.ownerElement): raise xml.dom.NotFoundErr() if _get_containing_entref(self) is not None: raise xml.dom.NoModificationAllowedErr() if not idAttr._is_id: idAttr.__dict__['_is_id'] = True self._magic_id_nodes += 1 self.ownerDocument._magic_id_count += 1 _clear_id_cache(self) defproperty(Element, "attributes", doc="NamedNodeMap of attributes on the element.") defproperty(Element, "localName", doc="Namespace-local name of this element.") def _set_attribute_node(element, attr): _clear_id_cache(element) element._attrs[attr.name] = attr element._attrsNS[(attr.namespaceURI, attr.localName)] = attr # This creates a circular reference, but Element.unlink() # breaks the cycle since the references to the attribute # dictionaries are tossed. attr.__dict__['ownerElement'] = element class Childless: """Mixin that makes childless-ness easy to implement and avoids the complexity of the Node methods that deal with children. """ attributes = None childNodes = EmptyNodeList() firstChild = None lastChild = None def _get_firstChild(self): return None def _get_lastChild(self): return None def appendChild(self, node): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes cannot have children") def hasChildNodes(self): return False def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") def removeChild(self, oldChild): raise xml.dom.NotFoundErr( self.nodeName + " nodes do not have children") def normalize(self): # For childless nodes, normalize() has nothing to do. pass def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( self.nodeName + " nodes do not have children") class ProcessingInstruction(Childless, Node): nodeType = Node.PROCESSING_INSTRUCTION_NODE def __init__(self, target, data): self.target = self.nodeName = target self.data = self.nodeValue = data def _get_data(self): return self.data def _set_data(self, value): d = self.__dict__ d['data'] = d['nodeValue'] = value def _get_target(self): return self.target def _set_target(self, value): d = self.__dict__ d['target'] = d['nodeName'] = value def __setattr__(self, name, value): if name == "data" or name == "nodeValue": self.__dict__['data'] = self.__dict__['nodeValue'] = value elif name == "target" or name == "nodeName": self.__dict__['target'] = self.__dict__['nodeName'] = value else: self.__dict__[name] = value def writexml(self, writer, indent="", addindent="", newl=""): writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl)) class CharacterData(Childless, Node): def _get_length(self): return len(self.data) __len__ = _get_length def _get_data(self): return self.__dict__['data'] def _set_data(self, data): d = self.__dict__ d['data'] = d['nodeValue'] = data _get_nodeValue = _get_data _set_nodeValue = _set_data def __setattr__(self, name, value): if name == "data" or name == "nodeValue": self.__dict__['data'] = self.__dict__['nodeValue'] = value else: self.__dict__[name] = value def __repr__(self): data = self.data if len(data) > 10: dotdotdot = "..." else: dotdotdot = "" return '<DOM %s node "%r%s">' % ( self.__class__.__name__, data[0:10], dotdotdot) def substringData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") return self.data[offset:offset+count] def appendData(self, arg): self.data = self.data + arg def insertData(self, offset, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if arg: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset:]) def deleteData(self, offset, count): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = self.data[:offset] + self.data[offset+count:] def replaceData(self, offset, count, arg): if offset < 0: raise xml.dom.IndexSizeErr("offset cannot be negative") if offset >= len(self.data): raise xml.dom.IndexSizeErr("offset cannot be beyond end of data") if count < 0: raise xml.dom.IndexSizeErr("count cannot be negative") if count: self.data = "%s%s%s" % ( self.data[:offset], arg, self.data[offset+count:]) defproperty(CharacterData, "length", doc="Length of the string data.") class Text(CharacterData): # Make sure we don't add an instance __dict__ if we don't already # have one, at least when that's possible: # XXX this does not work, CharacterData is an old-style class # __slots__ = () nodeType = Node.TEXT_NODE nodeName = "#text" attributes = None def splitText(self, offset): if offset < 0 or offset > len(self.data): raise xml.dom.IndexSizeErr("illegal offset value") newText = self.__class__() newText.data = self.data[offset:] newText.ownerDocument = self.ownerDocument next = self.nextSibling if self.parentNode and self in self.parentNode.childNodes: if next is None: self.parentNode.appendChild(newText) else: self.parentNode.insertBefore(newText, next) self.data = self.data[:offset] return newText def writexml(self, writer, indent="", addindent="", newl=""): _write_data(writer, "%s%s%s" % (indent, self.data, newl)) # DOM Level 3 (WD 9 April 2002) def _get_wholeText(self): L = [self.data] n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.insert(0, n.data) n = n.previousSibling else: break n = self.nextSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): L.append(n.data) n = n.nextSibling else: break return ''.join(L) def replaceWholeText(self, content): # XXX This needs to be seriously changed if minidom ever # supports EntityReference nodes. parent = self.parentNode n = self.previousSibling while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.previousSibling parent.removeChild(n) n = next else: break n = self.nextSibling if not content: parent.removeChild(self) while n is not None: if n.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE): next = n.nextSibling parent.removeChild(n) n = next else: break if content: d = self.__dict__ d['data'] = content d['nodeValue'] = content return self else: return None def _get_isWhitespaceInElementContent(self): if self.data.strip(): return False elem = _get_containing_element(self) if elem is None: return False info = self.ownerDocument._get_elem_info(elem) if info is None: return False else: return info.isElementContent() defproperty(Text, "isWhitespaceInElementContent", doc="True iff this text node contains only whitespace" " and is in element content.") defproperty(Text, "wholeText", doc="The text of all logically-adjacent text nodes.") def _get_containing_element(node): c = node.parentNode while c is not None: if c.nodeType == Node.ELEMENT_NODE: return c c = c.parentNode return None def _get_containing_entref(node): c = node.parentNode while c is not None: if c.nodeType == Node.ENTITY_REFERENCE_NODE: return c c = c.parentNode return None class Comment(Childless, CharacterData): nodeType = Node.COMMENT_NODE nodeName = "#comment" def __init__(self, data): self.data = self.nodeValue = data def writexml(self, writer, indent="", addindent="", newl=""): if "--" in self.data: raise ValueError("'--' is not allowed in a comment node") writer.write("%s<!--%s-->%s" % (indent, self.data, newl)) class CDATASection(Text): # Make sure we don't add an instance __dict__ if we don't already # have one, at least when that's possible: # XXX this does not work, Text is an old-style class # __slots__ = () nodeType = Node.CDATA_SECTION_NODE nodeName = "#cdata-section" def writexml(self, writer, indent="", addindent="", newl=""): if self.data.find("]]>") >= 0: raise ValueError("']]>' not allowed in a CDATA section") writer.write("<![CDATA[%s]]>" % self.data) class ReadOnlySequentialNamedNodeMap(object): __slots__ = '_seq', def __init__(self, seq=()): # seq should be a list or tuple self._seq = seq def __len__(self): return len(self._seq) def _get_length(self): return len(self._seq) def getNamedItem(self, name): for n in self._seq: if n.nodeName == name: return n def getNamedItemNS(self, namespaceURI, localName): for n in self._seq: if n.namespaceURI == namespaceURI and n.localName == localName: return n def __getitem__(self, name_or_tuple): if isinstance(name_or_tuple, tuple): node = self.getNamedItemNS(*name_or_tuple) else: node = self.getNamedItem(name_or_tuple) if node is None: raise KeyError, name_or_tuple return node def item(self, index): if index < 0: return None try: return self._seq[index] except IndexError: return None def removeNamedItem(self, name): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def removeNamedItemNS(self, namespaceURI, localName): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItem(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def setNamedItemNS(self, node): raise xml.dom.NoModificationAllowedErr( "NamedNodeMap instance is read-only") def __getstate__(self): return [self._seq] def __setstate__(self, state): self._seq = state[0] defproperty(ReadOnlySequentialNamedNodeMap, "length", doc="Number of entries in the NamedNodeMap.") class Identified: """Mix-in class that supports the publicId and systemId attributes.""" # XXX this does not work, this is an old-style class # __slots__ = 'publicId', 'systemId' def _identified_mixin_init(self, publicId, systemId): self.publicId = publicId self.systemId = systemId def _get_publicId(self): return self.publicId def _get_systemId(self): return self.systemId class DocumentType(Identified, Childless, Node): nodeType = Node.DOCUMENT_TYPE_NODE nodeValue = None name = None publicId = None systemId = None internalSubset = None def __init__(self, qualifiedName): self.entities = ReadOnlySequentialNamedNodeMap() self.notations = ReadOnlySequentialNamedNodeMap() if qualifiedName: prefix, localname = _nssplit(qualifiedName) self.name = localname self.nodeName = self.name def _get_internalSubset(self): return self.internalSubset def cloneNode(self, deep): if self.ownerDocument is None: # it's ok clone = DocumentType(None) clone.name = self.name clone.nodeName = self.name operation = xml.dom.UserDataHandler.NODE_CLONED if deep: clone.entities._seq = [] clone.notations._seq = [] for n in self.notations._seq: notation = Notation(n.nodeName, n.publicId, n.systemId) clone.notations._seq.append(notation) n._call_user_data_handler(operation, n, notation) for e in self.entities._seq: entity = Entity(e.nodeName, e.publicId, e.systemId, e.notationName) entity.actualEncoding = e.actualEncoding entity.encoding = e.encoding entity.version = e.version clone.entities._seq.append(entity) e._call_user_data_handler(operation, n, entity) self._call_user_data_handler(operation, self, clone) return clone else: return None def writexml(self, writer, indent="", addindent="", newl=""): writer.write("<!DOCTYPE ") writer.write(self.name) if self.publicId: writer.write("%s PUBLIC '%s'%s '%s'" % (newl, self.publicId, newl, self.systemId)) elif self.systemId: writer.write("%s SYSTEM '%s'" % (newl, self.systemId)) if self.internalSubset is not None: writer.write(" [") writer.write(self.internalSubset) writer.write("]") writer.write(">"+newl) class Entity(Identified, Node): attributes = None nodeType = Node.ENTITY_NODE nodeValue = None actualEncoding = None encoding = None version = None def __init__(self, name, publicId, systemId, notation): self.nodeName = name self.notationName = notation self.childNodes = NodeList() self._identified_mixin_init(publicId, systemId) def _get_actualEncoding(self): return self.actualEncoding def _get_encoding(self): return self.encoding def _get_version(self): return self.version def appendChild(self, newChild): raise xml.dom.HierarchyRequestErr( "cannot append children to an entity node") def insertBefore(self, newChild, refChild): raise xml.dom.HierarchyRequestErr( "cannot insert children below an entity node") def removeChild(self, oldChild): raise xml.dom.HierarchyRequestErr( "cannot remove children from an entity node") def replaceChild(self, newChild, oldChild): raise xml.dom.HierarchyRequestErr( "cannot replace children of an entity node") class Notation(Identified, Childless, Node): nodeType = Node.NOTATION_NODE nodeValue = None def __init__(self, name, publicId, systemId): self.nodeName = name self._identified_mixin_init(publicId, systemId) class DOMImplementation(DOMImplementationLS): _features = [("core", "1.0"), ("core", "2.0"), ("core", None), ("xml", "1.0"), ("xml", "2.0"), ("xml", None), ("ls-load", "3.0"), ("ls-load", None), ] def hasFeature(self, feature, version): if version == "": version = None return (feature.lower(), version) in self._features def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr( "doctype object owned by another DOM tree") doc = self._create_document() add_root_element = not (namespaceURI is None and qualifiedName is None and doctype is None) if not qualifiedName and add_root_element: # The spec is unclear what to raise here; SyntaxErr # would be the other obvious candidate. Since Xerces raises # InvalidCharacterErr, and since SyntaxErr is not listed # for createDocument, that seems to be the better choice. # XXX: need to check for illegal characters here and in # createElement. # DOM Level III clears this up when talking about the return value # of this function. If namespaceURI, qName and DocType are # Null the document is returned without a document element # Otherwise if doctype or namespaceURI are not None # Then we go back to the above problem raise xml.dom.InvalidCharacterErr("Element with no name") if add_root_element: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr( "illegal use of prefix without namespaces") element = doc.createElementNS(namespaceURI, qualifiedName) if doctype: doc.appendChild(doctype) doc.appendChild(element) if doctype: doctype.parentNode = doctype.ownerDocument = doc doc.doctype = doctype doc.implementation = self return doc def createDocumentType(self, qualifiedName, publicId, systemId): doctype = DocumentType(qualifiedName) doctype.publicId = publicId doctype.systemId = systemId return doctype # DOM Level 3 (WD 9 April 2002) def getInterface(self, feature): if self.hasFeature(feature, None): return self else: return None # internal def _create_document(self): return Document() class ElementInfo(object): """Object that represents content-model information for an element. This implementation is not expected to be used in practice; DOM builders should provide implementations which do the right thing using information available to it. """ __slots__ = 'tagName', def __init__(self, name): self.tagName = name def getAttributeType(self, aname): return _no_type def getAttributeTypeNS(self, namespaceURI, localName): return _no_type def isElementContent(self): return False def isEmpty(self): """Returns true iff this element is declared to have an EMPTY content model.""" return False def isId(self, aname): """Returns true iff the named attribute is a DTD-style ID.""" return False def isIdNS(self, namespaceURI, localName): """Returns true iff the identified attribute is a DTD-style ID.""" return False def __getstate__(self): return self.tagName def __setstate__(self, state): self.tagName = state def _clear_id_cache(node): if node.nodeType == Node.DOCUMENT_NODE: node._id_cache.clear() node._id_search_stack = None elif _in_document(node): node.ownerDocument._id_cache.clear() node.ownerDocument._id_search_stack= None class Document(Node, DocumentLS): _child_node_types = (Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE) nodeType = Node.DOCUMENT_NODE nodeName = "#document" nodeValue = None attributes = None doctype = None parentNode = None previousSibling = nextSibling = None implementation = DOMImplementation() # Document attributes from Level 3 (WD 9 April 2002) actualEncoding = None encoding = None standalone = None version = None strictErrorChecking = False errorHandler = None documentURI = None _magic_id_count = 0 def __init__(self): self.childNodes = NodeList() # mapping of (namespaceURI, localName) -> ElementInfo # and tagName -> ElementInfo self._elem_info = {} self._id_cache = {} self._id_search_stack = None def _get_elem_info(self, element): if element.namespaceURI: key = element.namespaceURI, element.localName else: key = element.tagName return self._elem_info.get(key) def _get_actualEncoding(self): return self.actualEncoding def _get_doctype(self): return self.doctype def _get_documentURI(self): return self.documentURI def _get_encoding(self): return self.encoding def _get_errorHandler(self): return self.errorHandler def _get_standalone(self): return self.standalone def _get_strictErrorChecking(self): return self.strictErrorChecking def _get_version(self): return self.version def appendChild(self, node): if node.nodeType not in self._child_node_types: raise xml.dom.HierarchyRequestErr( "%s cannot be child of %s" % (repr(node), repr(self))) if node.parentNode is not None: # This needs to be done before the next test since this # may *be* the document element, in which case it should # end up re-ordered to the end. node.parentNode.removeChild(node) if node.nodeType == Node.ELEMENT_NODE \ and self._get_documentElement(): raise xml.dom.HierarchyRequestErr( "two document elements disallowed") return Node.appendChild(self, node) def removeChild(self, oldChild): try: self.childNodes.remove(oldChild) except ValueError: raise xml.dom.NotFoundErr() oldChild.nextSibling = oldChild.previousSibling = None oldChild.parentNode = None if self.documentElement is oldChild: self.documentElement = None return oldChild def _get_documentElement(self): for node in self.childNodes: if node.nodeType == Node.ELEMENT_NODE: return node def unlink(self): if self.doctype is not None: self.doctype.unlink() self.doctype = None Node.unlink(self) def cloneNode(self, deep): if not deep: return None clone = self.implementation.createDocument(None, None, None) clone.encoding = self.encoding clone.standalone = self.standalone clone.version = self.version for n in self.childNodes: childclone = _clone_node(n, deep, clone) assert childclone.ownerDocument.isSameNode(clone) clone.childNodes.append(childclone) if childclone.nodeType == Node.DOCUMENT_NODE: assert clone.documentElement is None elif childclone.nodeType == Node.DOCUMENT_TYPE_NODE: assert clone.doctype is None clone.doctype = childclone childclone.parentNode = clone self._call_user_data_handler(xml.dom.UserDataHandler.NODE_CLONED, self, clone) return clone def createDocumentFragment(self): d = DocumentFragment() d.ownerDocument = self return d def createElement(self, tagName): e = Element(tagName) e.ownerDocument = self return e def createTextNode(self, data): if not isinstance(data, StringTypes): raise TypeError, "node contents must be a string" t = Text() t.data = data t.ownerDocument = self return t def createCDATASection(self, data): if not isinstance(data, StringTypes): raise TypeError, "node contents must be a string" c = CDATASection() c.data = data c.ownerDocument = self return c def createComment(self, data): c = Comment(data) c.ownerDocument = self return c def createProcessingInstruction(self, target, data): p = ProcessingInstruction(target, data) p.ownerDocument = self return p def createAttribute(self, qName): a = Attr(qName) a.ownerDocument = self a.value = "" return a def createElementNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) e = Element(qualifiedName, namespaceURI, prefix) e.ownerDocument = self return e def createAttributeNS(self, namespaceURI, qualifiedName): prefix, localName = _nssplit(qualifiedName) a = Attr(qualifiedName, namespaceURI, localName, prefix) a.ownerDocument = self a.value = "" return a # A couple of implementation-specific helpers to create node types # not supported by the W3C DOM specs: def _create_entity(self, name, publicId, systemId, notationName): e = Entity(name, publicId, systemId, notationName) e.ownerDocument = self return e def _create_notation(self, name, publicId, systemId): n = Notation(name, publicId, systemId) n.ownerDocument = self return n def getElementById(self, id): if id in self._id_cache: return self._id_cache[id] if not (self._elem_info or self._magic_id_count): return None stack = self._id_search_stack if stack is None: # we never searched before, or the cache has been cleared stack = [self.documentElement] self._id_search_stack = stack elif not stack: # Previous search was completed and cache is still valid; # no matching node. return None result = None while stack: node = stack.pop() # add child elements to stack for continued searching stack.extend([child for child in node.childNodes if child.nodeType in _nodeTypes_with_children]) # check this node info = self._get_elem_info(node) if info: # We have to process all ID attributes before # returning in order to get all the attributes set to # be IDs using Element.setIdAttribute*(). for attr in node.attributes.values(): if attr.namespaceURI: if info.isIdNS(attr.namespaceURI, attr.localName): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif info.isId(attr.name): self._id_cache[attr.value] = node if attr.value == id: result = node elif not node._magic_id_nodes: break elif attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node elif node._magic_id_nodes == 1: break elif node._magic_id_nodes: for attr in node.attributes.values(): if attr._is_id: self._id_cache[attr.value] = node if attr.value == id: result = node if result is not None: break return result def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) def getElementsByTagNameNS(self, namespaceURI, localName): return _get_elements_by_tagName_ns_helper( self, namespaceURI, localName, NodeList()) def isSupported(self, feature, version): return self.implementation.hasFeature(feature, version) def importNode(self, node, deep): if node.nodeType == Node.DOCUMENT_NODE: raise xml.dom.NotSupportedErr("cannot import document nodes") elif node.nodeType == Node.DOCUMENT_TYPE_NODE: raise xml.dom.NotSupportedErr("cannot import document type nodes") return _clone_node(node, deep, self) def writexml(self, writer, indent="", addindent="", newl="", encoding = None): if encoding is None: writer.write('<?xml version="1.0" ?>'+newl) else: writer.write('<?xml version="1.0" encoding="%s"?>%s' % (encoding, newl)) for node in self.childNodes: node.writexml(writer, indent, addindent, newl) # DOM Level 3 (WD 9 April 2002) def renameNode(self, n, namespaceURI, name): if n.ownerDocument is not self: raise xml.dom.WrongDocumentErr( "cannot rename nodes from other documents;\n" "expected %s,\nfound %s" % (self, n.ownerDocument)) if n.nodeType not in (Node.ELEMENT_NODE, Node.ATTRIBUTE_NODE): raise xml.dom.NotSupportedErr( "renameNode() only applies to element and attribute nodes") if namespaceURI != EMPTY_NAMESPACE: if ':' in name: prefix, localName = name.split(':', 1) if ( prefix == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE): raise xml.dom.NamespaceErr( "illegal use of 'xmlns' prefix") else: if ( name == "xmlns" and namespaceURI != xml.dom.XMLNS_NAMESPACE and n.nodeType == Node.ATTRIBUTE_NODE): raise xml.dom.NamespaceErr( "illegal use of the 'xmlns' attribute") prefix = None localName = name else: prefix = None localName = None if n.nodeType == Node.ATTRIBUTE_NODE: element = n.ownerElement if element is not None: is_id = n._is_id element.removeAttributeNode(n) else: element = None # avoid __setattr__ d = n.__dict__ d['prefix'] = prefix d['localName'] = localName d['namespaceURI'] = namespaceURI d['nodeName'] = name if n.nodeType == Node.ELEMENT_NODE: d['tagName'] = name else: # attribute node d['name'] = name if element is not None: element.setAttributeNode(n) if is_id: element.setIdAttributeNode(n) # It's not clear from a semantic perspective whether we should # call the user data handlers for the NODE_RENAMED event since # we're re-using the existing node. The draft spec has been # interpreted as meaning "no, don't call the handler unless a # new node is created." return n defproperty(Document, "documentElement", doc="Top-level element of this document.") def _clone_node(node, deep, newOwnerDocument): """ Clone a node and give it the new owner document. Called by Node.cloneNode and Document.importNode """ if node.ownerDocument.isSameNode(newOwnerDocument): operation = xml.dom.UserDataHandler.NODE_CLONED else: operation = xml.dom.UserDataHandler.NODE_IMPORTED if node.nodeType == Node.ELEMENT_NODE: clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName) for attr in node.attributes.values(): clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value) a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName) a.specified = attr.specified if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.DOCUMENT_FRAGMENT_NODE: clone = newOwnerDocument.createDocumentFragment() if deep: for child in node.childNodes: c = _clone_node(child, deep, newOwnerDocument) clone.appendChild(c) elif node.nodeType == Node.TEXT_NODE: clone = newOwnerDocument.createTextNode(node.data) elif node.nodeType == Node.CDATA_SECTION_NODE: clone = newOwnerDocument.createCDATASection(node.data) elif node.nodeType == Node.PROCESSING_INSTRUCTION_NODE: clone = newOwnerDocument.createProcessingInstruction(node.target, node.data) elif node.nodeType == Node.COMMENT_NODE: clone = newOwnerDocument.createComment(node.data) elif node.nodeType == Node.ATTRIBUTE_NODE: clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName) clone.specified = True clone.value = node.value
[ " elif node.nodeType == Node.DOCUMENT_TYPE_NODE:" ]
5,441
lcc
python
null
64062f61594fcf5875068e83e34bbe4352d55f2ffc994594
/** * <copyright> * </copyright> * * $Id$ */ package org.openhealthtools.mdht.uml.cda.emspcr.tests; import java.util.Map; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.ecore.EObject; import org.junit.Test; import org.openhealthtools.mdht.uml.cda.CDAFactory; import org.openhealthtools.mdht.uml.cda.StrucDocText; import org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection; import org.openhealthtools.mdht.uml.cda.emspcr.EmspcrFactory; import org.openhealthtools.mdht.uml.cda.emspcr.operations.EMSSceneSectionOperations; import org.openhealthtools.mdht.uml.cda.operations.CDAValidationTest; import org.openhealthtools.mdht.uml.hl7.datatypes.DatatypesFactory; import org.openhealthtools.mdht.uml.hl7.datatypes.ST; /** * <!-- begin-user-doc --> * A static utility class that provides operations related to '<em><b>EMS Scene Section</b></em>' model objects. * <!-- end-user-doc --> * * <p> * The following operations are supported: * <ul> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionTemplateId(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Template Id</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionCode(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Code</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionTitle(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Title</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionText(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Text</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionFirstUnitIndicator(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section First Unit Indicator</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionFirstUnitOnScene(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section First Unit On Scene</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionScenePatientCount(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Scene Patient Count</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionMassCasualtyIndicator(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Mass Casualty Indicator</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#validateEMSSceneSectionLocationTypeObservation(org.eclipse.emf.common.util.DiagnosticChain, java.util.Map) <em>Validate EMS Scene Section Location Type Observation</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#getFirstUnitIndicator() <em>Get First Unit Indicator</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#getFirstUnitOnScene() <em>Get First Unit On Scene</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#getScenePatientCount() <em>Get Scene Patient Count</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#getMassCasualtyIndicator() <em>Get Mass Casualty Indicator</em>}</li> * <li>{@link org.openhealthtools.mdht.uml.cda.emspcr.EMSSceneSection#getLocationTypeObservation() <em>Get Location Type Observation</em>}</li> * </ul> * </p> * * @generated */ public class EMSSceneSectionTest extends CDAValidationTest { /** * * @generated */ @Test public void testValidateEMSSceneSectionTemplateId() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionTemplateIdTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionTemplateId", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_TEMPLATE_ID__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionTemplateId( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionTemplateIdTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionCode() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionCodeTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionCode", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_CODE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionCode( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionCodeTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionTitle() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionTitleTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionTitle", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_TITLE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); ST title = DatatypesFactory.eINSTANCE.createST("title"); target.setTitle(title); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionTitle( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionTitleTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionText() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionTextTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionText", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_TEXT__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); StrucDocText text = CDAFactory.eINSTANCE.createStrucDocText(); target.setText(text); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionText( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionTextTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionFirstUnitIndicator() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionFirstUnitIndicatorTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionFirstUnitIndicator", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_FIRST_UNIT_INDICATOR__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionFirstUnitIndicator( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionFirstUnitIndicatorTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionFirstUnitOnScene() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionFirstUnitOnSceneTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionFirstUnitOnScene", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_FIRST_UNIT_ON_SCENE__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionFirstUnitOnScene( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionFirstUnitOnSceneTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionScenePatientCount() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionScenePatientCountTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionScenePatientCount", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_SCENE_PATIENT_COUNT__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionScenePatientCount( (EMSSceneSection) objectToTest, diagnostician, map); } }; validateEMSSceneSectionScenePatientCountTestCase.doValidationTest(); } /** * * @generated */ @Test public void testValidateEMSSceneSectionMassCasualtyIndicator() { OperationsTestCase<EMSSceneSection> validateEMSSceneSectionMassCasualtyIndicatorTestCase = new OperationsTestCase<EMSSceneSection>( "validateEMSSceneSectionMassCasualtyIndicator", operationsForOCL.getOCLValue("VALIDATE_EMS_SCENE_SECTION_MASS_CASUALTY_INDICATOR__DIAGNOSTIC_CHAIN_MAP__EOCL_EXP"), objectFactory) { @Override protected void updateToFail(EMSSceneSection target) { } @Override protected void updateToPass(EMSSceneSection target) { target.init(); } @Override protected boolean validate(EObject objectToTest, BasicDiagnostic diagnostician, Map<Object, Object> map) { return EMSSceneSectionOperations.validateEMSSceneSectionMassCasualtyIndicator(
[ "\t\t\t\t\t(EMSSceneSection) objectToTest, diagnostician, map);" ]
659
lcc
java
null
78238acd4e2f77afea6f7f0a6a7204254284924614d7e707
/** * Copyright (C) 2014-2015 Regents of the University of California. * Authors: * Jeff Thompson <jefft0@remap.ucla.edu> * Rafael Teixeira <monoman@gmail.com> * * This program 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 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, see <http://www.gnu.org/licenses/>. * A copy of the GNU Lesser General Public License is in the file COPYING. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Net.NamedData.Encoding { using System.Security.Cryptography; using Net.NamedData; using Net.NamedData.Encoding.Tlv; using Net.NamedData.Util; /** * A Tlv0_1_1WireFormat : the WireFormat interface for encoding and * decoding with the NDN-TLV wire format, version 0.1.1. */ public class Tlv0_1_1WireFormat : WireFormat { /** * Encode name in NDN-TLV and return the encoding. * @param name The Name object to Encode. * @return A Blob containing the encoding. */ public Blob encodeName(Name name) { TlvEncoder encoder = new TlvEncoder(); encodeName(name, new int[1], new int[1], encoder); return new Blob(encoder.getOutput(), false); } /** * Decode input as a name in NDN-TLV and set the fields of the interest object. * @param name The Name object whose fields are updated. * @param input The input buffer to Decode. This reads from position() to limit(), but does not change the position. * @ For invalid encoding. */ public void decodeName(Name name, ByteBuffer input) { TlvDecoder decoder = new TlvDecoder(input); decodeName(name, new int[1], new int[1], decoder); } /** * Encode interest using NDN-TLV and return the encoding. * @param interest The Interest object to Encode. * @param signedPortionBeginOffset Return the offset in the encoding of the * beginning of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * @param signedPortionEndOffset Return the offset in the encoding of the end * of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * @return A Blob containing the encoding. */ public Blob encodeInterest (Interest interest, int[] signedPortionBeginOffset, int[] signedPortionEndOffset) { TlvEncoder encoder = new TlvEncoder(); int saveLength = encoder.getLength(); // Encode backwards. encoder.writeOptionalNonNegativeIntegerTlvFromDouble (TlvTypeCodes.InterestLifetime, interest.getInterestLifetimeMilliseconds()); encoder.writeOptionalNonNegativeIntegerTlv(TlvTypeCodes.Scope, interest.getScope()); // Encode the Nonce as 4 bytes. if (interest.getNonce().size() == 0) { // This is the most common case. Generate a nonce. ByteBuffer nonce = ByteBuffer.allocate(4); random_.nextBytes(nonce.array()); encoder.writeBlobTlv(TlvTypeCodes.Nonce, nonce); } else if (interest.getNonce().size() < 4) { ByteBuffer nonce = ByteBuffer.allocate(4); // Copy existing nonce bytes. nonce.put(interest.getNonce().buf()); // Generate random bytes for remaining bytes in the nonce. for (int i = 0; i < 4 - interest.getNonce().size(); ++i) nonce.put((byte)random_.nextInt()); nonce.flip(); encoder.writeBlobTlv(TlvTypeCodes.Nonce, nonce); } else if (interest.getNonce().size() == 4) // Use the nonce as-is. encoder.writeBlobTlv(TlvTypeCodes.Nonce, interest.getNonce().buf()); else { // Truncate. ByteBuffer nonce = interest.getNonce().buf(); // buf() returns a new ByteBuffer, so we can change its limit. nonce.limit(nonce.position() + 4); encoder.writeBlobTlv(TlvTypeCodes.Nonce, nonce); } encodeSelectors(interest, encoder); int[] tempSignedPortionBeginOffset = new int[1]; int[] tempSignedPortionEndOffset = new int[1]; encodeName (interest.getName(), tempSignedPortionBeginOffset, tempSignedPortionEndOffset, encoder); int signedPortionBeginOffsetFromBack = encoder.getLength() - tempSignedPortionBeginOffset[0]; int signedPortionEndOffsetFromBack = encoder.getLength() - tempSignedPortionEndOffset[0]; encoder.writeTypeAndLength(TlvTypeCodes.Interest, encoder.getLength() - saveLength); signedPortionBeginOffset[0] = encoder.getLength() - signedPortionBeginOffsetFromBack; signedPortionEndOffset[0] = encoder.getLength() - signedPortionEndOffsetFromBack; return new Blob(encoder.getOutput(), false); } /** * Decode input as an interest in NDN-TLV and set the fields of the interest * object. * @param interest The Interest object whose fields are updated. * @param input The input buffer to Decode. This reads from position() to * limit(), but does not change the position. * @param signedPortionBeginOffset Return the offset in the encoding of the * beginning of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * @param signedPortionEndOffset Return the offset in the encoding of the end * of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * @ For invalid encoding. */ public void decodeInterest (Interest interest, ByteBuffer input, int[] signedPortionBeginOffset, int[] signedPortionEndOffset) { TlvDecoder decoder = new TlvDecoder(input); int endOffset = decoder.readNestedTlvsStart(TlvTypeCodes.Interest); decodeName (interest.getName(), signedPortionBeginOffset, signedPortionEndOffset, decoder); if (decoder.peekType(TlvTypeCodes.Selectors, endOffset)) decodeSelectors(interest, decoder); // Require a Nonce, but don't force it to be 4 bytes. ByteBuffer nonce = decoder.readBlobTlv(TlvTypeCodes.Nonce); interest.setScope((int)decoder.readOptionalNonNegativeIntegerTlv (TlvTypeCodes.Scope, endOffset)); interest.setInterestLifetimeMilliseconds (decoder.readOptionalNonNegativeIntegerTlv(TlvTypeCodes.InterestLifetime, endOffset)); // Set the nonce last because setting other interest fields clears it. interest.setNonce(new Blob(nonce, true)); decoder.finishNestedTlvs(endOffset); } /** * Encode data in NDN-TLV and return the encoding. * @param data The Data object to Encode. * @param signedPortionBeginOffset Return the offset in the encoding of the * beginning of the signed portion by setting signedPortionBeginOffset[0]. * If you are not encoding in order to Sign, you can call encodeData(data) to * ignore this returned value. * @param signedPortionEndOffset Return the offset in the encoding of the end * of the signed portion by setting signedPortionEndOffset[0]. * If you are not encoding in order to Sign, you can call encodeData(data) to * ignore this returned value. * @return A Blob containing the encoding. */ public Blob encodeData (Data data, int[] signedPortionBeginOffset, int[] signedPortionEndOffset) { TlvEncoder encoder = new TlvEncoder(1500); int saveLength = encoder.getLength(); // Encode backwards. encoder.writeBlobTlv (TlvTypeCodes.SignatureValue, (data.getSignature()).getSignature().buf()); int signedPortionEndOffsetFromBack = encoder.getLength(); encodeSignatureInfo(data.getSignature(), encoder); encoder.writeBlobTlv(TlvTypeCodes.Content, data.getContent().buf()); encodeMetaInfo(data.getMetaInfo(), encoder); encodeName(data.getName(), new int[1], new int[1], encoder); int signedPortionBeginOffsetFromBack = encoder.getLength(); encoder.writeTypeAndLength(TlvTypeCodes.Data, encoder.getLength() - saveLength); signedPortionBeginOffset[0] = encoder.getLength() - signedPortionBeginOffsetFromBack; signedPortionEndOffset[0] = encoder.getLength() - signedPortionEndOffsetFromBack; return new Blob(encoder.getOutput(), false); } /** * Decode input as a data packet in NDN-TLV and set the fields in the data * object. * @param data The Data object whose fields are updated. * @param input The input buffer to Decode. This reads from position() to * limit(), but does not change the position. * @param signedPortionBeginOffset Return the offset in the input buffer of * the beginning of the signed portion by setting signedPortionBeginOffset[0]. * If you are not decoding in order to verify, you can call * decodeData(data, input) to ignore this returned value. * @param signedPortionEndOffset Return the offset in the input buffer of the * end of the signed portion by setting signedPortionEndOffset[0]. If you are * not decoding in order to verify, you can call decodeData(data, input) to * ignore this returned value. * @ For invalid encoding. */ public void decodeData (Data data, ByteBuffer input, int[] signedPortionBeginOffset, int[] signedPortionEndOffset) { TlvDecoder decoder = new TlvDecoder(input); int endOffset = decoder.readNestedTlvsStart(TlvTypeCodes.Data); signedPortionBeginOffset[0] = decoder.getOffset(); decodeName(data.getName(), new int[1], new int[1], decoder); decodeMetaInfo(data.getMetaInfo(), decoder); data.setContent(new Blob(decoder.readBlobTlv(TlvTypeCodes.Content), true)); decodeSignatureInfo(data, decoder); signedPortionEndOffset[0] = decoder.getOffset(); data.getSignature().setSignature (new Blob(decoder.readBlobTlv(TlvTypeCodes.SignatureValue), true)); decoder.finishNestedTlvs(endOffset); } /** * Encode controlParameters in NDN-TLV and return the encoding. * @param controlParameters The ControlParameters object to Encode. * @return A Blob containing the encoding. */ public Blob encodeControlParameters(ControlParameters controlParameters) { TlvEncoder encoder = new TlvEncoder(256); int saveLength = encoder.getLength(); // Encode backwards. encoder.writeOptionalNonNegativeIntegerTlvFromDouble (TlvTypeCodes.ControlParameters_ExpirationPeriod, controlParameters.getExpirationPeriod()); // Encode strategy if (controlParameters.getStrategy().size() != 0) { int strategySaveLength = encoder.getLength(); encodeName(controlParameters.getStrategy(), new int[1], new int[1], encoder); encoder.writeTypeAndLength(TlvTypeCodes.ControlParameters_Strategy, encoder.getLength() - strategySaveLength); } // Encode ForwardingFlags int flags = controlParameters.getForwardingFlags().getNfdForwardingFlags(); if (flags != new ForwardingFlags().getNfdForwardingFlags()) // The flags are not the default value. encoder.writeNonNegativeIntegerTlv(TlvTypeCodes.ControlParameters_Flags, flags); encoder.writeOptionalNonNegativeIntegerTlv (TlvTypeCodes.ControlParameters_Cost, controlParameters.getCost()); encoder.writeOptionalNonNegativeIntegerTlv (TlvTypeCodes.ControlParameters_Origin, controlParameters.getOrigin()); encoder.writeOptionalNonNegativeIntegerTlv (TlvTypeCodes.ControlParameters_LocalControlFeature, controlParameters.getLocalControlFeature()); // Encode URI if (!controlParameters.getUri().isEmpty()) { encoder.writeBlobTlv(TlvTypeCodes.ControlParameters_Uri, new Blob(controlParameters.getUri()).buf()); } encoder.writeOptionalNonNegativeIntegerTlv (TlvTypeCodes.ControlParameters_FaceId, controlParameters.getFaceId()); // Encode name if (controlParameters.getName().size() != 0) { encodeName(controlParameters.getName(), new int[1], new int[1], encoder); } encoder.writeTypeAndLength (TlvTypeCodes.ControlParameters_ControlParameters, encoder.getLength() - saveLength); return new Blob(encoder.getOutput(), false); } /** * Decode controlParameters in NDN-TLV and return the encoding. * @param controlParameters The ControlParameters object to Encode. * @param input * @ For invalid encoding */ public void decodeControlParameters(ControlParameters controlParameters, ByteBuffer input) { TlvDecoder decoder = new TlvDecoder(input); int endOffset = decoder. readNestedTlvsStart(TlvTypeCodes.ControlParameters_ControlParameters); // Decode name if (decoder.peekType(TlvTypeCodes.Name, endOffset)) { Name name = new Name(); decodeName(name, new int[1], new int[1], decoder); controlParameters.setName(name); } // Decode face ID controlParameters.setFaceId((int)decoder.readOptionalNonNegativeIntegerTlv(TlvTypeCodes.ControlParameters_FaceId, endOffset)); // Decode URI if (decoder.peekType(TlvTypeCodes.ControlParameters_Uri, endOffset)) { Blob uri = new Blob(decoder.readOptionalBlobTlv(TlvTypeCodes.ControlParameters_Uri, endOffset), true); controlParameters.setUri(uri.toString()); } // Decode integers controlParameters.setLocalControlFeature((int)decoder. readOptionalNonNegativeIntegerTlv( TlvTypeCodes.ControlParameters_LocalControlFeature, endOffset)); controlParameters.setOrigin((int)decoder. readOptionalNonNegativeIntegerTlv(TlvTypeCodes.ControlParameters_Origin, endOffset)); controlParameters.setCost((int)decoder.readOptionalNonNegativeIntegerTlv( TlvTypeCodes.ControlParameters_Cost, endOffset)); // set forwarding flags ForwardingFlags flags = new ForwardingFlags(); flags.setNfdForwardingFlags((int)decoder. readOptionalNonNegativeIntegerTlv(TlvTypeCodes.ControlParameters_Flags, endOffset)); controlParameters.setForwardingFlags(flags); // Decode strategy if (decoder.peekType(TlvTypeCodes.ControlParameters_Strategy, endOffset)) { int strategyEndOffset = decoder.readNestedTlvsStart(TlvTypeCodes.ControlParameters_Strategy); decodeName(controlParameters.getStrategy(), new int[1], new int[1], decoder); decoder.finishNestedTlvs(strategyEndOffset); } // Decode expiration period controlParameters.setExpirationPeriod((int)decoder.readOptionalNonNegativeIntegerTlv(TlvTypeCodes.ControlParameters_ExpirationPeriod, endOffset)); decoder.finishNestedTlvs(endOffset); } /** * Encode signature as a SignatureInfo in NDN-TLV and return the encoding. * @param signature An object of a subclass of AbstractSignature to Encode. * @return A Blob containing the encoding. */ public Blob encodeSignatureInfo(AbstractSignature signature) { TlvEncoder encoder = new TlvEncoder(256); encodeSignatureInfo(signature, encoder); return new Blob(encoder.getOutput(), false); } private class SimpleSignatureHolder : ISignatureHolder { public ISignatureHolder setSignature(AbstractSignature signature) { signature_ = signature; return this; } public AbstractSignature getSignature() { return signature_; } private AbstractSignature signature_; } /** * Decode signatureInfo as an NDN-TLV signature info and signatureValue as the * related NDN-TLV SignatureValue, and return a new object which is a subclass * of AbstractSignature. * @param signatureInfo The signature info input buffer to Decode. This reads * from position() to limit(), but does not change the position. * @param signatureValue The signature value input buffer to Decode. This reads * from position() to limit(), but does not change the position. * @return A new object which is a subclass of AbstractSignature. * @ For invalid encoding. */ public AbstractSignature decodeSignatureInfoAndValue (ByteBuffer signatureInfo, ByteBuffer signatureValue) { // Use a ISignatureHolder to imitate a Data object for _decodeSignatureInfo. SimpleSignatureHolder signatureHolder = new SimpleSignatureHolder(); TlvDecoder decoder = new TlvDecoder(signatureInfo); decodeSignatureInfo(signatureHolder, decoder); decoder = new TlvDecoder(signatureValue); signatureHolder.getSignature().setSignature (new Blob(decoder.readBlobTlv(TlvTypeCodes.SignatureValue), true)); return signatureHolder.getSignature(); } /** * Encode the signatureValue in the AbstractSignature object as a SignatureValue (the * signature bits) in NDN-TLV and return the encoding. * @param signature An object of a subclass of AbstractSignature with the signature * value to Encode. * @return A Blob containing the encoding. */ public Blob encodeSignatureValue(AbstractSignature signature) { TlvEncoder encoder = new TlvEncoder(256); encoder.writeBlobTlv(TlvTypeCodes.SignatureValue, signature.getSignature().buf()); return new Blob(encoder.getOutput(), false); } /** * Get a singleton instance of a Tlv1_0a2WireFormat. To always use the * preferred version NDN-TLV, you should use TlvWireFormat.get(). * @return The singleton instance. */ public static Tlv0_1_1WireFormat get() { return instance_; } /** * Encode the name to the encoder. * @param name The name to Encode. * @param signedPortionBeginOffset Return the offset in the encoding of the * beginning of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * @param signedPortionEndOffset Return the offset in the encoding of the end * of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * @param encoder The TlvEncoder to receive the encoding. */ private static void encodeName (Name name, int[] signedPortionBeginOffset, int[] signedPortionEndOffset, TlvEncoder encoder) { int saveLength = encoder.getLength(); // Encode the components backwards. int signedPortionEndOffsetFromBack = 0; for (int i = name.size() - 1; i >= 0; --i) { encoder.writeBlobTlv(TlvTypeCodes.NameComponent, name.get(i).getValue().buf()); if (i == name.size() - 1) signedPortionEndOffsetFromBack = encoder.getLength(); } int signedPortionBeginOffsetFromBack = encoder.getLength(); encoder.writeTypeAndLength(TlvTypeCodes.Name, encoder.getLength() - saveLength); signedPortionBeginOffset[0] = encoder.getLength() - signedPortionBeginOffsetFromBack; if (name.size() == 0) // There is no "final component", so set signedPortionEndOffset // arbitrarily. signedPortionEndOffset[0] = signedPortionBeginOffset[0]; else signedPortionEndOffset[0] = encoder.getLength() - signedPortionEndOffsetFromBack; } /** * Decode the name as NDN-TLV and set the fields in name. * @param name The name object whose fields are set. * @param signedPortionBeginOffset Return the offset in the encoding of the * beginning of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * If you are not decoding in order to verify, you can ignore this returned value. * @param signedPortionEndOffset Return the offset in the encoding of the end * of the signed portion. The signed portion starts from the first * name component and ends just before the final name component (which is * assumed to be a signature for a signed interest). * If you are not decoding in order to verify, you can ignore this returned value. * @param decoder The decoder with the input to Decode. * @ */ private static void decodeName (Name name, int[] signedPortionBeginOffset, int[] signedPortionEndOffset, TlvDecoder decoder) { name.Clear(); int endOffset = decoder.readNestedTlvsStart(TlvTypeCodes.Name); signedPortionBeginOffset[0] = decoder.getOffset(); // In case there are no components, set signedPortionEndOffset arbitrarily. signedPortionEndOffset[0] = signedPortionBeginOffset[0]; while (decoder.getOffset() < endOffset) { signedPortionEndOffset[0] = decoder.getOffset(); name.Append(new Blob(decoder.readBlobTlv(TlvTypeCodes.NameComponent), true)); } decoder.finishNestedTlvs(endOffset); } /** * Encode the interest selectors. If no selectors are written, do not output * a Selectors TLV. */ private static void encodeSelectors(Interest interest, TlvEncoder encoder) { int saveLength = encoder.getLength(); // Encode backwards. if (interest.getMustBeFresh()) encoder.writeTypeAndLength(TlvTypeCodes.MustBeFresh, 0); encoder.writeOptionalNonNegativeIntegerTlv( TlvTypeCodes.ChildSelector, interest.getChildSelector()); if (interest.getExclude().size() > 0) encodeExclude(interest.getExclude(), encoder); if (interest.getKeyLocator().getType() != KeyLocatorType.NONE) encodeKeyLocator (TlvTypeCodes.PublisherPublicKeyLocator, interest.getKeyLocator(), encoder); else { // There is no keyLocator. If there is a publisherPublicKeyDigest, then // Encode as KEY_LOCATOR_DIGEST. (When we remove the deprecated // publisherPublicKeyDigest, we don't need this.) if (interest.getPublisherPublicKeyDigest().getPublisherPublicKeyDigest().size() > 0) { int savePublisherPublicKeyDigestLength = encoder.getLength(); encoder.writeBlobTlv (TlvTypeCodes.KeyLocatorDigest, interest.getPublisherPublicKeyDigest().getPublisherPublicKeyDigest().buf()); encoder.writeTypeAndLength (TlvTypeCodes.KeyLocator, encoder.getLength() - savePublisherPublicKeyDigestLength); } } encoder.writeOptionalNonNegativeIntegerTlv( TlvTypeCodes.MaxSuffixComponents, interest.getMaxSuffixComponents()); encoder.writeOptionalNonNegativeIntegerTlv( TlvTypeCodes.MinSuffixComponents, interest.getMinSuffixComponents()); // Only output the type and length if values were written. if (encoder.getLength() != saveLength) encoder.writeTypeAndLength(TlvTypeCodes.Selectors, encoder.getLength() - saveLength); } private static void decodeSelectors(Interest interest, TlvDecoder decoder) { int endOffset = decoder.readNestedTlvsStart(TlvTypeCodes.Selectors); interest.setMinSuffixComponents((int)decoder.readOptionalNonNegativeIntegerTlv (TlvTypeCodes.MinSuffixComponents, endOffset)); interest.setMaxSuffixComponents((int)decoder.readOptionalNonNegativeIntegerTlv (TlvTypeCodes.MaxSuffixComponents, endOffset)); // Initially set publisherPublicKeyDigest to none. interest.getPublisherPublicKeyDigest().clear(); if (decoder.peekType(TlvTypeCodes.PublisherPublicKeyLocator, endOffset)) { decodeKeyLocator (TlvTypeCodes.PublisherPublicKeyLocator, interest.getKeyLocator(), decoder); if (interest.getKeyLocator().getType() == KeyLocatorType.KEY_LOCATOR_DIGEST) { // For backwards compatibility, also set the publisherPublicKeyDigest. interest.getPublisherPublicKeyDigest().setPublisherPublicKeyDigest (interest.getKeyLocator().getKeyData()); } } else interest.getKeyLocator().clear(); if (decoder.peekType(TlvTypeCodes.Exclude, endOffset)) decodeExclude(interest.getExclude(), decoder); else interest.getExclude().clear(); interest.setChildSelector((int)decoder.readOptionalNonNegativeIntegerTlv (TlvTypeCodes.ChildSelector, endOffset)); interest.setMustBeFresh(decoder.readBooleanTlv(TlvTypeCodes.MustBeFresh, endOffset)); decoder.finishNestedTlvs(endOffset); } private static void encodeExclude(Exclude exclude, TlvEncoder encoder) { int saveLength = encoder.getLength(); // TODO: Do we want to order the components (except for ANY)? // Encode the entries backwards. for (int i = exclude.size() - 1; i >= 0; --i) { Exclude.Entry entry = exclude.get(i); if (entry.getType() == Exclude.Type.ANY) encoder.writeTypeAndLength(TlvTypeCodes.Any, 0); else encoder.writeBlobTlv (TlvTypeCodes.NameComponent, entry.getComponent().getValue().buf()); } encoder.writeTypeAndLength(TlvTypeCodes.Exclude, encoder.getLength() - saveLength); } private static void decodeExclude(Exclude exclude, TlvDecoder decoder) { int endOffset = decoder.readNestedTlvsStart(TlvTypeCodes.Exclude); exclude.clear(); while (true) { if (decoder.peekType(TlvTypeCodes.NameComponent, endOffset)) exclude.appendComponent(new Name.Component (new Blob(decoder.readBlobTlv(TlvTypeCodes.NameComponent), true))); else if (decoder.readBooleanTlv(TlvTypeCodes.Any, endOffset)) exclude.appendAny(); else // Else no more entries. break; } decoder.finishNestedTlvs(endOffset); } private static void encodeKeyLocator(int type, KeyLocator keyLocator, TlvEncoder encoder) { int saveLength = encoder.getLength(); // Encode backwards. if (keyLocator.getType() != KeyLocatorType.NONE) { if (keyLocator.getType() == KeyLocatorType.KEYNAME) encodeName(keyLocator.getKeyName(), new int[1], new int[1], encoder); else if (keyLocator.getType() == KeyLocatorType.KEY_LOCATOR_DIGEST && keyLocator.getKeyData().size() > 0) encoder.writeBlobTlv(TlvTypeCodes.KeyLocatorDigest, keyLocator.getKeyData().buf()); else throw new Error("Unrecognized KeyLocatorType " + keyLocator.getType()); } encoder.writeTypeAndLength(type, encoder.getLength() - saveLength); } private static void decodeKeyLocator (int expectedType, KeyLocator keyLocator, TlvDecoder decoder) { int endOffset = decoder.readNestedTlvsStart(expectedType); keyLocator.clear();
[ "\t\t\tif (decoder.getOffset() == endOffset)" ]
2,575
lcc
csharp
null
3478f59e50537de1932e70589d61d1ffd7f3cc98c321b79a
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package NetSpace; import NetSpace.weapons.WeaponsEnum; import NetSpace.weapons.Weapon; import NetSpace.weapons.WeaponType; import NetSpace.aliens.Enemy; import NetSpace.aliens.EnemyRepresentation; import NetSpace.update.UpdatePatch; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.Image; import org.newdawn.slick.tiled.*; import org.newdawn.slick.geom.*; import org.newdawn.slick.Animation; import org.newdawn.slick.Input; /** * * @author Aidan Malone */ public class game extends BasicGame { //Single-player constructor public game() { super("game"); } //Multi-player constructor public game(ObjectOutputStream out, ObjectInputStream in, String user) { super("game"); try { Username = user; Soutput = out; Sinput = in; } catch (Exception ex) { ex.printStackTrace(); } } //This is the width and height of your game window final static int viewW = 1024, viewH = 690; //Image [] shipSprites; //Animation ship; float theta = 0f; TiledMap StarMap; int mapw, maph; int spritew = 100, spriteh = 100; float Shipx = viewW/2-spritew/2, Shipy = viewH/2-spriteh/2; final int phaseShift = 90; final int speed = 5; float destx = Shipx + spritew/2, desty = Shipy + spriteh/2; float viewx = 0, viewy = 0; HUD display; //This contains all of the methods for actually controlling the ship's motion Player myPlayer; //This contains the data for all of the players currently registered with // the server, including yours ArrayList <PlayerInfo> players = new ArrayList<PlayerInfo>(); Rectangle camera; WeaponType[] myWeapons; WeaponType auto; //Socket serv; ObjectInputStream Sinput; ObjectOutputStream Soutput; final int MAXMSGS = 6; ArrayList <String>Messages = new ArrayList<String>(MAXMSGS); ArrayList <EnemyRepresentation> ennemies = new ArrayList<EnemyRepresentation>(); ArrayList <Weapon> ActiveWeapons = new ArrayList<Weapon>(); String Username; float[][] todraw; InputThread inputReader; SpriteBank spriteBank; public static void create() { try { AppGameContainer app = new AppGameContainer(new game()); app.setDisplayMode(viewW, viewH, false); app.setVSync(true); app.start(); } catch (SlickException e) { e.printStackTrace(); } } public static void createNetGame(ObjectOutputStream out, ObjectInputStream in, String user) { try { AppGameContainer app = new AppGameContainer(new game(out, in, user)); app.setDisplayMode(viewW, viewH, false); app.setVSync(true); app.start(); } catch (SlickException e) { e.printStackTrace(); } } @Override public void init(GameContainer container) throws SlickException { //Load all map variables StarMap = new TiledMap("data/StarMap.tmx"); mapw = StarMap.getWidth()*StarMap.getTileWidth(); maph = StarMap.getHeight()*StarMap.getTileHeight(); //Load the HUD display = new HUD(viewW, viewH); //Initialize the sprites spriteBank = new SpriteBank(); myPlayer = new Player(Username,50,50); // for(int i = 0; i<bots.size(); i++){ // ennemies.add(new Enemy((int)(Math.random()*mapw),(int)(Math.random()*maph))); // } camera = new Rectangle(viewx,viewy,viewW,viewH); //Sets which Weapons the player is using myWeapons = new WeaponType[4]; myWeapons[0] = new WeaponType(WeaponsEnum.PULSE); myWeapons[1] = new WeaponType(WeaponsEnum.BLAST); myWeapons[2] = new WeaponType(WeaponsEnum.BLAST); myWeapons[3] = new WeaponType(WeaponsEnum.MINE); auto = new WeaponType(WeaponsEnum.LASER); display.loadWeapons(myWeapons); inputReader = new InputThread (); inputReader.start(); } @Override public void update(GameContainer container, int delta) throws SlickException { Input input = container.getInput(); float x = input.getMouseX(); float y = input.getMouseY(); //Checks for the left mouse button. if (input.isMouseButtonDown(0)) { if (display.minimap.contains(x, y)) { myPlayer.newDestination((int)display.getMapX(x, mapw),(int)display.getMapY(y, maph)); } else { myPlayer.newDestination((int)(x + viewx),(int)(y + viewy)); } } //Checks for key input /* if (inputReader.isKeyDown(Input.KEY_Q)) { //Deals with Player targetting int target = -1; for(int i = 0; i<bots.size(); i++) { if((ennemies.get(i)).isAlive()){ if(ennemies.get(i).hitbox.contains(x + viewx, y + viewy)){ target = i; break; } } } player.target = target; } */ //Debugging button if (input.isKeyDown(Input.KEY_A)) { //System.out.println(ennemies.get(0).ID); for (int i = 0; i<ennemies.size(); i++){ System.out.println("Bot #" + i + " x: " + ennemies.get(i).x); } } if (input.isKeyDown(Input.KEY_1)) { if(myWeapons[0].offCD()){ Weapon a = myPlayer.fireWeapon((int)(x + viewx),(int)(y+ viewy), myWeapons[0]); a.init(0, Username); ActiveWeapons.add(a); send(a); } } if (input.isKeyDown(Input.KEY_2)) { if(myWeapons[1].offCD()){ Weapon a = myPlayer.fireWeapon((int)(x + viewx),(int)(y+ viewy), myWeapons[1]); a.init(1, Username); ActiveWeapons.add(a); send(a); } } if (input.isKeyDown(Input.KEY_3)) { if(myWeapons[2].offCD()){ Weapon a = myPlayer.fireWeapon((int)(x + viewx),(int)(y+ viewy), myWeapons[2]); a.init(2, Username); ActiveWeapons.add(a); send(a); } } if (input.isKeyDown(Input.KEY_4)) { if(myWeapons[3].offCD()){ Weapon a = myPlayer.fireWeapon((int)(x + viewx),(int)(y+ viewy), myWeapons[3]); a.init(3, Username); ActiveWeapons.add(a); send(a); } } //Updates the player myPlayer.update(delta,mapw,maph); //Updates the player's location on the server send(myPlayer.getUpdate()); //Updates the other player's animations and ship positions for(int i = 0; i < players.size(); i++){ PlayerInfo player2 = players.get(i); player2.Ship.update(delta); player2.moveShip(delta); } for(int i = 0; i < ennemies.size(); i++){ ennemies.get(i).move(delta); } //updates Weapon cooldowns
[ " for(int i = 0; i< myWeapons.length; i++) {" ]
673
lcc
java
null
d885bc25f6d6b7f2bed6c360c4182759018c010914bbd263
/* ********************************************************************* * * This file is part of Full Metal Galaxy. * http://www.fullmetalgalaxy.com * * Full Metal Galaxy 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. * * Full Metal Galaxy 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 Full Metal Galaxy. * If not, see <http://www.gnu.org/licenses/>. * * Copyright 2010 to 2015 Vincent Legendre * * *********************************************************************/ package com.fullmetalgalaxy.client.game.board; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.fullmetalgalaxy.client.AppMain; import com.fullmetalgalaxy.client.game.GameEngine; import com.fullmetalgalaxy.model.Company; import com.fullmetalgalaxy.model.EnuColor; import com.fullmetalgalaxy.model.persist.EbRegistration; import com.fullmetalgalaxy.model.persist.EbTeam; import com.fullmetalgalaxy.model.persist.gamelog.EbGameJoin; import com.fullmetalgalaxy.model.ressources.Messages; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Random; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.VerticalPanel; /** * @author Kroc * * During the game join process, this dialog ask player to choose his color. */ public class DlgJoinChooseColor extends DialogBox { // UI private ListBox m_companySelection = new ListBox(); private Image m_companyPreview = new Image(); private ListBox m_colorSelection = new ListBox(); private Image m_colorPreview = new Image(); private Button m_btnOk = new Button( MAppBoard.s_messages.ok() ); private Button m_btnCancel = new Button( MAppBoard.s_messages.cancel() ); private Panel m_panel = new VerticalPanel(); private static DlgJoinChooseColor s_dlg = null; public static DlgJoinChooseColor instance() { if( s_dlg == null ) { s_dlg = new DlgJoinChooseColor(); } return s_dlg; } /** * */ public DlgJoinChooseColor() { // auto hide / modal super( false, true ); // Set the dialog box's caption. setText( MAppBoard.s_messages.unitsTitle() ); // add company list widget // ======================= List<Company> freeCompany = new ArrayList<Company>(); for( Company company : Company.values() ) { if( company != Company.Freelancer ) { freeCompany.add( company ); } } if( !GameEngine.model().getGame().isTeamAllowed() ) { // remove already chosen company for( EbTeam team : GameEngine.model().getGame().getTeams() ) { if( team.getCompany() != null && team.getCompany() != Company.Freelancer ) { freeCompany.remove( team.getCompany() ); } } freeCompany.add( 0, Company.Freelancer ); } else { m_panel.add( new HTML( "<b>" + MAppBoard.s_messages.warningTeamAllowed() + "</b>" ) ); if( GameEngine.model().getGame().getMaxTeamAllowed() <= GameEngine.model().getGame() .getTeams().size() ) { // player shouldn't choose other team freeCompany.clear(); for( EbTeam team : GameEngine.model().getGame().getTeams() ) { freeCompany.add( team.getCompany() ); } } } for( Company company : freeCompany ) { m_companySelection.addItem( company.getFullName(), company.toString() ); } m_companySelection.setSelectedIndex( Random.nextInt( m_companySelection.getItemCount() ) ); Company company = Company.valueOf( m_companySelection.getValue( m_companySelection .getSelectedIndex() ) ); m_companyPreview.setUrl( "/images/avatar/" + company + ".jpg" ); m_companySelection.addChangeHandler( new ChangeHandler() { @Override public void onChange(ChangeEvent p_event) { Company company = Company.valueOf( m_companySelection.getValue( m_companySelection .getSelectedIndex() ) ); m_companyPreview.setUrl( "/images/avatar/" + company + ".jpg" ); } } ); Panel hpanel = new HorizontalPanel(); hpanel.add( m_companySelection ); hpanel.add( m_companyPreview ); m_panel.add( new HTML( "<b>" + MAppBoard.s_messages.chooseCompany() + "</b>" ) ); m_panel.add( hpanel ); // add color list widget // ===================== Set<EnuColor> freeColors = null; if( GameEngine.model().getGame().getSetRegistration().size() >= GameEngine.model().getGame() .getMaxNumberOfPlayer() ) { // this is a player replacement: don't allow company selection m_companySelection.setVisible( false ); freeColors = GameEngine.model().getGame().getFreeRegistrationColors(); } else { freeColors = GameEngine.model().getGame().getFreePlayersColors(); } for( EnuColor color : freeColors ) { if( color.getValue() != EnuColor.None ) { m_colorSelection.addItem( Messages.getColorString( 0, color.getValue() ), ""+color.getValue() ); } } m_colorSelection.setSelectedIndex( Random.nextInt( m_colorSelection.getItemCount() ) ); // initialize company icon int colorValue = Integer.parseInt( m_colorSelection.getValue( m_colorSelection.getSelectedIndex() )); EbRegistration registration = GameEngine.model().getGame().getRegistrationByColor( colorValue ); if( registration != null && registration.getTeam( GameEngine.model().getGame() ) != null ) { m_companyPreview.setUrl( "/images/avatar/" + registration.getTeam( GameEngine.model().getGame() ).getCompany() + ".jpg" ); } // initialize color icon m_colorPreview.setUrl( "/images/board/" + (new EnuColor( colorValue )).toString() + "/preview.jpg" ); m_colorSelection.addChangeHandler( new ChangeHandler() { @Override public void onChange(ChangeEvent p_event) { int colorValue = Integer.parseInt( m_colorSelection.getValue( m_colorSelection.getSelectedIndex() )); EnuColor color = new EnuColor(colorValue); m_colorPreview.setUrl( "/images/board/" + color.toString() + "/preview.jpg" ); m_btnOk.setEnabled( true ); // for replacement: search corresponding team EbRegistration registration = GameEngine.model().getGame().getRegistrationByColor( colorValue ); if( registration != null && registration.getTeam( GameEngine.model().getGame() ) != null ) { m_companyPreview.setUrl( "/images/avatar/" + registration.getTeam( GameEngine.model().getGame() ).getCompany() + ".jpg" ); } } } ); hpanel = new HorizontalPanel(); hpanel.add( m_colorSelection ); hpanel.add( m_colorPreview ); m_panel.add( new HTML( "<b>" + MAppBoard.s_messages.chooseColor() + "</b>" ) ); m_panel.add( hpanel ); // add buttons // =========== hpanel = new HorizontalPanel(); // add cancel button m_btnCancel.addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent p_event) { hide(); } } ); hpanel.add( m_btnCancel ); // add OK button m_btnOk.addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent p_event) { int colorValue = Integer.parseInt( m_colorSelection.getValue( m_colorSelection .getSelectedIndex() ) ); EnuColor color = new EnuColor( colorValue ); EbGameJoin action = new EbGameJoin(); Company company = Company.Freelancer; try { company = Company.valueOf( m_companySelection.getValue( m_companySelection .getSelectedIndex() ) ); } catch( Exception e ) { } action.setCompany( company ); action.setGame( GameEngine.model().getGame() ); action.setAccountId( AppMain.instance().getMyAccount().getId() );
[ " action.setAccount( AppMain.instance().getMyAccount() );" ]
819
lcc
java
null
b81d989e514c39c2fbe5246f88c81834d4b9daf9ea103acc
# # Copyright (C) 2018 Red Hat, Inc. # # 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, see <http://www.gnu.org/licenses/>. # import logging log = logging.getLogger("composer-cli") import os import sys import json from urllib.parse import urlparse, urlunparse from composer.unix_socket import UnixHTTPConnectionPool def api_url(api_version, url): """Return the versioned path to the API route :param api_version: The version of the API to talk to. eg. "0" :type api_version: str :param url: The API route to talk to :type url: str :returns: The full url to use for the route and API version :rtype: str """ return os.path.normpath("/api/v%s/%s" % (api_version, url)) def append_query(url, query): """Add a query argument to a URL The query should be of the form "param1=what&param2=ever", i.e., no leading '?'. The new query data will be appended to any existing query string. :param url: The original URL :type url: str :param query: The query to append :type query: str :returns: The new URL with the query argument included :rtype: str """ url_parts = urlparse(url) if url_parts.query: new_query = url_parts.query + "&" + query else: new_query = query return urlunparse([url_parts[0], url_parts[1], url_parts[2], url_parts[3], new_query, url_parts[5]]) def get_url_raw(socket_path, url): """Return the raw results of a GET request :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to request :type url: str :returns: The raw response from the server :rtype: str """ http = UnixHTTPConnectionPool(socket_path) r = http.request("GET", url) if r.status == 400: err = json.loads(r.data.decode("utf-8")) if "status" in err and err["status"] == False: msgs = [e["msg"] for e in err["errors"]] raise RuntimeError(", ".join(msgs)) return r.data.decode('utf-8') def get_url_json(socket_path, url): """Return the JSON results of a GET request :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to request :type url: str :returns: The json response from the server :rtype: dict """ http = UnixHTTPConnectionPool(socket_path) r = http.request("GET", url) return json.loads(r.data.decode('utf-8')) def get_url_json_unlimited(socket_path, url, total_fn=None): """Return the JSON results of a GET request For URLs that use offset/limit arguments, this command will fetch all results for the given request. :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to request :type url: str :returns: The json response from the server :rtype: dict """ def default_total_fn(data): """Return the total number of available results""" return data["total"] http = UnixHTTPConnectionPool(socket_path) # Start with limit=0 to just get the number of objects total_url = append_query(url, "limit=0") r_total = http.request("GET", total_url) json_total = json.loads(r_total.data.decode('utf-8')) # Where to get the total from if not total_fn: total_fn = default_total_fn # Add the "total" returned by limit=0 as the new limit unlimited_url = append_query(url, "limit=%d" % total_fn(json_total)) r_unlimited = http.request("GET", unlimited_url) return json.loads(r_unlimited.data.decode('utf-8')) def delete_url_json(socket_path, url): """Send a DELETE request to the url and return JSON response :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to send DELETE to :type url: str :returns: The json response from the server :rtype: dict """ http = UnixHTTPConnectionPool(socket_path) r = http.request("DELETE", url) return json.loads(r.data.decode("utf-8")) def post_url(socket_path, url, body): """POST raw data to the URL :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to send POST to :type url: str :param body: The data for the body of the POST :type body: str :returns: The json response from the server :rtype: dict """ http = UnixHTTPConnectionPool(socket_path) r = http.request("POST", url, body=body.encode("utf-8")) return json.loads(r.data.decode("utf-8")) def post_url_toml(socket_path, url, body): """POST a TOML string to the URL :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to send POST to :type url: str :param body: The data for the body of the POST :type body: str :returns: The json response from the server :rtype: dict """ http = UnixHTTPConnectionPool(socket_path) r = http.request("POST", url, body=body.encode("utf-8"), headers={"Content-Type": "text/x-toml"}) return json.loads(r.data.decode("utf-8")) def post_url_json(socket_path, url, body): """POST some JSON data to the URL :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to send POST to :type url: str :param body: The data for the body of the POST :type body: str :returns: The json response from the server :rtype: dict """ http = UnixHTTPConnectionPool(socket_path) r = http.request("POST", url, body=body.encode("utf-8"), headers={"Content-Type": "application/json"}) return json.loads(r.data.decode("utf-8")) def get_filename(headers): """Get the filename from the response header :param response: The urllib3 response object :type response: Response :raises: RuntimeError if it cannot find a filename in the header :returns: Filename from content-disposition header :rtype: str """ log.debug("Headers = %s", headers) if "content-disposition" not in headers: raise RuntimeError("No Content-Disposition header; cannot get filename") try: k, _, v = headers["content-disposition"].split(";")[1].strip().partition("=") if k != "filename": raise RuntimeError("No filename= found in content-disposition header") except RuntimeError: raise except Exception as e: raise RuntimeError("Error parsing filename from content-disposition header: %s" % str(e)) return os.path.basename(v) def download_file(socket_path, url, progress=True): """Download a file, saving it to the CWD with the included filename :param socket_path: Path to the Unix socket to use for API communication :type socket_path: str :param url: URL to send POST to :type url: str """ http = UnixHTTPConnectionPool(socket_path) r = http.request("GET", url, preload_content=False) if r.status == 400:
[ " err = json.loads(r.data.decode(\"utf-8\"))" ]
962
lcc
python
null
3577964dff527ef6068237089eaaf8be6c4ce4aa3ba45df8
#region License // Copyright (c) 2013, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This file is part of the ClearCanvas RIS/PACS open source project. // // The ClearCanvas RIS/PACS open source project 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. // // The ClearCanvas RIS/PACS open source project 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 // the ClearCanvas RIS/PACS open source project. If not, see // <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Generic; using ClearCanvas.Common; using ClearCanvas.Desktop; using ClearCanvas.Desktop.Tables; using ClearCanvas.Enterprise.Common; using ClearCanvas.Ris.Application.Common; using ClearCanvas.Ris.Application.Common.BrowsePatientData; using ClearCanvas.Ris.Application.Common.RegistrationWorkflow.OrderEntry; using ClearCanvas.Ris.Client.Formatting; using ClearCanvas.Common.Utilities; namespace ClearCanvas.Ris.Client.Workflow { /// <summary> /// Defines an interface for providing custom pages to be displayed in the merge orders component. /// </summary> public interface IMergeOrdersPageProvider : IExtensionPageProvider<IMergeOrdersPage, IMergeOrdersContext> { } /// <summary> /// Defines an interface to a custom merge orders page. /// </summary> public interface IMergeOrdersPage : IExtensionPage { } /// <summary> /// Defines an interface for providing a custom page with access to the merge orders context. /// </summary> public interface IMergeOrdersContext { event EventHandler DryRunMergedOrderChanged; OrderDetail DryRunMergedOrder { get; } } /// <summary> /// Defines an extension point for adding custom pages to the merge orders component. /// </summary> [ExtensionPoint] public class MergeOrdersPageProviderExtensionPoint : ExtensionPoint<IMergeOrdersPageProvider> { } /// <summary> /// Extension point for views onto <see cref="MergeOrdersComponent"/>. /// </summary> [ExtensionPoint] public sealed class MergeOrdersComponentViewExtensionPoint : ExtensionPoint<IApplicationComponentView> { } /// <summary> /// MergeOrdersComponent class. /// </summary> [AssociateView(typeof(MergeOrdersComponentViewExtensionPoint))] public class MergeOrdersComponent : ApplicationComponent { class MergeOrdersTable : Table<OrderDetail> { public MergeOrdersTable() { ITableColumn accesionNumberColumn; this.Columns.Add(accesionNumberColumn = new TableColumn<OrderDetail, string>(SR.ColumnAccessionNumber, o => AccessionFormat.Format(o.AccessionNumber), 0.25f)); this.Columns.Add(new TableColumn<OrderDetail, string>(SR.ColumnImagingService, o => o.DiagnosticService.Name, 0.75f)); this.Sort(new TableSortParams(accesionNumberColumn, true)); } } class MergeOrdersContext : IMergeOrdersContext { private readonly MergeOrdersComponent _owner; public MergeOrdersContext(MergeOrdersComponent owner) { _owner = owner; } public event EventHandler DryRunMergedOrderChanged; public OrderDetail DryRunMergedOrder { get { return _owner._dryRunMergedOrder; } } internal void NotifyDryRunMergedOrderChanged() { EventsHelper.Fire(DryRunMergedOrderChanged, this, EventArgs.Empty); } } private readonly List<EntityRef> _orderRefs; private readonly MergeOrdersTable _ordersTable; private OrderDetail _selectedOrder; private OrderDetail _dryRunMergedOrder; private TabComponentContainer _mergedOrderViewComponentContainer; private ChildComponentHost _mergedOrderPreviewComponentHost; private MergedOrderDetailViewComponent _orderPreviewComponent; private AttachedDocumentPreviewComponent _attachmentSummaryComponent; private readonly List<IMergeOrdersPage> _extensionPages = new List<IMergeOrdersPage>(); private readonly MergeOrdersContext _extensionPageContext; public MergeOrdersComponent(List<EntityRef> orderRefs) { _orderRefs = orderRefs; _ordersTable = new MergeOrdersTable(); _extensionPageContext = new MergeOrdersContext(this); } public override void Start() { _mergedOrderViewComponentContainer = new TabComponentContainer(); _mergedOrderPreviewComponentHost = new ChildComponentHost(this.Host, _mergedOrderViewComponentContainer); _mergedOrderPreviewComponentHost.StartComponent(); _mergedOrderViewComponentContainer.Pages.Add(new TabPage(SR.TitleOrder, _orderPreviewComponent = new MergedOrderDetailViewComponent())); _mergedOrderViewComponentContainer.Pages.Add(new TabPage(SR.TitleOrderAttachments, _attachmentSummaryComponent = new AttachedDocumentPreviewComponent(true, AttachmentSite.Order))); // instantiate all extension pages foreach (IMergeOrdersPageProvider pageProvider in new MergeOrdersPageProviderExtensionPoint().CreateExtensions()) { _extensionPages.AddRange(pageProvider.GetPages(_extensionPageContext)); } // add extension pages to container and set initial context // the container will start those components if the user goes to that page foreach (var page in _extensionPages) { _mergedOrderViewComponentContainer.Pages.Add(new TabPage(page.Path, page.GetComponent())); } // Load form data Platform.GetService( delegate(IBrowsePatientDataService service) { var request = new GetDataRequest { GetOrderDetailRequest = new GetOrderDetailRequest() }; foreach (var orderRef in _orderRefs) { request.GetOrderDetailRequest.OrderRef = orderRef; var response = service.GetData(request); _ordersTable.Items.Add(response.GetOrderDetailResponse.Order); } }); _ordersTable.Sort(); // Re-populate orderRef list by sorted accession number _orderRefs.Clear(); _orderRefs.AddRange(CollectionUtils.Map<OrderDetail, EntityRef>(_ordersTable.Items, item => item.OrderRef)); _selectedOrder = CollectionUtils.FirstElement(_ordersTable.Items); DryRunForSelectedOrder(); base.Start(); } public override void Stop() { if (_mergedOrderPreviewComponentHost != null) { _mergedOrderPreviewComponentHost.StopComponent(); _mergedOrderPreviewComponentHost = null; } base.Stop(); } #region Presentation Model public ITable OrdersTable { get { return _ordersTable; } } public ISelection OrdersTableSelection { get { return new Selection(_selectedOrder); } set { var previousSelection = new Selection(_selectedOrder); if (previousSelection.Equals(value)) return; _selectedOrder = (OrderDetail) value.Item; DryRunForSelectedOrder(); NotifyPropertyChanged("SummarySelection"); } } public bool AcceptEnabled { get { return _ordersTable.Items.Count > 0 && _selectedOrder != null && _dryRunMergedOrder != null; } } public ApplicationComponentHost MergedOrderPreviewComponentHost { get { return _mergedOrderPreviewComponentHost; } } public void Accept() { try { var destAccNumber = _selectedOrder.AccessionNumber; var sourceAccNumbers = CollectionUtils.Map(_ordersTable.Items, (OrderDetail o) => o.AccessionNumber); sourceAccNumbers.Remove(destAccNumber); var message = string.Format("Merge order(s) {0} into order {1}?", StringUtilities.Combine(sourceAccNumbers, ","), destAccNumber); if (DialogBoxAction.No == this.Host.DesktopWindow.ShowMessageBox(message, MessageBoxActions.YesNo)) return; var destinationOrderRef = _selectedOrder.OrderRef; var sourceOrderRefs = new List<EntityRef>(_orderRefs); sourceOrderRefs.Remove(_selectedOrder.OrderRef); Platform.GetService( delegate(IOrderEntryService service) { var request = new MergeOrderRequest(sourceOrderRefs, destinationOrderRef) { DryRun = false }; service.MergeOrder(request); }); this.Exit(ApplicationComponentExitCode.Accepted); } catch (Exception e) { ExceptionHandler.Report(e, SR.ExceptionMergeOrdersTool, this.Host.DesktopWindow, () => this.Exit(ApplicationComponentExitCode.Error)); } } public void Cancel() { this.Exit(ApplicationComponentExitCode.None); } #endregion private void DryRunForSelectedOrder() { string failureReason; MergeOrderDryRun(out _dryRunMergedOrder, out failureReason); if (!string.IsNullOrEmpty(failureReason)) this.Host.ShowMessageBox(failureReason, MessageBoxActions.Ok); // Update order preview components if (_dryRunMergedOrder == null) { _orderPreviewComponent.Context = null; _attachmentSummaryComponent.Attachments = new List<AttachmentSummary>(); } else { _orderPreviewComponent.Context = _dryRunMergedOrder; _attachmentSummaryComponent.Attachments = _dryRunMergedOrder.Attachments; } _extensionPageContext.NotifyDryRunMergedOrderChanged(); } private void MergeOrderDryRun(out OrderDetail mergedOrder, out string failureReason) { if (_selectedOrder == null) { failureReason = null; mergedOrder = null; return; } var destinationOrderRef = _selectedOrder.OrderRef; var sourceOrderRefs = new List<EntityRef>(_orderRefs); sourceOrderRefs.Remove(_selectedOrder.OrderRef); try { MergeOrderResponse response = null; Platform.GetService( delegate(IOrderEntryService service) { var request = new MergeOrderRequest(sourceOrderRefs, destinationOrderRef) { DryRun = true };
[ "\t\t\t\t\t\tresponse = service.MergeOrder(request);" ]
849
lcc
csharp
null
653224ff195b272eec8557efa25225d29043896dba76e043
"""Provide functions for phenotype phase plane analysis.""" from itertools import product from typing import TYPE_CHECKING, Dict, List, Optional, Union import numpy as np import pandas as pd from optlang.interface import OPTIMAL from ..exceptions import OptimizationError from ..util import solver as sutil from .helpers import normalize_cutoff from .variability import flux_variability_analysis as fva if TYPE_CHECKING: from optlang.interface import Objective from cobra import Model, Reaction def production_envelope( model: "Model", reactions: List["Reaction"], objective: Union[Dict, "Objective", None] = None, carbon_sources: Optional[List["Reaction"]] = None, points: int = 20, threshold: Optional[float] = None, ) -> pd.DataFrame: """Calculate the objective value conditioned on all flux combinations. The production envelope can be used to analyze a model's ability to produce a given compound conditional on the fluxes for another set of reactions, such as the uptake rates. The model is alternately optimized with respect to minimizing and maximizing the objective and the obtained fluxes are recorded. Ranges to compute production is set to the effective bounds, i.e., the minimum / maximum fluxes that can be obtained given current reaction bounds. Parameters ---------- model : cobra.Model The model to compute the production envelope for. reactions : list of cobra.Reaction A list of reaction objects. objective : dict or cobra.Model.objective, optional The objective (reaction) to use for the production envelope. Use the model's current objective if left missing (default None). carbon_sources : list of cobra.Reaction, optional One or more reactions that are the source of carbon for computing carbon (mol carbon in output over mol carbon in input) and mass yield (gram product over gram output). Only objectives with a carbon containing input and output metabolite is supported. Will identify active carbon sources in the medium if none are specified (default None). points : int, optional The number of points to calculate production for (default 20). threshold : float, optional A cut-off under which flux values will be considered to be zero. If not specified, it defaults to `model.tolerance` (default None). Returns ------- pandas.DataFrame A DataFrame with fixed columns as: - carbon_source : identifiers of carbon exchange reactions - flux_maximum : maximum objective flux - flux_minimum : minimum objective flux - carbon_yield_maximum : maximum yield of a carbon source - carbon_yield_minimum : minimum yield of a carbon source - mass_yield_maximum : maximum mass yield of a carbon source - mass_yield_minimum : minimum mass yield of a carbon source and variable columns (for each input `reactions`) as: - reaction_id : flux at each given point Raises ------ ValueError If model's objective is comprised of multiple reactions. Examples -------- >>> import cobra.test >>> from cobra.flux_analysis import production_envelope >>> model = cobra.test.create_test_model("textbook") >>> production_envelope(model, ["EX_glc__D_e", "EX_o2_e"]) carbon_source flux_minimum carbon_yield_minimum mass_yield_minimum ... 0 EX_glc__D_e 0.0 0.0 NaN ... 1 EX_glc__D_e 0.0 0.0 NaN ... 2 EX_glc__D_e 0.0 0.0 NaN ... 3 EX_glc__D_e 0.0 0.0 NaN ... 4 EX_glc__D_e 0.0 0.0 NaN ... .. ... ... ... ... ... 395 EX_glc__D_e NaN NaN NaN ... 396 EX_glc__D_e NaN NaN NaN ... 397 EX_glc__D_e NaN NaN NaN ... 398 EX_glc__D_e NaN NaN NaN ... 399 EX_glc__D_e NaN NaN NaN ... [400 rows x 9 columns] """ reactions = model.reactions.get_by_any(reactions) objective = model.solver.objective if objective is None else objective data = dict() if carbon_sources is None: c_input = _find_carbon_sources(model) else: c_input = model.reactions.get_by_any(carbon_sources) if c_input is None: data["carbon_source"] = None elif hasattr(c_input, "id"): data["carbon_source"] = c_input.id else: data["carbon_source"] = ", ".join(rxn.id for rxn in c_input) threshold = normalize_cutoff(model, threshold) size = points ** len(reactions) for direction in ("minimum", "maximum"): data[f"flux_{direction}"] = np.full(size, np.nan, dtype=float) data[f"carbon_yield_{direction}"] = np.full(size, np.nan, dtype=float) data[f"mass_yield_{direction}"] = np.full(size, np.nan, dtype=float) grid = pd.DataFrame(data) with model: model.objective = objective objective_reactions = list(sutil.linear_reaction_coefficients(model)) if len(objective_reactions) != 1: raise ValueError( "Cannot calculate yields for objectives with multiple reactions." ) c_output = objective_reactions[0] min_max = fva(model, reactions, fraction_of_optimum=0) min_max[min_max.abs() < threshold] = 0.0 points = list( product( *[ np.linspace( min_max.at[rxn.id, "minimum"], min_max.at[rxn.id, "maximum"], points, endpoint=True, ) for rxn in reactions ] ) ) tmp = pd.DataFrame(points, columns=[rxn.id for rxn in reactions]) grid = pd.concat([grid, tmp], axis=1, copy=False) _add_envelope(model, reactions, grid, c_input, c_output, threshold) return grid def _add_envelope( model: "Model", reactions: List["Reaction"], grid: pd.DataFrame, c_input: List["Reaction"], c_output: List["Reaction"], threshold: float, ) -> None: """Add a production envelope based on the parameters provided. Parameters ---------- model : cobra.Model The model to operate on. reactions : list of cobra.Reaction The input reaction objects. grid : pandas.DataFrame The DataFrame containing all the data regarding the operation. c_input : list of cobra.Reaction The list of reaction objects acting as carbon inputs. c_output : list of cobra.Reaction The list of reaction objects acting as carbon outputs. """ if c_input is not None: input_components = [_reaction_elements(rxn) for rxn in c_input] output_components = _reaction_elements(c_output) try: input_weights = [_reaction_weight(rxn) for rxn in c_input] output_weight = _reaction_weight(c_output) except ValueError: input_weights = [] output_weight = [] else: input_components = [] output_components = [] input_weights = [] output_weight = [] for direction in ("minimum", "maximum"): with model: model.objective_direction = direction for i in range(len(grid)): with model: for rxn in reactions: point = grid.at[i, rxn.id] rxn.bounds = point, point obj_val = model.slim_optimize() if model.solver.status != OPTIMAL: continue grid.at[i, f"flux_{direction}"] = ( 0.0 if np.abs(obj_val) < threshold else obj_val ) if c_input is not None: grid.at[i, f"carbon_yield_{direction}"] = _total_yield( [rxn.flux for rxn in c_input], input_components, obj_val, output_components, ) grid.at[i, f"mass_yield_{direction}"] = _total_yield( [rxn.flux for rxn in c_input], input_weights, obj_val, output_weight, ) def _total_yield( input_fluxes: List[float], input_elements: List[float], output_flux: List[float], output_elements: List[float], ) -> float: """Compute total output per input unit. Units are typically mol carbon atoms or gram of source and product. Parameters ---------- input_fluxes : list of float A list of input reaction fluxes in the same order as the `input_components`. input_elements : list of float A list of reaction components which are in turn list of numbers. output_flux : float The output flux value. output_elements : list A list of stoichiometrically weighted output reaction components. Returns ------- float The ratio between output (mol carbon atoms or grams of product) and input (mol carbon atoms or grams of source compounds). If input flux of carbon sources is zero then numpy.nan is returned. """ carbon_input_flux = sum( _total_components_flux(flux, components, consumption=True) for flux, components in zip(input_fluxes, input_elements) ) carbon_output_flux = _total_components_flux( output_flux, output_elements, consumption=False ) try: return carbon_output_flux / carbon_input_flux except ZeroDivisionError: return np.nan def _reaction_elements(reaction: "Reaction") -> List[float]: """Split metabolites into atoms times their stoichiometric coefficients. Parameters ---------- reaction : cobra.Reaction The reaction whose metabolite components are desired. Returns ------- list of float Each of the reaction's metabolites' desired carbon elements (if any) times that metabolite's stoichiometric coefficient. """ c_elements = [ coeff * met.elements.get("C", 0) for met, coeff in reaction.metabolites.items() ] return [elem for elem in c_elements if elem != 0] def _reaction_weight(reaction: "Reaction") -> List[float]: """Return the metabolite weight times its stoichiometric coefficient. Parameters ---------- reaction : cobra.Reaction The reaction whose metabolite component weights is desired. Returns ------- list of float Each of reaction's metabolite components' weights. Raises ------ ValueError If more than one metabolite comprises the `reaction`. """
[ " if len(reaction.metabolites) != 1:" ]
1,153
lcc
python
null
80bda6d99d3c518ff6465d159112864d8eed9a04c56b1d15
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import datetime import difflib import logging import operator import os from hashlib import md5 from django.conf import settings from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.db import models, transaction, IntegrityError from django.db.models import F from django.template.defaultfilters import escape, truncatechars from django.utils import timezone from django.utils.functional import cached_property from django.utils.http import urlquote from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from translate.filters.decorators import Category from translate.storage import base from pootle.core.log import (TRANSLATION_ADDED, TRANSLATION_CHANGED, TRANSLATION_DELETED, UNIT_ADDED, UNIT_DELETED, UNIT_OBSOLETE, UNIT_RESURRECTED, STORE_ADDED, STORE_OBSOLETE, STORE_DELETED, MUTE_QUALITYCHECK, UNMUTE_QUALITYCHECK, action_log, store_log, log) from pootle.core.mixins import CachedMethods, CachedTreeItem from pootle.core.models import Revision from pootle.core.storage import PootleFileSystemStorage from pootle.core.search import SearchBroker from pootle.core.url_helpers import get_editor_filter, split_pootle_path from pootle.core.utils import dateformat from pootle.core.utils.timezone import datetime_min, make_aware from pootle_misc.aggregate import max_column from pootle_misc.checks import check_names, run_given_filters, get_checker from pootle_misc.util import import_func from pootle_statistics.models import (SubmissionFields, SubmissionTypes, Submission) from .fields import (TranslationStoreField, MultiStringField, PLURAL_PLACEHOLDER, SEPARATOR) from .filetypes import factory_classes from .util import OBSOLETE, UNTRANSLATED, FUZZY, TRANSLATED, get_change_str # # Store States # # Store being modified LOCKED = -1 # Store just created, not parsed yet NEW = 0 # Store just parsed, units added but no quality checks were run PARSED = 1 # Quality checks run CHECKED = 2 ############### Quality Check ############# class QualityCheckManager(models.Manager): def get_queryset(self): """Mimics `select_related(depth=1)` behavior. Pending review.""" return ( super(QualityCheckManager, self).get_queryset().select_related( 'unit', ) ) class QualityCheck(models.Model): """Database cache of results of qualitychecks on unit.""" name = models.CharField(max_length=64, db_index=True) unit = models.ForeignKey("pootle_store.Unit", db_index=True) category = models.IntegerField(null=False, default=Category.NO_CATEGORY) message = models.TextField() false_positive = models.BooleanField(default=False, db_index=True) objects = QualityCheckManager() def __unicode__(self): return self.name @property def display_name(self): return check_names.get(self.name, self.name) @classmethod def delete_unknown_checks(cls): unknown_checks = QualityCheck.objects \ .exclude(name__in=check_names.keys()) unknown_checks.delete() ################# Suggestion ################ class SuggestionManager(models.Manager): def get_queryset(self): """Mimics `select_related(depth=1)` behavior. Pending review.""" return ( super(SuggestionManager, self).get_queryset().select_related( 'unit', 'user', 'reviewer', ) ) def pending(self): return self.get_queryset().filter(state=SuggestionStates.PENDING) class SuggestionStates(object): PENDING = 'pending' ACCEPTED = 'accepted' REJECTED = 'rejected' class Suggestion(models.Model, base.TranslationUnit): """Suggested translation for a :cls:`~pootle_store.models.Unit`, provided by users or automatically generated after a merge. """ target_f = MultiStringField() target_hash = models.CharField(max_length=32, db_index=True) unit = models.ForeignKey('pootle_store.Unit') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name='suggestions', db_index=True) reviewer = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name='reviews', db_index=True) translator_comment_f = models.TextField(null=True, blank=True) state_choices = [ (SuggestionStates.PENDING, _('Pending')), (SuggestionStates.ACCEPTED, _('Accepted')), (SuggestionStates.REJECTED, _('Rejected')), ] state = models.CharField(max_length=16, default=SuggestionStates.PENDING, null=False, choices=state_choices, db_index=True) creation_time = models.DateTimeField(db_index=True, null=True) review_time = models.DateTimeField(null=True, db_index=True) objects = SuggestionManager() ############################ Properties ################################### @property def _target(self): return self.target_f @_target.setter def _target(self, value): self.target_f = value self._set_hash() @property def _source(self): return self.unit._source @property def translator_comment(self, value): return self.translator_comment_f @translator_comment.setter def translator_comment(self, value): self.translator_comment_f = value self._set_hash() ############################ Methods ###################################### def __unicode__(self): return unicode(self.target) def _set_hash(self): string = self.translator_comment_f if string: string = self.target_f + SEPARATOR + string else: string = self.target_f self.target_hash = md5(string.encode("utf-8")).hexdigest() ############### Unit #################### wordcount_f = import_func(settings.POOTLE_WORDCOUNT_FUNC) def count_words(strings): wordcount = 0 for string in strings: wordcount += wordcount_f(string) return wordcount def stringcount(string): try: return len(string.strings) except AttributeError: return 1 TMServer = SearchBroker() class UnitManager(models.Manager): def get_queryset(self): """Mimics `select_related(depth=1)` behavior. Pending review.""" return ( super(UnitManager, self).get_queryset().select_related( 'store', 'submitted_by', 'commented_by', 'reviewed_by', ) ) def get_for_path(self, pootle_path, user): """Returns units that fall below the `pootle_path` umbrella. :param pootle_path: An internal pootle path. :param user: The user who is accessing the units. """
[ " lang, proj, dir_path, filename = split_pootle_path(pootle_path)" ]
588
lcc
python
null
a8df204f2a859a703bf766e6567ed3d50e67fb8e91bc975b
# -*- coding: utf-8 -*- from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('creation', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='AcademicCenter', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('academic_code', models.CharField(unique=True, max_length=100)), ('institution_name', models.CharField(max_length=200)), ('address', models.TextField()), ('pincode', models.PositiveIntegerField()), ('resource_center', models.BooleanField()), ('rating', models.PositiveSmallIntegerField()), ('contact_person', models.TextField()), ('remarks', models.TextField()), ('status', models.BooleanField()), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'Academic Center', }, ), migrations.CreateModel( name='City', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('updated', models.DateTimeField(auto_now=True, null=True)), ], ), migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='CourseMap', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('test', models.BooleanField(default=False)), ('category', models.PositiveIntegerField(default=0)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ('foss',), }, ), migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ['name'], }, ), migrations.CreateModel( name='District', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(max_length=3)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('updated', models.DateTimeField(auto_now=True, null=True)), ], ), migrations.CreateModel( name='EventsNotification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('role', models.PositiveSmallIntegerField(default=0)), ('category', models.PositiveSmallIntegerField(default=0)), ('categoryid', models.PositiveIntegerField(default=0)), ('status', models.PositiveSmallIntegerField(default=0)), ('message', models.CharField(max_length=255)), ('created', models.DateTimeField(auto_now_add=True)), ('academic', models.ForeignKey(to='events.AcademicCenter')), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='FossMdlCourses', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('mdlcourse_id', models.PositiveIntegerField()), ('mdlquiz_id', models.PositiveIntegerField()), ('foss', models.ForeignKey(to='creation.FossCategory')), ], ), migrations.CreateModel( name='InstituteCategory', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'Institute Categorie', }, ), migrations.CreateModel( name='InstituteType', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='Invigilator', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('status', models.PositiveSmallIntegerField(default=0)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('academic', models.ForeignKey(to='events.AcademicCenter')), ('appoved_by', models.ForeignKey(related_name='invigilator_approved_by', blank=True, to=settings.AUTH_USER_MODEL, null=True)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='LabCourse', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='Location', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('pincode', models.PositiveIntegerField()), ('created', models.DateTimeField(auto_now_add=True, null=True)), ('updated', models.DateTimeField(auto_now=True)), ('district', models.ForeignKey(to='events.District')), ], ), migrations.CreateModel( name='Organiser', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('status', models.PositiveSmallIntegerField(default=0)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('academic', models.ForeignKey(blank=True, to='events.AcademicCenter', null=True)), ('appoved_by', models.ForeignKey(related_name='organiser_approved_by', blank=True, to=settings.AUTH_USER_MODEL, null=True)), ('user', models.OneToOneField(related_name='organiser', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='OrganiserNotification', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Permission', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('assigned_by', models.ForeignKey(related_name='permission_assigned_by', to=settings.AUTH_USER_MODEL)), ('district', models.ForeignKey(related_name='permission_district', to='events.District', null=True)), ('institute', models.ForeignKey(related_name='permission_district', to='events.AcademicCenter', null=True)), ('institute_type', models.ForeignKey(related_name='permission_institution_type', to='events.InstituteType', null=True)), ], ), migrations.CreateModel( name='PermissionType', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=200)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='ResourcePerson', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('assigned_by', models.PositiveIntegerField()), ('status', models.BooleanField()), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'Resource Person', }, ), migrations.CreateModel( name='Semester', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=50)), ('even', models.BooleanField(default=True)), ], ), migrations.CreateModel( name='SingleTraining', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('training_type', models.PositiveIntegerField(default=0)), ('tdate', models.DateField()), ('ttime', models.TimeField()), ('status', models.PositiveSmallIntegerField(default=0)), ('participant_count', models.PositiveIntegerField(default=0)), ('created', models.DateTimeField()), ('updated', models.DateTimeField()), ('academic', models.ForeignKey(to='events.AcademicCenter')), ('course', models.ForeignKey(to='events.CourseMap')), ('language', models.ForeignKey(to='creation.Language')), ('organiser', models.ForeignKey(to='events.Organiser')), ], ), migrations.CreateModel( name='SingleTrainingAttendance', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('firstname', models.CharField(max_length=100, null=True)), ('lastname', models.CharField(max_length=100, null=True)), ('gender', models.CharField(max_length=10, null=True)), ('email', models.EmailField(max_length=254, null=True)), ('password', models.CharField(max_length=100, null=True)), ('count', models.PositiveSmallIntegerField(default=0)), ('status', models.PositiveSmallIntegerField(default=0)), ('created', models.DateTimeField()), ('updated', models.DateTimeField()), ('training', models.ForeignKey(to='events.SingleTraining')), ], ), migrations.CreateModel( name='State', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('code', models.CharField(max_length=3)), ('name', models.CharField(max_length=50)), ('slug', models.CharField(max_length=100)), ('latitude', models.DecimalField(null=True, max_digits=10, decimal_places=4, blank=True)), ('longtitude', models.DecimalField(null=True, max_digits=10, decimal_places=4, blank=True)), ('img_map_area', models.TextField()),
[ " ('created', models.DateTimeField(auto_now_add=True, null=True))," ]
519
lcc
python
null
8d8cddfebc329d8bed250acfd102274d7ccd8f8bf08e4b85
import sys import pdb from socket import IPPROTO_TCP, IPPROTO_UDP, IPPROTO_ICMP import logging from ipaddr import IPv4Address from struct import pack as spack from pytricia import PyTricia import socket from fslib.node import Node, PortInfo from fslib.link import NullLink from fslib.common import fscore, get_logger from fslib.flowlet import Flowlet, FlowIdent from fslib.util import default_ip_to_macaddr from fslib.configurator import FsConfigurator from fslib.openflow import load_pox_component, load_odl_component from pox.openflow import libopenflow_01 as oflib import pox.core from pox.lib.addresses import * import pox.lib.packet as pktlib from pox.lib.util import dpid_to_str import pox.openflow.of_01 as ofcore from pox.datapaths.switch import SoftwareSwitch class UnhandledPoxPacketFlowletTranslation(Exception): pass class PoxFlowlet(Flowlet): __slots__ = ['origpkt'] def __init__(self, ident): Flowlet.__init__(self, ident) self.origpkt = None class OpenflowMessage(Flowlet): __slots__ = ['ofmsg'] def __init__(self, ident, ofmsg): Flowlet.__init__(self, ident) self.ofmsg = ofmsg self.bytes = len(ofmsg) def flowlet_to_packet(flowlet): if hasattr(flowlet, "origpkt"): return getattr(flowlet, "origpkt") ident = flowlet.ident.key etherhdr = pktlib.ethernet() etherhdr.src = EthAddr(flowlet.srcmac) etherhdr.dst = EthAddr(flowlet.dstmac) etherhdr.type = pktlib.ethernet.IP_TYPE ipv4 = pktlib.ipv4() ipv4.srcip = IPAddr(ident.srcip) ipv4.dstip = IPAddr(ident.dstip) ipv4.protocol = ident.ipproto ipv4.tos = flowlet.iptos iplen = flowlet.bytes / flowlet.pkts ipv4.iplen = iplen payloadlen = 0 etherhdr.payload = ipv4 if ident.ipproto == IPPROTO_ICMP: layer4 = pktlib.icmp() layer4.type = ident.dport >> 8 layer4.code = ident.dport & 0x00FF payloadlen = max(iplen-28,0) elif ident.ipproto == IPPROTO_UDP: layer4 = pktlib.udp() layer4.srcport = ident.sport layer4.dstport = ident.dport elif ident.ipproto == IPPROTO_TCP: layer4 = pktlib.tcp() layer4.srcport = ident.sport layer4.dstport = ident.dport layer4.flags = flowlet.tcpflags layer4.off = 5 payloadlen = max(iplen-40,0) layer4.tcplen = payloadlen layer4.payload = spack('{}x'.format(payloadlen)) else: raise UnhandledPoxPacketFlowletTranslation("Can't translate IP protocol {} from flowlet to POX packet".format(fident.ipproto)) ipv4.payload = layer4 etherhdr.origflet = flowlet return etherhdr def packet_to_flowlet(pkt): try: return getattr(pkt, "origflet") except AttributeError,e: log = get_logger() flet = None ip = pkt.find('ipv4') if ip is None: flet = PoxFlowlet(FlowIdent()) log.debug("Received non-IP packet {} from POX: there's no direct translation to fs".format(str(pkt.payload))) else: dport = sport = tcpflags = 0 if ip.protocol == IPPROTO_TCP: tcp = ip.payload sport = tcp.srcport dport = tcp.dstport tcpflags = tcp.flags log.debug("Translating POX TCP packet to fs {}".format(tcp)) elif ip.protocol == IPPROTO_UDP: udp = ip.payload sport = udp.srcport dport = udp.dstport log.debug("Translating POX UDP packet to fs {}".format(udp)) elif ip.protocol == IPPROTO_ICMP: icmp = ip.payload dport = (icmp.type << 8) | icmp.code log.debug("Translating POX ICMP packet to fs {}".format(icmp)) else: log.warn("Received unhandled IPv4 packet {} from POX: can't translate to fs".format(str(ip.payload))) flet = PoxFlowlet(FlowIdent(srcip=ip.srcip, dstip=ip.dstip, ipproto=ip.protocol, sport=sport, dport=dport)) flet.tcpflags = tcpflags flet.iptos = ip.tos flet.srcmac = pkt.src flet.dstmac = pkt.dst flet.pkts = 1 flet.bytes = len(pkt) flet.origpkt = pkt return flet class PoxBridgeSoftwareSwitch(SoftwareSwitch): def __init__(self, *args, **kwargs): SoftwareSwitch.__init__(self, *args, **kwargs) def _output_packet_physical(self, packet, port_num): self.forward(packet, port_num) SoftwareSwitch._output_packet_physical(self, packet, port_num) def set_output_packet_callback(self, fn): self.forward = fn # start here ''' def _get_table_entry(self, dpid): print self.pox_switch ''' class OpenflowSwitch(Node): __slots__ = ['dpid', 'pox_switch', 'controller_name', 'controller_links', 'ipdests', 'interface_to_port_map', 'trafgen_ip', 'autoack', 'trafgen_mac', 'dstmac_cache', 'trace','tracePkt'] def __init__(self, name, measurement_config, **kwargs): Node.__init__(self, name, measurement_config, **kwargs) self.dpid = abs(hash(name)) self.dstmac_cache = {} self.pox_switch = PoxBridgeSoftwareSwitch(self.dpid, name=name, ports=0, miss_send_len=2**16, max_buffers=2**8, features=None) self.pox_switch.set_connection(self) self.pox_switch.set_output_packet_callback(self. send_packet) self.controller_name = kwargs.get('controller', 'controller') self.autoack = bool(eval(kwargs.get('autoack', 'False'))) self.controller_links = {} self.interface_to_port_map = {} self.trace = bool(eval(kwargs.get('trace', 'False'))) self.tracePkt = bool(eval(kwargs.get('tracePkt','False'))) self.ipdests = PyTricia() for prefix in kwargs.get('ipdests','').split(): self.ipdests[prefix] = True # explicitly add a localhost link/interface ipa,ipb = [ ip for ip in next(FsConfigurator.link_subnetter).iterhosts() ] remotemac = default_ip_to_macaddr(ipb) self.add_link(NullLink, ipa, ipb, 'remote', remotemac=remotemac) self.trafgen_ip = str(ipa) self.trafgen_mac = remotemac self.dstmac_cache[self.name] = remotemac @property def remote_macaddr(self): return self.trafgen_mac def send_packet(self, packet, port_num): '''Forward a data plane packet out a given port''' flet = packet_to_flowlet(packet) # has packet reached destination? if flet is None or self.ipdests.get(flet.dstaddr, None): return pinfo = self.ports[port_num] # self.logger.debug("Switch sending translated packet {}->{} from {}->{} on port {} to {}".format(packet, flet, flet.srcmac, flet.dstmac, port_num, pinfo.link.egress_name)) pinfo.link.flowlet_arrival(flet, self.name, pinfo.remoteip) def send(self, ofmessage): '''Callback function for POX SoftwareSwitch to send an outgoing OF message to controller.''' if not self.started: # self.logger.debug("OF switch-to-controller deferred message {}".format(ofmessage)) evid = 'deferred switch->controller send' fscore().after(0.0, evid, self.send, ofmessage) else: # self.logger.debug("OF switch-to-controller {} - {}".format(str(self.controller_links[self.controller_name]), ofmessage)) clink = self.controller_links[self.controller_name] self.controller_links[self.controller_name].flowlet_arrival(OpenflowMessage(FlowIdent(), ofmessage), self.name, self.controller_name) def set_message_handler(self, *args): '''Dummy callback function for POX SoftwareSwitchBase''' pass def process_packet(self, poxpkt, inputport): '''Process an incoming POX packet. Mainly want to check whether it's an ARP and update our ARP "table" state''' # self.logger.debug("Switch {} processing packet: {}".format(self.name, str(poxpkt))) if poxpkt.type == poxpkt.ARP_TYPE: if poxpkt.payload.opcode == pktlib.arp.REQUEST: self.logger.debug("Got ARP request: {}".format(str(poxpkt.payload))) arp = poxpkt.payload dstip = str(IPv4Address(arp.protodst)) srcip = str(IPv4Address(arp.protosrc)) if dstip in self.interface_to_port_map: portnum = self.interface_to_port_map[dstip]
[ " pinfo = self.ports[portnum]" ]
720
lcc
python
null
f18f638df2a7be9849603948e255d240c5646454c2a0a5a0
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any 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, see <http://www.gnu.org/licenses/>. */ /* * AbstractRecentItemsHandler.java * Copyright (C) 2013-2016 University of Waikato, Hamilton, New Zealand */ package adams.gui.core; import adams.core.Properties; import adams.core.logging.LoggingObject; import adams.env.Environment; import adams.gui.event.RecentItemEvent; import adams.gui.event.RecentItemListener; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import java.awt.event.ActionEvent; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.logging.Level; /** * Ancestor for classes that handle a list of recent items. Reads/writes them from/to * a props file in the application's home directory. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ * @see Environment#getHome() * @param <M> the type of menu to use * @param <T> the type of item to use */ public abstract class AbstractRecentItemsHandler<M, T> extends LoggingObject { /** for serialization. */ private static final long serialVersionUID = 7532226757387619342L; /** the props file to use. */ protected String m_PropertiesFile; /** the prefix for the properties. */ protected String m_PropertyPrefix; /** the maximum number of items to keep. */ protected int m_MaxCount; /** whether to add keyboard shortcuts. */ protected boolean m_AddShortcuts; /** the menu to add the items as sub-items to. */ protected M m_Menu; /** the items. */ protected List<T> m_RecentItems; /** whether to ignore changes temporarily. */ protected boolean m_IgnoreChanges; /** the event listeners. */ protected HashSet<RecentItemListener<M,T>> m_Listeners; /** * Initializes the handler with a maximum of 5 items. * * @param propsFile the props file to store the items in * @param menu the menu to add the recent items as subitems to */ public AbstractRecentItemsHandler(String propsFile, M menu) { this(propsFile, 5, menu); } /** * Initializes the handler. * * @param propsFile the props file to store the items in * @param maxCount the maximum number of items to keep in menu * @param menu the menu to add the recent items as subitems to */ public AbstractRecentItemsHandler(String propsFile, int maxCount, M menu) { this(propsFile, null, maxCount, menu); } /** * Initializes the handler. * * @param propsFile the props file to store the items in * @param propPrefix the properties prefix, use null to ignore * @param maxCount the maximum number of items to keep in menu * @param menu the menu to add the recent items as subitems to */ public AbstractRecentItemsHandler(String propsFile, String propPrefix, int maxCount, M menu) { super(); if (!((menu instanceof JMenu) || (menu instanceof JPopupMenu))) throw new IllegalArgumentException( "Menu must be derived from " + JMenu.class.getName() + " or " + JPopupMenu.class.getName() + ", provided: " + menu.getClass().getName()); m_PropertiesFile = Environment.getInstance().getHome() + File.separator + new File(propsFile).getName(); m_PropertyPrefix = propPrefix; m_MaxCount = maxCount; m_Menu = menu; m_RecentItems = new ArrayList<T>(); m_IgnoreChanges = false; m_Listeners = new HashSet<RecentItemListener<M,T>>(); m_AddShortcuts = true; readProps(); updateMenu(); } /** * Returns the props file used to store the recent items in. * * @return the filename */ public String getPropertiesFile() { return m_PropertiesFile; } /** * Returns the prefix for the property names. * * @return the prefix */ public String getPropertyPrefix() { return m_PropertyPrefix; } /** * Returns the maximum number of items to keep. * * @return the maximum number */ public int getMaxCount() { return m_MaxCount; } /** * Sets whether to add shortcuts to the menu. * * @param value true if to add shortcuts */ public void setAddShortcuts(boolean value) { m_AddShortcuts = value; updateMenu(); } /** * Returns whether to add shortcuts to the menu. * * @return true if to add shortcuts */ public boolean getAddShortcuts() { return m_AddShortcuts; } /** * Returns the menu to add the recent items as subitems to. * * @return the menu */ public M getMenu() { return m_Menu; } /** * Returns the key to use for the counts in the props file. * * @return the key */ protected abstract String getCountKey(); /** * Returns the key prefix to use for the items in the props file. * * @return the prefix */ protected abstract String getItemPrefix(); /** * Turns an object into a string for storing in the props. * * @param obj the object to convert * @return the string representation */ protected abstract String toString(T obj); /** * Turns the string obtained from the props into an object again. * * @param s the string representation * @return the parsed object */ protected abstract T fromString(String s); /** * Adds the prefix to the property name if provided. * * @param property the property to expand * @return the expanded property name */ protected String expand(String property) { if (m_PropertyPrefix == null) return property; else return m_PropertyPrefix + property; } /** * Loads the properties file from disk, if possible. * * @return the properties file */ protected Properties loadProps() { Properties result; File file; try { result = new Properties(); file = new File(m_PropertiesFile); if (file.exists()) result.load(m_PropertiesFile); } catch (Exception e) { getLogger().log(Level.SEVERE, "Failed to load properties: " + m_PropertiesFile, e); result = new Properties(); } return result; } /** * Checks the item after obtaining from the props file. * <br><br> * Default implementation performs no checks and always returns true. * * @param item the item to check * @return true if checks passed */ protected boolean check(T item) { return true; } /** * Reads the recent items from the props file. */ protected void readProps() { int count; Properties props; int i; String itemStr; T item; m_IgnoreChanges = true; props = loadProps(); count = props.getInteger(expand(getCountKey()), 0); m_RecentItems.clear(); for (i = count - 1; i >= 0; i--) { itemStr = props.getPath(expand(getItemPrefix() + i), ""); if (itemStr.length() > 0) { item = fromString(itemStr); if (check(item)) addRecentItem(item); } } m_IgnoreChanges = false; } /** * Writes the current recent items back to the props file. */ protected synchronized void writeProps() { Properties props; int i; props = loadProps(); props.setInteger(expand(getCountKey()), m_RecentItems.size()); for (i = 0; i < m_RecentItems.size(); i++) props.setProperty(expand(getItemPrefix() + i), toString(m_RecentItems.get(i))); try { props.save(m_PropertiesFile); } catch (Exception e) { getLogger().log(Level.SEVERE, "Failed to write properties: " + m_PropertiesFile, e); } } /** * Hook method which gets executed just before the menu gets updated. * <br><br> * Default implementation does nothing. */ protected void preUpdateMenu() { } /** * Generates the text for the menuitem. * * @param index the index of the item * @param item the item itself * @return the generated text */ protected abstract String createMenuItemText(int index, T item); /** * Updates the menu. */ protected void doUpdateMenu() { int i; JMenuItem menuitem; // clear menu if (m_Menu instanceof JMenu) { ((JMenu) m_Menu).removeAll(); ((JMenu) m_Menu).setEnabled(m_RecentItems.size() > 0); } else if (m_Menu instanceof JPopupMenu) { ((JPopupMenu) m_Menu).removeAll(); ((JPopupMenu) m_Menu).setEnabled(m_RecentItems.size() > 0); } // add menu items for (i = 0; i < m_RecentItems.size(); i++) { final T item = m_RecentItems.get(i); menuitem = new JMenuItem((i+1) + " - " + createMenuItemText(i, item)); if (i < 9) menuitem.setMnemonic(Integer.toString(i+1).charAt(0)); if (i == 9) menuitem.setMnemonic('0'); menuitem.addActionListener((ActionEvent e) -> notifyRecentItemListenersOfSelect(item)); if (m_Menu instanceof JMenu) { if (m_AddShortcuts) { if (i < 9) menuitem.setAccelerator(KeyStroke.getKeyStroke("ctrl pressed " + (i + 1))); if (i == 9) menuitem.setAccelerator(KeyStroke.getKeyStroke("ctrl pressed 0")); } ((JMenu) m_Menu).add(menuitem); } else if (m_Menu instanceof JPopupMenu) ((JPopupMenu) m_Menu).add(menuitem); } // add "clear" if (m_RecentItems.size() > 0) { if (m_Menu instanceof JMenu) ((JMenu) m_Menu).addSeparator(); else if (m_Menu instanceof JPopupMenu) ((JPopupMenu) m_Menu).addSeparator(); menuitem = new JMenuItem("Clear"); menuitem.addActionListener((ActionEvent e) -> removeAll()); if (m_Menu instanceof JMenu) ((JMenu) m_Menu).add(menuitem); else if (m_Menu instanceof JPopupMenu) ((JPopupMenu) m_Menu).add(menuitem); } } /** * Hook method which gets executed just after the menu was updated. * <br><br> * Default implementation does nothing. */ protected void postUpdateMenu() { } /** * Updates the menu with the currently stored recent files. */ protected void updateMenu() { preUpdateMenu(); doUpdateMenu(); postUpdateMenu(); } /** * Adds the item to the internal list. * * @param item the item to add to the list */ public synchronized void addRecentItem(T item) {
[ " item = fromString(toString(item));" ]
1,401
lcc
java
null
e20af03f2ee467f621a8abf4253b8106ed16e82d2aeb0e8c
using System; using System.Collections.Generic; using System.Linq; using Server.Factions; using Server.Mobiles; using Server.Multis; using Server.Targeting; using Server.Engines.VvV; using Server.Items; using Server.Spells; using Server.Network; namespace Server.Items { public interface IRevealableItem { bool CheckReveal(Mobile m); bool CheckPassiveDetect(Mobile m); void OnRevealed(Mobile m); bool CheckWhenHidden { get; } } } namespace Server.SkillHandlers { public class DetectHidden { public static void Initialize() { SkillInfo.Table[(int)SkillName.DetectHidden].Callback = new SkillUseCallback(OnUse); } public static TimeSpan OnUse(Mobile src) { src.SendLocalizedMessage(500819);//Where will you search? src.Target = new InternalTarget(); return TimeSpan.FromSeconds(10.0); } public class InternalTarget : Target { public InternalTarget() : base(12, true, TargetFlags.None) { } protected override void OnTarget(Mobile src, object targ) { bool foundAnyone = false; Point3D p; if (targ is Mobile) p = ((Mobile)targ).Location; else if (targ is Item) p = ((Item)targ).Location; else if (targ is IPoint3D) p = new Point3D((IPoint3D)targ); else p = src.Location; double srcSkill = src.Skills[SkillName.DetectHidden].Value; int range = Math.Max(2, (int)(srcSkill / 10.0)); if (!src.CheckSkill(SkillName.DetectHidden, 0.0, 100.0)) range /= 2; BaseHouse house = BaseHouse.FindHouseAt(p, src.Map, 16); bool inHouse = house != null && house.IsFriend(src); if (inHouse) range = 22; if (range > 0) { IPooledEnumerable inRange = src.Map.GetMobilesInRange(p, range); foreach (Mobile trg in inRange) { if (trg.Hidden && src != trg) { double ss = srcSkill + Utility.Random(21) - 10; double ts = trg.Skills[SkillName.Hiding].Value + Utility.Random(21) - 10; double shadow = Server.Spells.SkillMasteries.ShadowSpell.GetDifficultyFactor(trg); bool houseCheck = inHouse && house.IsInside(trg); if (src.AccessLevel >= trg.AccessLevel && (ss >= ts || houseCheck) && Utility.RandomDouble() > shadow) { if ((trg is ShadowKnight && (trg.X != p.X || trg.Y != p.Y)) || (!houseCheck && !CanDetect(src, trg))) continue; trg.RevealingAction(); trg.SendLocalizedMessage(500814); // You have been revealed! trg.PrivateOverheadMessage(MessageType.Regular, 0x3B2, 500814, trg.NetState); foundAnyone = true; } } } inRange.Free(); IPooledEnumerable itemsInRange = src.Map.GetItemsInRange(p, range); foreach (Item item in itemsInRange) { if (item is LibraryBookcase && Server.Engines.Khaldun.GoingGumshoeQuest3.CheckBookcase(src, item)) { foundAnyone = true; } else { IRevealableItem dItem = item as IRevealableItem; if (dItem == null || (item.Visible && dItem.CheckWhenHidden)) continue; if (dItem.CheckReveal(src)) { dItem.OnRevealed(src); foundAnyone = true; } } } itemsInRange.Free(); } if (!foundAnyone) { src.SendLocalizedMessage(500817); // You can see nothing hidden there. } } } public static void DoPassiveDetect(Mobile src) { if (src == null || src.Map == null || src.Location == Point3D.Zero || src.IsStaff()) return; double ss = src.Skills[SkillName.DetectHidden].Value; if (ss <= 0) return; IPooledEnumerable eable = src.Map.GetMobilesInRange(src.Location, 4); if (eable == null) return; foreach (Mobile m in eable) { if (m == null || m == src || m is ShadowKnight || !CanDetect(src, m)) continue; double ts = (m.Skills[SkillName.Hiding].Value + m.Skills[SkillName.Stealth].Value) / 2; if (src.Race == Race.Elf) ss += 20; if (src.AccessLevel >= m.AccessLevel && Utility.Random(1000) < (ss - ts) + 1) { m.RevealingAction(); m.SendLocalizedMessage(500814); // You have been revealed! } } eable.Free(); eable = src.Map.GetItemsInRange(src.Location, 8); foreach (Item item in eable) { if (!item.Visible && item is IRevealableItem && ((IRevealableItem)item).CheckPassiveDetect(src)) { src.SendLocalizedMessage(1153493); // Your keen senses detect something hidden in the area... } } eable.Free(); } public static bool CanDetect(Mobile src, Mobile target) { if (src.Map == null || target.Map == null || !src.CanBeHarmful(target, false)) return false; // No invulnerable NPC's if (src.Blessed || (src is BaseCreature && ((BaseCreature)src).IsInvulnerable)) return false; if (target.Blessed || (target is BaseCreature && ((BaseCreature)target).IsInvulnerable)) return false; // pet owner, guild/alliance, party if (!Server.Spells.SpellHelper.ValidIndirectTarget(target, src)) return false; // Checked aggressed/aggressors if (src.Aggressed.Any(x => x.Defender == target) || src.Aggressors.Any(x => x.Attacker == target)) return true; // In Fel or Follow the same rules as indirect spells such as wither
[ " return src.Map.Rules == MapRules.FeluccaRules;" ]
562
lcc
csharp
null
ab64e80497dc29027b566fe583c6e6936d54fd063307f698
/* * This file is part of Bitsquare. * * Bitsquare 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. * * Bitsquare 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 Bitsquare. If not, see <http://www.gnu.org/licenses/>. */ package io.bitsquare.trade; import com.google.common.base.Throwables; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.bitsquare.app.Log; import io.bitsquare.app.Version; import io.bitsquare.arbitration.Arbitrator; import io.bitsquare.arbitration.ArbitratorManager; import io.bitsquare.btc.TradeWalletService; import io.bitsquare.btc.WalletService; import io.bitsquare.common.crypto.KeyRing; import io.bitsquare.common.taskrunner.Model; import io.bitsquare.crypto.DecryptedMsgWithPubKey; import io.bitsquare.filter.FilterManager; import io.bitsquare.p2p.NodeAddress; import io.bitsquare.p2p.P2PService; import io.bitsquare.storage.Storage; import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.offer.OpenOfferManager; import io.bitsquare.trade.protocol.trade.ProcessModel; import io.bitsquare.trade.protocol.trade.TradeProtocol; import io.bitsquare.user.User; import javafx.beans.property.*; import org.bitcoinj.core.Coin; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.utils.ExchangeRate; import org.bitcoinj.utils.Fiat; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Date; import java.util.HashSet; import java.util.Set; import static com.google.common.base.Preconditions.checkNotNull; /** * Holds all data which are relevant to the trade, but not those which are only needed in the trade process as shared data between tasks. Those data are * stored in the task model. */ public abstract class Trade implements Tradable, Model { // That object is saved to disc. We need to take care of changes to not break deserialization. private static final long serialVersionUID = Version.LOCAL_DB_VERSION; private static final Logger log = LoggerFactory.getLogger(Trade.class); public enum State { PREPARATION(Phase.PREPARATION), TAKER_FEE_PAID(Phase.TAKER_FEE_PAID), OFFERER_SENT_PUBLISH_DEPOSIT_TX_REQUEST(Phase.DEPOSIT_REQUESTED), TAKER_PUBLISHED_DEPOSIT_TX(Phase.DEPOSIT_PAID), DEPOSIT_SEEN_IN_NETWORK(Phase.DEPOSIT_PAID), // triggered by balance update, used only in error cases TAKER_SENT_DEPOSIT_TX_PUBLISHED_MSG(Phase.DEPOSIT_PAID), OFFERER_RECEIVED_DEPOSIT_TX_PUBLISHED_MSG(Phase.DEPOSIT_PAID), DEPOSIT_CONFIRMED_IN_BLOCK_CHAIN(Phase.DEPOSIT_PAID), BUYER_CONFIRMED_FIAT_PAYMENT_INITIATED(Phase.FIAT_SENT), BUYER_SENT_FIAT_PAYMENT_INITIATED_MSG(Phase.FIAT_SENT), SELLER_RECEIVED_FIAT_PAYMENT_INITIATED_MSG(Phase.FIAT_SENT), SELLER_CONFIRMED_FIAT_PAYMENT_RECEIPT(Phase.FIAT_RECEIVED), SELLER_SENT_FIAT_PAYMENT_RECEIPT_MSG(Phase.FIAT_RECEIVED), BUYER_RECEIVED_FIAT_PAYMENT_RECEIPT_MSG(Phase.FIAT_RECEIVED), BUYER_COMMITTED_PAYOUT_TX(Phase.PAYOUT_PAID), //TODO needed? BUYER_STARTED_SEND_PAYOUT_TX(Phase.PAYOUT_PAID), // not from the success/arrived handler! SELLER_RECEIVED_AND_COMMITTED_PAYOUT_TX(Phase.PAYOUT_PAID), PAYOUT_BROAD_CASTED(Phase.PAYOUT_PAID), WITHDRAW_COMPLETED(Phase.WITHDRAWN); public Phase getPhase() { return phase; } private final Phase phase; State(Phase phase) { this.phase = phase; } } public enum Phase { PREPARATION, TAKER_FEE_PAID, DEPOSIT_REQUESTED, DEPOSIT_PAID, FIAT_SENT, FIAT_RECEIVED, PAYOUT_PAID, WITHDRAWN, DISPUTE } public enum DisputeState { NONE, DISPUTE_REQUESTED, DISPUTE_STARTED_BY_PEER, DISPUTE_CLOSED } public enum TradePeriodState { NORMAL, HALF_REACHED, TRADE_PERIOD_OVER } /////////////////////////////////////////////////////////////////////////////////////////// // Fields /////////////////////////////////////////////////////////////////////////////////////////// // Transient/Immutable transient private ObjectProperty<State> stateProperty; transient private ObjectProperty<DisputeState> disputeStateProperty; transient private ObjectProperty<TradePeriodState> tradePeriodStateProperty; // Trades are saved in the TradeList @Nullable transient private Storage<? extends TradableList> storage; transient protected TradeProtocol tradeProtocol; transient private Date maxTradePeriodDate, halfTradePeriodDate; // Immutable private final Offer offer; private final ProcessModel processModel; // Mutable private DecryptedMsgWithPubKey decryptedMsgWithPubKey; private Date takeOfferDate; private Coin tradeAmount; private long tradePrice; private NodeAddress tradingPeerNodeAddress; @Nullable private String takeOfferFeeTxId; protected State state; private DisputeState disputeState = DisputeState.NONE; private TradePeriodState tradePeriodState = TradePeriodState.NORMAL; private Transaction depositTx; private Contract contract; private String contractAsJson; private byte[] contractHash; private String takerContractSignature; private String offererContractSignature; private Transaction payoutTx; private long lockTimeAsBlockHeight; private NodeAddress arbitratorNodeAddress; private byte[] arbitratorBtcPubKey; private String takerPaymentAccountId; private String errorMessage; transient private StringProperty errorMessageProperty; transient private ObjectProperty<Coin> tradeAmountProperty; transient private ObjectProperty<Fiat> tradeVolumeProperty; transient private Set<DecryptedMsgWithPubKey> mailboxMessageSet = new HashSet<>(); /////////////////////////////////////////////////////////////////////////////////////////// // Constructor, initialization /////////////////////////////////////////////////////////////////////////////////////////// // offerer protected Trade(Offer offer, Storage<? extends TradableList> storage) { this.offer = offer; this.storage = storage; this.takeOfferDate = new Date(); processModel = new ProcessModel(); tradeVolumeProperty = new SimpleObjectProperty<>(); tradeAmountProperty = new SimpleObjectProperty<>(); errorMessageProperty = new SimpleStringProperty(); initStates(); initStateProperties(); } // taker protected Trade(Offer offer, Coin tradeAmount, long tradePrice, NodeAddress tradingPeerNodeAddress, Storage<? extends TradableList> storage) { this(offer, storage); this.tradeAmount = tradeAmount; this.tradePrice = tradePrice; this.tradingPeerNodeAddress = tradingPeerNodeAddress; tradeAmountProperty.set(tradeAmount); tradeVolumeProperty.set(getTradeVolume()); this.takeOfferDate = new Date(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { try { in.defaultReadObject(); initStateProperties(); initAmountProperty(); errorMessageProperty = new SimpleStringProperty(errorMessage); mailboxMessageSet = new HashSet<>(); } catch (Throwable t) { log.warn("Cannot be deserialized." + t.getMessage()); } } public void init(P2PService p2PService, WalletService walletService, TradeWalletService tradeWalletService, ArbitratorManager arbitratorManager, TradeManager tradeManager, OpenOfferManager openOfferManager, User user, FilterManager filterManager, KeyRing keyRing, boolean useSavingsWallet, Coin fundsNeededForTrade) { Log.traceCall(); processModel.onAllServicesInitialized(offer, tradeManager, openOfferManager, p2PService, walletService, tradeWalletService, arbitratorManager, user, filterManager, keyRing, useSavingsWallet, fundsNeededForTrade); createProtocol(); log.trace("init: decryptedMsgWithPubKey = " + decryptedMsgWithPubKey); if (decryptedMsgWithPubKey != null && !mailboxMessageSet.contains(decryptedMsgWithPubKey)) { mailboxMessageSet.add(decryptedMsgWithPubKey); tradeProtocol.applyMailboxMessage(decryptedMsgWithPubKey, this); } } protected void initStateProperties() { stateProperty = new SimpleObjectProperty<>(state); disputeStateProperty = new SimpleObjectProperty<>(disputeState); tradePeriodStateProperty = new SimpleObjectProperty<>(tradePeriodState); } protected void initAmountProperty() { tradeAmountProperty = new SimpleObjectProperty<>(); tradeVolumeProperty = new SimpleObjectProperty<>(); if (tradeAmount != null) { tradeAmountProperty.set(tradeAmount); tradeVolumeProperty.set(getTradeVolume()); } } /////////////////////////////////////////////////////////////////////////////////////////// // API /////////////////////////////////////////////////////////////////////////////////////////// // The deserialized tx has not actual confidence data, so we need to get the fresh one from the wallet. public void updateDepositTxFromWallet() { if (depositTx != null) setDepositTx(processModel.getTradeWalletService().getWalletTx(depositTx.getHash())); } public void setDepositTx(Transaction tx) { log.debug("setDepositTx " + tx); this.depositTx = tx; setupConfidenceListener(); persist(); } @Nullable public Transaction getDepositTx() { return depositTx; } public void setMailboxMessage(DecryptedMsgWithPubKey decryptedMsgWithPubKey) { log.trace("setMailboxMessage decryptedMsgWithPubKey=" + decryptedMsgWithPubKey); this.decryptedMsgWithPubKey = decryptedMsgWithPubKey; if (tradeProtocol != null && decryptedMsgWithPubKey != null && !mailboxMessageSet.contains(decryptedMsgWithPubKey)) { mailboxMessageSet.add(decryptedMsgWithPubKey); tradeProtocol.applyMailboxMessage(decryptedMsgWithPubKey, this); } } public DecryptedMsgWithPubKey getMailboxMessage() { return decryptedMsgWithPubKey; } public void setStorage(Storage<? extends TradableList> storage) { this.storage = storage; } /////////////////////////////////////////////////////////////////////////////////////////// // States /////////////////////////////////////////////////////////////////////////////////////////// public void setState(State state) { log.info("Trade.setState: " + state); boolean changed = this.state != state; this.state = state; stateProperty.set(state); if (changed) persist(); } public void setDisputeState(DisputeState disputeState) { Log.traceCall("disputeState=" + disputeState + "\n\ttrade=" + this); boolean changed = this.disputeState != disputeState; this.disputeState = disputeState; disputeStateProperty.set(disputeState); if (changed) persist(); } public DisputeState getDisputeState() { return disputeState; } public void setTradePeriodState(TradePeriodState tradePeriodState) { boolean changed = this.tradePeriodState != tradePeriodState; this.tradePeriodState = tradePeriodState; tradePeriodStateProperty.set(tradePeriodState); if (changed) persist(); } public TradePeriodState getTradePeriodState() { return tradePeriodState; } public boolean isTakerFeePaid() { return state.getPhase() != null && state.getPhase().ordinal() >= Phase.TAKER_FEE_PAID.ordinal(); } public boolean isDepositPaid() { return state.getPhase() != null && state.getPhase().ordinal() >= Phase.DEPOSIT_PAID.ordinal(); } public State getState() { return state; } /////////////////////////////////////////////////////////////////////////////////////////// // Model implementation /////////////////////////////////////////////////////////////////////////////////////////// // Get called from taskRunner after each completed task @Override public void persist() { if (storage != null) storage.queueUpForSave(); } @Override public void onComplete() { persist(); } /////////////////////////////////////////////////////////////////////////////////////////// // Getter only /////////////////////////////////////////////////////////////////////////////////////////// public String getId() { return offer.getId(); } public String getShortId() { return offer.getShortId(); } public Offer getOffer() { return offer; } abstract public Coin getPayoutAmount(); public ProcessModel getProcessModel() { return processModel; } @Nullable public Fiat getTradeVolume() { if (tradeAmount != null && getTradePrice() != null) return new ExchangeRate(getTradePrice()).coinToFiat(tradeAmount); else return null; } @Nullable public Date getMaxTradePeriodDate() { if (maxTradePeriodDate == null && takeOfferDate != null) maxTradePeriodDate = new Date(takeOfferDate.getTime() + getOffer().getPaymentMethod().getMaxTradePeriod()); return maxTradePeriodDate; } @Nullable public Date getHalfTradePeriodDate() {
[ " if (halfTradePeriodDate == null && takeOfferDate != null)" ]
1,060
lcc
java
null
23da8d9de20f882d02d5c855b1322a6bc6b13eebcf69be20
/* ------------------------------------------------------------------------ * Tab.cs * Symbol table management of Coco/R * by H.Moessenboeck, Univ. of Linz * ------------------------------------------------------------------------*/ using System; using System.IO; using System.Collections; namespace at.jku.ssw.Coco { public class Position { // position of source code stretch (e.g. semantic action, resolver expressions) public int beg; // start relative to the beginning of the file public int len; // length of stretch public int col; // column number of start position public Position(int beg, int len, int col) { this.beg = beg; this.len = len; this.col = col; } } //--------------------------------------------------------------------- // Symbols //--------------------------------------------------------------------- public class Symbol : IComparable { public static ArrayList terminals = new ArrayList(); public static ArrayList pragmas = new ArrayList(); public static ArrayList nonterminals = new ArrayList(); public static Hashtable tokenNames = null; /* AW 2003-03-25 */ public const int classToken = 0; // token kinds public const int litToken = 1; public const int classLitToken = 2; public int n; // symbol number public int typ; // t, nt, pr, unknown, rslv /* ML 29_11_2002 slv added */ /* AW slv --> rslv */ public string name; // symbol name public Node graph; // nt: to first node of syntax graph public int tokenKind; // t: token kind (literal, class, ...) public bool deletable; // nt: true if nonterminal is deletable public bool firstReady; // nt: true if terminal start symbols have already been computed public BitArray first; // nt: terminal start symbols public BitArray follow; // nt: terminal followers public BitArray nts; // nt: nonterminals whose followers have to be added to this sym public int line; // source text line number of item in this node public Position attrPos; // nt: position of attributes in source text (or null) public Position semPos; // pr: pos of semantic action in source text (or null) // nt: pos of local declarations in source text (or null) public override string ToString() { return String.Format("[Symbol:Name={0}, n={1}]", name, n); } public Symbol(int typ, string name, int line) { if (name.Length == 2 && name[0] == '"') { Parser.SemErr("empty token not allowed"); name = "???"; } if (name.IndexOf(' ') >= 0) Parser.SemErr("tokens must not contain blanks"); this.typ = typ; this.name = name; this.line = line; switch (typ) { case Node.t: n = terminals.Count; terminals.Add(this); break; case Node.pr: pragmas.Add(this); break; case Node.nt: n = nonterminals.Count; nonterminals.Add(this); break; } } public static Symbol Find(string name) { foreach (Symbol s in terminals) if (s.name == name) return s; foreach (Symbol s in nonterminals) if (s.name == name) return s; return null; } public int CompareTo(object x) { return name.CompareTo(((Symbol)x).name); } } //--------------------------------------------------------------------- // Syntax graph (class Node, class Graph) //--------------------------------------------------------------------- public class Node { public static ArrayList nodes = new ArrayList(); public static string[] nTyp = {" ", "t ", "pr ", "nt ", "clas", "chr ", "wt ", "any ", "eps ", /* AW 03-01-14 nTyp[0]: " " --> " " */ "sync", "sem ", "alt ", "iter", "opt ", "rslv"}; // constants for node kinds public const int t = 1; // terminal symbol public const int pr = 2; // pragma public const int nt = 3; // nonterminal symbol public const int clas = 4; // character class public const int chr = 5; // character public const int wt = 6; // weak terminal symbol public const int any = 7; // public const int eps = 8; // empty public const int sync = 9; // synchronization symbol public const int sem = 10; // semantic action: (. .) public const int alt = 11; // alternative: | public const int iter = 12; // iteration: { } public const int opt = 13; // option: [ ] public const int rslv = 14; // resolver expr /* ML */ /* AW 03-01-13 renamed slv --> rslv */ public const int normalTrans = 0; // transition codes public const int contextTrans = 1; public int n; // node number public int typ; // t, nt, wt, chr, clas, any, eps, sem, sync, alt, iter, opt, rslv public Node next; // to successor node public Node down; // alt: to next alternative public Node sub; // alt, iter, opt: to first node of substructure public bool up; // true: "next" leads to successor in enclosing structure public Symbol sym; // nt, t, wt: symbol represented by this node public int val; // chr: ordinal character value // clas: index of character class public int code; // chr, clas: transition code public BitArray set; // any, sync: the set represented by this node public Position pos; // nt, t, wt: pos of actual attributes // sem: pos of semantic action in source text public int line; // source text line number of item in this node public State state; // DFA state corresponding to this node // (only used in DFA.ConvertToStates) public Node(int typ, Symbol sym, int line) { this.typ = typ; this.sym = sym; this.line = line; n = nodes.Count; nodes.Add(this); } public Node(int typ, Node sub): this(typ, null, 0) { this.sub = sub; } public Node(int typ, int val, int line): this(typ, null, line) { this.val = val; } public static bool DelGraph(Node p) { return p == null || DelNode(p) && DelGraph(p.next); } public static bool DelAlt(Node p) { return p == null || DelNode(p) && (p.up || DelAlt(p.next)); } public static bool DelNode(Node p) { if (p.typ == nt) return p.sym.deletable; else if (p.typ == alt) return DelAlt(p.sub) || p.down != null && DelAlt(p.down); else return p.typ == eps || p.typ == iter || p.typ == opt || p.typ == sem || p.typ == sync; } //----------------- for printing ---------------------- static int Ptr(Node p, bool up) { if (p == null) return 0; else if (up) return -p.n; else return p.n; } static string Pos(Position pos) { if (pos == null) return " "; else return String.Format("{0,5}", pos.beg); } public static string Name(string name) { return (name + " ").Substring(0, 12); /* isn't this better (less string allocations, easier to understand): * * return (name.Length > 12) ? name.Substring(0,12) : name; */ } public static void PrintNodes() { Trace.WriteLine("Graph nodes:"); Trace.WriteLine("----------------------------------------------------"); Trace.WriteLine(" n type name next down sub pos line"); Trace.WriteLine(" val code"); Trace.WriteLine("----------------------------------------------------"); foreach (Node p in nodes) { Trace.Write("{0,4} {1} ", p.n, nTyp[p.typ]); if (p.sym != null) Trace.Write("{0,12} ", Name(p.sym.name)); else if (p.typ == Node.clas) { CharClass c = (CharClass)CharClass.classes[p.val]; Trace.Write("{0,12} ", Name(c.name)); } else Trace.Write(" "); Trace.Write("{0,5} ", Ptr(p.next, p.up)); switch (p.typ) { case t: case nt: case wt: Trace.Write(" {0,5}", Pos(p.pos)); break; case chr: Trace.Write("{0,5} {1,5} ", p.val, p.code); break; case clas: Trace.Write(" {0,5} ", p.code); break; case alt: case iter: case opt: Trace.Write("{0,5} {1,5} ", Ptr(p.down, false), Ptr(p.sub, false)); break; case sem: Trace.Write(" {0,5}", Pos(p.pos)); break; case eps: case any: case sync: Trace.Write(" "); break; } Trace.WriteLine("{0,5}", p.line); } Trace.WriteLine(); } } public class Graph { static Node dummyNode = new Node(Node.eps, null, 0); public Node l; // left end of graph = head public Node r; // right end of graph = list of nodes to be linked to successor graph public Graph() { l = null; r = null; } public Graph(Node left, Node right) { l = left; r = right; } public Graph(Node p) { l = p; r = p; } public static void MakeFirstAlt(Graph g) { g.l = new Node(Node.alt, g.l); g.l.line = g.l.sub.line; /* AW 2002-03-07 make line available for error handling */ g.l.next = g.r; g.r = g.l; } public static void MakeAlternative(Graph g1, Graph g2) { g2.l = new Node(Node.alt, g2.l); g2.l.line = g2.l.sub.line; Node p = g1.l; while (p.down != null) p = p.down; p.down = g2.l; p = g1.r; while (p.next != null) p = p.next; p.next = g2.r; } public static void MakeSequence(Graph g1, Graph g2) { Node p = g1.r.next; g1.r.next = g2.l; // link head node while (p != null) { // link substructure Node q = p.next; p.next = g2.l; p.up = true; p = q; } g1.r = g2.r; } public static void MakeIteration(Graph g) { g.l = new Node(Node.iter, g.l); Node p = g.r; g.r = g.l; while (p != null) { Node q = p.next; p.next = g.l; p.up = true; p = q; } } public static void MakeOption(Graph g) { g.l = new Node(Node.opt, g.l); g.l.next = g.r; g.r = g.l; } public static void Finish(Graph g) { Node p = g.r; while (p != null) { Node q = p.next; p.next = null; p = q; } } public static void SetContextTrans(Node p) { // set transition code in the graph rooted at p DFA.hasCtxMoves = true; while (p != null) { if (p.typ == Node.chr || p.typ == Node.clas) { p.code = Node.contextTrans; } else if (p.typ == Node.opt || p.typ == Node.iter) { SetContextTrans(p.sub); } else if (p.typ == Node.alt) { SetContextTrans(p.sub); SetContextTrans(p.down); } if (p.up) break; p = p.next; } } public static void DeleteNodes() { Node.nodes = new ArrayList(); dummyNode = new Node(Node.eps, null, 0); } public static Graph StrToGraph(string str) { string s = DFA.Unescape(str.Substring(1, str.Length-2)); if (s.IndexOf('\0') >= 0) Parser.SemErr("\\0 not allowed here. Used as eof character"); if (s.Length == 0) Parser.SemErr("empty token not allowed"); Graph g = new Graph(); g.r = dummyNode; for (int i = 0; i < s.Length; i++) { Node p = new Node(Node.chr, (int)s[i], 0); g.r.next = p; g.r = p; } g.l = dummyNode.next; dummyNode.next = null; return g; } } //---------------------------------------------------------------- // Bit sets //---------------------------------------------------------------- public class Sets { public static int First(BitArray s) { int max = s.Count; for (int i=0; i<max; i++) if (s[i]) return i; return -1; } public static int Elements(BitArray s) { int max = s.Count; int n = 0; for (int i=0; i<max; i++) if (s[i]) n++; return n; } public static bool Equals(BitArray a, BitArray b) { int max = a.Count; for (int i=0; i<max; i++) if (a[i] != b[i]) return false; return true; } public static bool Includes(BitArray a, BitArray b) { // a > b ? int max = a.Count; for (int i=0; i<max; i++) if (b[i] && ! a[i]) return false; return true; } public static bool Intersect(BitArray a, BitArray b) { // a * b != {} int max = a.Count; for (int i=0; i<max; i++) if (a[i] && b[i]) return true; return false; } public static void Subtract(BitArray a, BitArray b) { // a = a - b BitArray c = (BitArray) b.Clone(); a.And(c.Not()); } public static void PrintSet(BitArray s, int indent) { int col, len; col = indent; foreach (Symbol sym in Symbol.terminals) { if (s[sym.n]) { len = sym.name.Length; if (col + len >= 80) { Trace.WriteLine(); for (col = 1; col < indent; col++) Trace.Write(" "); } Trace.Write("{0} ", sym.name); col += len + 1; } } if (col == indent) Trace.Write("-- empty set --"); Trace.WriteLine(); } } //--------------------------------------------------------------------- // Character class management //--------------------------------------------------------------------- public class CharClass { public static ArrayList classes = new ArrayList(); public static int dummyName = 'A'; public const int charSetSize = 256; // must be a multiple of 16 public int n; // class number public string name; // class name public BitArray set; // set representing the class public CharClass(string name, BitArray s) { if (name == "#") name = "#" + (char)dummyName++; this.n = classes.Count; this.name = name; this.set = s; classes.Add(this); } public static CharClass Find(string name) { foreach (CharClass c in classes) if (c.name == name) return c; return null; } public static CharClass Find(BitArray s) { foreach (CharClass c in classes) if (Sets.Equals(s, c.set)) return c; return null; } public static BitArray Set(int i) { return ((CharClass)classes[i]).set; } static string Ch(int ch) { if (ch < ' ' || ch >= 127 || ch == '\'' || ch == '\\') return ch.ToString(); else return String.Format("'{0}'", (char)ch); } static void WriteCharSet(BitArray s) { int i = 0, len = s.Count; while (i < len) { while (i < len && !s[i]) i++; if (i == len) break; int j = i; while (i < len && s[i]) i++; if (j < i-1) Trace.Write("{0}..{1} ", Ch(j), Ch(i-1)); else Trace.Write("{0} ", Ch(j)); } } public static void WriteClasses () { foreach (CharClass c in classes) { Trace.Write("{0,-10}: ", c.name); WriteCharSet(c.set); Trace.WriteLine(); } Trace.WriteLine(); } } //----------------------------------------------------------- // Symbol table management routines //----------------------------------------------------------- public class Tab { public static Position semDeclPos; // position of global semantic declarations public static BitArray ignored; // characters ignored by the scanner public static bool[] ddt = new bool[10]; // debug and test switches public static Symbol gramSy; // root nonterminal; filled by ATG public static Symbol eofSy; // end of file symbol public static Symbol noSym; // used in case of an error public static BitArray allSyncSets; // union of all synchronisation sets public static string nsName; // namespace for generated files static BitArray visited; // mark list for graph traversals static Symbol curSy; // current symbol in computation of sets //--------------------------------------------------------------------- // Symbol set computations //--------------------------------------------------------------------- /* Computes the first set for the given Node. */ static BitArray First0(Node p, BitArray mark) { BitArray fs = new BitArray(Symbol.terminals.Count); while (p != null && !mark[p.n]) { mark[p.n] = true; switch (p.typ) { case Node.nt: { if (p.sym.firstReady) fs.Or(p.sym.first); else fs.Or(First0(p.sym.graph, mark)); break; } case Node.t: case Node.wt: { fs[p.sym.n] = true; break; } case Node.any: { fs.Or(p.set); break; } case Node.alt: { fs.Or(First0(p.sub, mark)); fs.Or(First0(p.down, mark)); break; } case Node.iter: case Node.opt: { fs.Or(First0(p.sub, mark)); break; } } if (!Node.DelNode(p)) break; p = p.next; } return fs; } /// <returns> /// BitArray which contains the first tokens. /// </returns> public static BitArray First(Node p) { BitArray fs = First0(p, new BitArray(Node.nodes.Count)); if (ddt[3]) { Trace.WriteLine(); if (p != null) Trace.WriteLine("First: node = {0}", p.n); else Trace.WriteLine("First: node = null"); Sets.PrintSet(fs, 0); } return fs; } static void CompFirstSets() { foreach (Symbol sym in Symbol.nonterminals) { sym.first = new BitArray(Symbol.terminals.Count); sym.firstReady = false; } foreach (Symbol sym in Symbol.nonterminals) { sym.first = First(sym.graph); sym.firstReady = true; } } static void CompFollow(Node p) { while (p != null && !visited[p.n]) { visited[p.n] = true; if (p.typ == Node.nt) { BitArray s = First(p.next); p.sym.follow.Or(s); if (Node.DelGraph(p.next)) p.sym.nts[curSy.n] = true; } else if (p.typ == Node.opt || p.typ == Node.iter) { CompFollow(p.sub); } else if (p.typ == Node.alt) { CompFollow(p.sub); CompFollow(p.down); } p = p.next; } } static void Complete(Symbol sym) { if (!visited[sym.n]) { visited[sym.n] = true; foreach (Symbol s in Symbol.nonterminals) { if (sym.nts[s.n]) { Complete(s); sym.follow.Or(s.follow); if (sym == curSy) sym.nts[s.n] = false; } } } } static void CompFollowSets() { foreach (Symbol sym in Symbol.nonterminals) { sym.follow = new BitArray(Symbol.terminals.Count); sym.nts = new BitArray(Symbol.nonterminals.Count); } visited = new BitArray(Node.nodes.Count); foreach (Symbol sym in Symbol.nonterminals) { // get direct successors of nonterminals curSy = sym; CompFollow(sym.graph); } foreach (Symbol sym in Symbol.nonterminals) { // add indirect successors to followers visited = new BitArray(Symbol.nonterminals.Count); curSy = sym; Complete(sym); } } static Node LeadingAny(Node p) { if (p == null) return null; Node a = null; if (p.typ == Node.any) a = p; else if (p.typ == Node.alt) { a = LeadingAny(p.sub);
[ "\t\t\tif (a == null) a = LeadingAny(p.down);" ]
2,508
lcc
csharp
null
bca3c4560f23f25e2f915056e3c74f7832b570be4c2e30fb
////////////////////////////////////////////////////////////////////////////////// // Wiimote.cs // Managed Wiimote Library // Written by Brian Peek (http://www.brianpeek.com/) // for MSDN's Coding4Fun (http://msdn.microsoft.com/coding4fun/) // Visit http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx // and http://www.codeplex.com/WiimoteLib // for more information ////////////////////////////////////////////////////////////////////////////////// using System; using System.Runtime.InteropServices; using System.Diagnostics; using System.IO; using System.Runtime.Serialization; using Microsoft.Win32.SafeHandles; using System.Threading; namespace WiimoteLib { /// <summary> /// Implementation of Wiimote /// </summary> public class Wiimote : IDisposable { /// <summary> /// Event raised when Wiimote state is changed /// </summary> public event EventHandler<WiimoteChangedEventArgs> WiimoteChanged; /// <summary> /// Event raised when an extension is inserted or removed /// </summary> public event EventHandler<WiimoteExtensionChangedEventArgs> WiimoteExtensionChanged; // VID = Nintendo, PID = Wiimote private const int VID = 0x057e; private const int PID = 0x0306; // sure, we could find this out the hard way using HID, but trust me, it's 22 private const int REPORT_LENGTH = 22; // Wiimote output commands private enum OutputReport : byte { LEDs = 0x11, DataReportType = 0x12, IR = 0x13, SpeakerOnOff = 0x14, Status = 0x15, WriteMemory = 0x16, ReadMemory = 0x17, IR2 = 0x1a, SpeakerDataOut = 0x18, SpeakerMute = 0x19, }; // Wiimote registers private const int REGISTER_IR = 0x04b00030; private const int REGISTER_IR_SENSITIVITY_1 = 0x04b00000; private const int REGISTER_IR_SENSITIVITY_2 = 0x04b0001a; private const int REGISTER_IR_MODE = 0x04b00033; private const int REGISTER_EXTENSION_INIT_1 = 0x04a400f0; private const int REGISTER_EXTENSION_INIT_2 = 0x04a400fb; private const int REGISTER_EXTENSION_TYPE = 0x04a400fa; private const int REGISTER_EXTENSION_TYPE_2 = 0x04a400fe; private const int REGISTER_EXTENSION_CALIBRATION = 0x04a40020; private const int REGISTER_MOTIONPLUS_INIT = 0x04a600fe; // length between board sensors private const int BSL = 43; // width between board sensors private const int BSW = 24; // read/write handle to the device private SafeFileHandle mHandle; // a pretty .NET stream to read/write from/to private FileStream mStream; // read data buffer private byte[] mReadBuff; // address to read from private int mAddress; // size of requested read private short mSize; // current state of controller private readonly WiimoteState mWiimoteState = new WiimoteState(); // event for read data processing private readonly AutoResetEvent mReadDone = new AutoResetEvent(false); private readonly AutoResetEvent mWriteDone = new AutoResetEvent(false); // event for status report private readonly AutoResetEvent mStatusDone = new AutoResetEvent(false); // use a different method to write reports private bool mAltWriteMethod; // HID device path of this Wiimote private string mDevicePath = string.Empty; // unique ID private readonly Guid mID = Guid.NewGuid(); // delegate used for enumerating found Wiimotes internal delegate bool WiimoteFoundDelegate(string devicePath); // kilograms to pounds private const float KG2LB = 2.20462262f; // volume for playing tones private byte volume = 0x20; // frequency for playing tones private byte frequency = 15; // amplitude for playing tones private byte amplitude = 0xC3; // sound is playing or not private bool SoundPlaying = false; // thread to stream audio tone private Thread StreamMusicThread; /// <summary> /// Default constructor /// </summary> public Wiimote() { } internal Wiimote(string devicePath) { mDevicePath = devicePath; } /// <summary> /// Connect to the first-found Wiimote /// </summary> /// <exception cref="WiimoteNotFoundException">Wiimote not found in HID device list</exception> public void Connect() { if(string.IsNullOrEmpty(mDevicePath)) FindWiimote(WiimoteFound); else OpenWiimoteDeviceHandle(mDevicePath); } internal static void FindWiimote(WiimoteFoundDelegate wiimoteFound) { int index = 0; Guid guid; SafeFileHandle mHandle; // get the GUID of the HID class HIDImports.HidD_GetHidGuid(out guid); // get a handle to all devices that are part of the HID class // Fun fact: DIGCF_PRESENT worked on my machine just fine. I reinstalled Vista, and now it no longer finds the Wiimote with that parameter enabled... IntPtr hDevInfo = HIDImports.SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, HIDImports.DIGCF_DEVICEINTERFACE);// | HIDImports.DIGCF_PRESENT); // create a new interface data struct and initialize its size HIDImports.SP_DEVICE_INTERFACE_DATA diData = new HIDImports.SP_DEVICE_INTERFACE_DATA(); diData.cbSize = Marshal.SizeOf(diData); // get a device interface to a single device (enumerate all devices) while(HIDImports.SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guid, index, ref diData)) { UInt32 size; // get the buffer size for this device detail instance (returned in the size parameter) HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero); // create a detail struct and set its size HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA diDetail = new HIDImports.SP_DEVICE_INTERFACE_DETAIL_DATA(); // yeah, yeah...well, see, on Win x86, cbSize must be 5 for some reason. On x64, apparently 8 is what it wants. // someday I should figure this out. Thanks to Paul Miller on this... diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5); // actually get the detail struct if(HIDImports.SetupDiGetDeviceInterfaceDetail(hDevInfo, ref diData, ref diDetail, size, out size, IntPtr.Zero)) { Debug.WriteLine(string.Format("{0}: {1} - {2}", index, diDetail.DevicePath, Marshal.GetLastWin32Error())); // open a read/write handle to our device using the DevicePath returned mHandle = HIDImports.CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero); // create an attributes struct and initialize the size HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES(); attrib.Size = Marshal.SizeOf(attrib); // get the attributes of the current device if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib)) { // if the vendor and product IDs match up if(attrib.VendorID == VID && attrib.ProductID == PID) { // it's a Wiimote Debug.WriteLine("Found one!"); // fire the callback function...if the callee doesn't care about more Wiimotes, break out if(!wiimoteFound(diDetail.DevicePath)) break; } } mHandle.Close(); } else { // failed to get the detail struct throw new WiimoteException("SetupDiGetDeviceInterfaceDetail failed on index " + index); } // move to the next device index++; } // clean up our list HIDImports.SetupDiDestroyDeviceInfoList(hDevInfo); // if we didn't find a Wiimote, throw an exception /*if(!found) throw new WiimoteNotFoundException("No Wiimotes found in HID device list.");*/ } private bool WiimoteFound(string devicePath) { mDevicePath = devicePath; // if we didn't find a Wiimote, throw an exception OpenWiimoteDeviceHandle(mDevicePath); return false; } private void OpenWiimoteDeviceHandle(string devicePath) { // open a read/write handle to our device using the DevicePath returned mHandle = HIDImports.CreateFile(devicePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, HIDImports.EFileAttributes.Overlapped, IntPtr.Zero); // create an attributes struct and initialize the size HIDImports.HIDD_ATTRIBUTES attrib = new HIDImports.HIDD_ATTRIBUTES(); attrib.Size = Marshal.SizeOf(attrib); // get the attributes of the current device if(HIDImports.HidD_GetAttributes(mHandle.DangerousGetHandle(), ref attrib)) { // if the vendor and product IDs match up if(attrib.VendorID == VID && attrib.ProductID == PID) { // create a nice .NET FileStream wrapping the handle above mStream = new FileStream(mHandle, FileAccess.ReadWrite, REPORT_LENGTH, true); // start an async read operation on it BeginAsyncRead(); // read the calibration info from the controller try { ReadWiimoteCalibration(); } catch { // if we fail above, try the alternate HID writes mAltWriteMethod = true; ReadWiimoteCalibration(); } // force a status check to get the state of any extensions plugged in at startup GetStatus(); } else { // otherwise this isn't the controller, so close up the file handle mHandle.Close(); throw new WiimoteException("Attempted to open a non-Wiimote device."); } } } /// <summary> /// Initialize the MotionPlus extension /// </summary> public void InitializeMotionPlus() { Debug.WriteLine("InitializeMotionPlus"); WriteData(REGISTER_MOTIONPLUS_INIT, 0x04); } /// <summary> /// Disconnect from the controller and stop reading data from it /// </summary> public void Disconnect() { // close up the stream and handle if(mStream != null) mStream.Close(); if(mHandle != null) mHandle.Close(); } /// <summary> /// Start reading asynchronously from the controller /// </summary> private void BeginAsyncRead() { // if the stream is valid and ready if(mStream != null && mStream.CanRead) { // setup the read and the callback byte[] buff = new byte[REPORT_LENGTH]; mStream.BeginRead(buff, 0, REPORT_LENGTH, new AsyncCallback(OnReadData), buff); } } /// <summary> /// Callback when data is ready to be processed /// </summary> /// <param name="ar">State information for the callback</param> private void OnReadData(IAsyncResult ar) { // grab the byte buffer byte[] buff = (byte[])ar.AsyncState; try { // end the current read mStream.EndRead(ar); // parse it if(ParseInputReport(buff)) { // post an event if(WiimoteChanged != null) WiimoteChanged(this, new WiimoteChangedEventArgs(mWiimoteState)); } // start reading again BeginAsyncRead(); } catch(OperationCanceledException) { Debug.WriteLine("OperationCanceledException"); } } /// <summary> /// Parse a report sent by the Wiimote /// </summary> /// <param name="buff">Data buffer to parse</param> /// <returns>Returns a boolean noting whether an event needs to be posted</returns> private bool ParseInputReport(byte[] buff) { InputReport type = (InputReport)buff[0]; switch(type) { case InputReport.Buttons: ParseButtons(buff); break; case InputReport.ButtonsAccel: ParseButtons(buff); ParseAccel(buff); break; case InputReport.IRAccel: ParseButtons(buff); ParseAccel(buff); ParseIR(buff); break; case InputReport.ButtonsExtension: ParseButtons(buff); ParseExtension(buff, 3); break; case InputReport.ExtensionAccel: ParseButtons(buff); ParseAccel(buff); ParseExtension(buff, 6); break; case InputReport.IRExtensionAccel: ParseButtons(buff); ParseAccel(buff); ParseIR(buff); ParseExtension(buff, 16); break; case InputReport.Status: Debug.WriteLine("******** STATUS ********"); ParseButtons(buff); mWiimoteState.BatteryRaw = buff[6]; mWiimoteState.Battery = (((100.0f * 48.0f * (float)((int)buff[6] / 48.0f))) / 192.0f); // get the real LED values in case the values from SetLEDs() somehow becomes out of sync, which really shouldn't be possible mWiimoteState.LEDState.LED1 = (buff[3] & 0x10) != 0; mWiimoteState.LEDState.LED2 = (buff[3] & 0x20) != 0; mWiimoteState.LEDState.LED3 = (buff[3] & 0x40) != 0; mWiimoteState.LEDState.LED4 = (buff[3] & 0x80) != 0; BeginAsyncRead(); byte[] extensionType = ReadData(REGISTER_EXTENSION_TYPE_2, 1); Debug.WriteLine("Extension byte=" + extensionType[0].ToString("x2")); // extension connected? bool extension = (buff[3] & 0x02) != 0; Debug.WriteLine("Extension, Old: " + mWiimoteState.Extension + ", New: " + extension); if(mWiimoteState.Extension != extension || extensionType[0] == 0x04) { mWiimoteState.Extension = extension; if(extension) { BeginAsyncRead(); InitializeExtension(extensionType[0]); } else mWiimoteState.ExtensionType = ExtensionType.None; // only fire the extension changed event if we have a real extension (i.e. not a balance board) if(WiimoteExtensionChanged != null && mWiimoteState.ExtensionType != ExtensionType.BalanceBoard) WiimoteExtensionChanged(this, new WiimoteExtensionChangedEventArgs(mWiimoteState.ExtensionType, mWiimoteState.Extension)); } mStatusDone.Set(); break; case InputReport.ReadData: ParseButtons(buff); ParseReadData(buff); break; case InputReport.OutputReportAck: // Debug.WriteLine("ack: " + buff[0] + " " + buff[1] + " " +buff[2] + " " +buff[3] + " " +buff[4]); mWriteDone.Set(); break; default: Debug.WriteLine("Unknown report type: " + type.ToString("x")); return false; } return true; } /// <summary> /// Handles setting up an extension when plugged in /// </summary> private void InitializeExtension(byte extensionType) { Debug.WriteLine("InitExtension"); // only initialize if it's not a MotionPlus if(extensionType != 0x04) { WriteData(REGISTER_EXTENSION_INIT_1, 0x55); WriteData(REGISTER_EXTENSION_INIT_2, 0x00); } // start reading again BeginAsyncRead(); byte[] buff = ReadData(REGISTER_EXTENSION_TYPE, 6); long type = ((long)buff[0] << 40) | ((long)buff[1] << 32) | ((long)buff[2]) << 24 | ((long)buff[3]) << 16 | ((long)buff[4]) << 8 | buff[5]; switch((ExtensionType)type) { case ExtensionType.None: case ExtensionType.ParitallyInserted: mWiimoteState.Extension = false; mWiimoteState.ExtensionType = ExtensionType.None; return; case ExtensionType.Nunchuk: case ExtensionType.Nunchuk2: case ExtensionType.Nunchuk3: case ExtensionType.ClassicController: case ExtensionType.Guitar: case ExtensionType.BalanceBoard: case ExtensionType.Drums: case ExtensionType.TaikoDrum: case ExtensionType.MotionPlus: mWiimoteState.ExtensionType = (ExtensionType)type; this.SetReportType(InputReport.ButtonsExtension, true); break; default: throw new WiimoteException("Unknown extension controller found: " + type.ToString("x")); } switch(mWiimoteState.ExtensionType) { case ExtensionType.Nunchuk: case ExtensionType.Nunchuk2: case ExtensionType.Nunchuk3: buff = ReadData(REGISTER_EXTENSION_CALIBRATION, 16); mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.X0 = buff[0]; mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.Y0 = buff[1]; mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.Z0 = buff[2]; mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.XG = buff[4]; mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.YG = buff[5]; mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.ZG = buff[6]; mWiimoteState.NunchukState.CalibrationInfo.MaxX = buff[8]; mWiimoteState.NunchukState.CalibrationInfo.MinX = buff[9]; mWiimoteState.NunchukState.CalibrationInfo.MidX = buff[10]; mWiimoteState.NunchukState.CalibrationInfo.MaxY = buff[11]; mWiimoteState.NunchukState.CalibrationInfo.MinY = buff[12]; mWiimoteState.NunchukState.CalibrationInfo.MidY = buff[13]; break; case ExtensionType.ClassicController: buff = ReadData(REGISTER_EXTENSION_CALIBRATION, 16); mWiimoteState.ClassicControllerState.CalibrationInfo.MaxXL = (byte)(buff[0] >> 2); mWiimoteState.ClassicControllerState.CalibrationInfo.MinXL = (byte)(buff[1] >> 2); mWiimoteState.ClassicControllerState.CalibrationInfo.MidXL = (byte)(buff[2] >> 2); mWiimoteState.ClassicControllerState.CalibrationInfo.MaxYL = (byte)(buff[3] >> 2); mWiimoteState.ClassicControllerState.CalibrationInfo.MinYL = (byte)(buff[4] >> 2); mWiimoteState.ClassicControllerState.CalibrationInfo.MidYL = (byte)(buff[5] >> 2); mWiimoteState.ClassicControllerState.CalibrationInfo.MaxXR = (byte)(buff[6] >> 3); mWiimoteState.ClassicControllerState.CalibrationInfo.MinXR = (byte)(buff[7] >> 3); mWiimoteState.ClassicControllerState.CalibrationInfo.MidXR = (byte)(buff[8] >> 3); mWiimoteState.ClassicControllerState.CalibrationInfo.MaxYR = (byte)(buff[9] >> 3); mWiimoteState.ClassicControllerState.CalibrationInfo.MinYR = (byte)(buff[10] >> 3); mWiimoteState.ClassicControllerState.CalibrationInfo.MidYR = (byte)(buff[11] >> 3); // this doesn't seem right... // mWiimoteState.ClassicControllerState.AccelCalibrationInfo.MinTriggerL = (byte)(buff[12] >> 3); // mWiimoteState.ClassicControllerState.AccelCalibrationInfo.MaxTriggerL = (byte)(buff[14] >> 3); // mWiimoteState.ClassicControllerState.AccelCalibrationInfo.MinTriggerR = (byte)(buff[13] >> 3); // mWiimoteState.ClassicControllerState.AccelCalibrationInfo.MaxTriggerR = (byte)(buff[15] >> 3); mWiimoteState.ClassicControllerState.CalibrationInfo.MinTriggerL = 0; mWiimoteState.ClassicControllerState.CalibrationInfo.MaxTriggerL = 31; mWiimoteState.ClassicControllerState.CalibrationInfo.MinTriggerR = 0; mWiimoteState.ClassicControllerState.CalibrationInfo.MaxTriggerR = 31; break; case ExtensionType.BalanceBoard: buff = ReadData(REGISTER_EXTENSION_CALIBRATION, 32); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.TopRight = (short)((short)buff[4] << 8 | buff[5]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.BottomRight = (short)((short)buff[6] << 8 | buff[7]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.TopLeft = (short)((short)buff[8] << 8 | buff[9]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.BottomLeft = (short)((short)buff[10] << 8 | buff[11]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.TopRight = (short)((short)buff[12] << 8 | buff[13]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.BottomRight = (short)((short)buff[14] << 8 | buff[15]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.TopLeft = (short)((short)buff[16] << 8 | buff[17]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.BottomLeft = (short)((short)buff[18] << 8 | buff[19]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.TopRight = (short)((short)buff[20] << 8 | buff[21]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.BottomRight = (short)((short)buff[22] << 8 | buff[23]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.TopLeft = (short)((short)buff[24] << 8 | buff[25]); mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.BottomLeft = (short)((short)buff[26] << 8 | buff[27]); break; case ExtensionType.MotionPlus: // someday... break; case ExtensionType.Guitar: case ExtensionType.Drums: case ExtensionType.TaikoDrum: // there appears to be no calibration for these controllers break; } } /// <summary> /// Decrypts data sent from the extension to the Wiimote /// </summary> /// <param name="buff">Data buffer</param> /// <returns>Byte array containing decoded data</returns> private byte[] DecryptBuffer(byte[] buff) { for(int i = 0; i < buff.Length; i++) buff[i] = (byte)(((buff[i] ^ 0x17) + 0x17) & 0xff); return buff; } /// <summary> /// Parses a standard button report into the ButtonState struct /// </summary> /// <param name="buff">Data buffer</param> private void ParseButtons(byte[] buff) { mWiimoteState.ButtonState.A = (buff[2] & 0x08) != 0; mWiimoteState.ButtonState.B = (buff[2] & 0x04) != 0; mWiimoteState.ButtonState.Minus = (buff[2] & 0x10) != 0; mWiimoteState.ButtonState.Home = (buff[2] & 0x80) != 0; mWiimoteState.ButtonState.Plus = (buff[1] & 0x10) != 0; mWiimoteState.ButtonState.One = (buff[2] & 0x02) != 0; mWiimoteState.ButtonState.Two = (buff[2] & 0x01) != 0; mWiimoteState.ButtonState.Up = (buff[1] & 0x08) != 0; mWiimoteState.ButtonState.Down = (buff[1] & 0x04) != 0; mWiimoteState.ButtonState.Left = (buff[1] & 0x01) != 0; mWiimoteState.ButtonState.Right = (buff[1] & 0x02) != 0; } /// <summary> /// Parse accelerometer data /// </summary> /// <param name="buff">Data buffer</param> private void ParseAccel(byte[] buff) { mWiimoteState.AccelState.RawValues.X = buff[3]; mWiimoteState.AccelState.RawValues.Y = buff[4]; mWiimoteState.AccelState.RawValues.Z = buff[5]; mWiimoteState.AccelState.Values.X = (float)((float)mWiimoteState.AccelState.RawValues.X - ((int)mWiimoteState.AccelCalibrationInfo.X0)) / ((float)mWiimoteState.AccelCalibrationInfo.XG - ((int)mWiimoteState.AccelCalibrationInfo.X0)); mWiimoteState.AccelState.Values.Y = (float)((float)mWiimoteState.AccelState.RawValues.Y - mWiimoteState.AccelCalibrationInfo.Y0) / ((float)mWiimoteState.AccelCalibrationInfo.YG - mWiimoteState.AccelCalibrationInfo.Y0); mWiimoteState.AccelState.Values.Z = (float)((float)mWiimoteState.AccelState.RawValues.Z - mWiimoteState.AccelCalibrationInfo.Z0) / ((float)mWiimoteState.AccelCalibrationInfo.ZG - mWiimoteState.AccelCalibrationInfo.Z0); } /// <summary> /// Parse IR data from report /// </summary> /// <param name="buff">Data buffer</param> private void ParseIR(byte[] buff) { mWiimoteState.IRState.IRSensors[0].RawPosition.X = buff[6] | ((buff[8] >> 4) & 0x03) << 8; mWiimoteState.IRState.IRSensors[0].RawPosition.Y = buff[7] | ((buff[8] >> 6) & 0x03) << 8; switch(mWiimoteState.IRState.Mode) { case IRMode.Basic: mWiimoteState.IRState.IRSensors[1].RawPosition.X = buff[9] | ((buff[8] >> 0) & 0x03) << 8; mWiimoteState.IRState.IRSensors[1].RawPosition.Y = buff[10] | ((buff[8] >> 2) & 0x03) << 8; mWiimoteState.IRState.IRSensors[2].RawPosition.X = buff[11] | ((buff[13] >> 4) & 0x03) << 8; mWiimoteState.IRState.IRSensors[2].RawPosition.Y = buff[12] | ((buff[13] >> 6) & 0x03) << 8; mWiimoteState.IRState.IRSensors[3].RawPosition.X = buff[14] | ((buff[13] >> 0) & 0x03) << 8; mWiimoteState.IRState.IRSensors[3].RawPosition.Y = buff[15] | ((buff[13] >> 2) & 0x03) << 8; mWiimoteState.IRState.IRSensors[0].Size = 0x00; mWiimoteState.IRState.IRSensors[1].Size = 0x00; mWiimoteState.IRState.IRSensors[2].Size = 0x00; mWiimoteState.IRState.IRSensors[3].Size = 0x00; mWiimoteState.IRState.IRSensors[0].Found = !(buff[6] == 0xff && buff[7] == 0xff); mWiimoteState.IRState.IRSensors[1].Found = !(buff[9] == 0xff && buff[10] == 0xff); mWiimoteState.IRState.IRSensors[2].Found = !(buff[11] == 0xff && buff[12] == 0xff); mWiimoteState.IRState.IRSensors[3].Found = !(buff[14] == 0xff && buff[15] == 0xff); break; case IRMode.Extended: mWiimoteState.IRState.IRSensors[1].RawPosition.X = buff[9] | ((buff[11] >> 4) & 0x03) << 8; mWiimoteState.IRState.IRSensors[1].RawPosition.Y = buff[10] | ((buff[11] >> 6) & 0x03) << 8; mWiimoteState.IRState.IRSensors[2].RawPosition.X = buff[12] | ((buff[14] >> 4) & 0x03) << 8; mWiimoteState.IRState.IRSensors[2].RawPosition.Y = buff[13] | ((buff[14] >> 6) & 0x03) << 8; mWiimoteState.IRState.IRSensors[3].RawPosition.X = buff[15] | ((buff[17] >> 4) & 0x03) << 8; mWiimoteState.IRState.IRSensors[3].RawPosition.Y = buff[16] | ((buff[17] >> 6) & 0x03) << 8; mWiimoteState.IRState.IRSensors[0].Size = buff[8] & 0x0f; mWiimoteState.IRState.IRSensors[1].Size = buff[11] & 0x0f; mWiimoteState.IRState.IRSensors[2].Size = buff[14] & 0x0f; mWiimoteState.IRState.IRSensors[3].Size = buff[17] & 0x0f; mWiimoteState.IRState.IRSensors[0].Found = !(buff[6] == 0xff && buff[7] == 0xff && buff[8] == 0xff); mWiimoteState.IRState.IRSensors[1].Found = !(buff[9] == 0xff && buff[10] == 0xff && buff[11] == 0xff); mWiimoteState.IRState.IRSensors[2].Found = !(buff[12] == 0xff && buff[13] == 0xff && buff[14] == 0xff); mWiimoteState.IRState.IRSensors[3].Found = !(buff[15] == 0xff && buff[16] == 0xff && buff[17] == 0xff); break; } mWiimoteState.IRState.IRSensors[0].Position.X = (float)(mWiimoteState.IRState.IRSensors[0].RawPosition.X / 1023.5f); mWiimoteState.IRState.IRSensors[1].Position.X = (float)(mWiimoteState.IRState.IRSensors[1].RawPosition.X / 1023.5f); mWiimoteState.IRState.IRSensors[2].Position.X = (float)(mWiimoteState.IRState.IRSensors[2].RawPosition.X / 1023.5f); mWiimoteState.IRState.IRSensors[3].Position.X = (float)(mWiimoteState.IRState.IRSensors[3].RawPosition.X / 1023.5f); mWiimoteState.IRState.IRSensors[0].Position.Y = (float)(mWiimoteState.IRState.IRSensors[0].RawPosition.Y / 767.5f); mWiimoteState.IRState.IRSensors[1].Position.Y = (float)(mWiimoteState.IRState.IRSensors[1].RawPosition.Y / 767.5f); mWiimoteState.IRState.IRSensors[2].Position.Y = (float)(mWiimoteState.IRState.IRSensors[2].RawPosition.Y / 767.5f); mWiimoteState.IRState.IRSensors[3].Position.Y = (float)(mWiimoteState.IRState.IRSensors[3].RawPosition.Y / 767.5f); if(mWiimoteState.IRState.IRSensors[0].Found && mWiimoteState.IRState.IRSensors[1].Found) { mWiimoteState.IRState.RawMidpoint.X = (mWiimoteState.IRState.IRSensors[1].RawPosition.X + mWiimoteState.IRState.IRSensors[0].RawPosition.X) / 2; mWiimoteState.IRState.RawMidpoint.Y = (mWiimoteState.IRState.IRSensors[1].RawPosition.Y + mWiimoteState.IRState.IRSensors[0].RawPosition.Y) / 2; mWiimoteState.IRState.Midpoint.X = (mWiimoteState.IRState.IRSensors[1].Position.X + mWiimoteState.IRState.IRSensors[0].Position.X) / 2.0f; mWiimoteState.IRState.Midpoint.Y = (mWiimoteState.IRState.IRSensors[1].Position.Y + mWiimoteState.IRState.IRSensors[0].Position.Y) / 2.0f; } else mWiimoteState.IRState.Midpoint.X = mWiimoteState.IRState.Midpoint.Y = 0.0f; } /// <summary> /// Toggles tone streaming to wiimote /// </summary> public void ToggleSound(bool tones) { if (!SoundPlaying) { BeginAudioSetup(); if (tones) StreamMusicThread = new Thread(PlayAudioTones); /*else StreamMusicThread = new Thread(PlayAudioFile);*/ StreamMusicThread.Start(); SoundPlaying = true; } else { if (StreamMusicThread.ThreadState == System.Threading.ThreadState.Running) StreamMusicThread.Abort(); SoundPlaying = false; } } /// <summary> /// Plays tones /// </summary> public void PlayTone(byte freq, byte vol, byte amp) { frequency = freq; volume = vol; amplitude = amp; BeginAudioSetup(); byte[] mBuff = CreateReport(); for (int j = 0; j < 20; j++) { mBuff[0] = (byte)OutputReport.SpeakerDataOut; mBuff[1] = (byte)((20 << 3) | GetRumbleBit()); for (int i = 2; i < 22; i++) { mBuff[i] = amplitude; // Amplitude } //amplitude--; Drop this over time?? WriteReport(mBuff); } //StreamMusicThread = new Thread(PlayAudio); //StreamMusicThread.Start(); } /// <summary> /// Plays tones with length /// </summary> public void PlayTone(byte freq, byte vol, byte amp, int noteLength) { frequency = freq; volume = vol; amplitude = amp; BeginAudioSetup(); byte[] mBuff = CreateReport(); for (int j = 0; j < 20 * noteLength; j++) { mBuff[0] = (byte)OutputReport.SpeakerDataOut; mBuff[1] = (byte)((20 << 3) | GetRumbleBit()); for (int i = 2; i < 22; i++) mBuff[i] = amplitude; // Amplitude //amplitude--; Drop this over time?? WriteReport(mBuff); } //StreamMusicThread = new Thread(PlayAudio); //StreamMusicThread.Start(); } /// <summary> /// Plays a tone /// </summary> private void PlayAudioTones() { byte[] mBuff = CreateReport(); for (int j = 0; j < 20; j++) { mBuff[0] = (byte)OutputReport.SpeakerDataOut; mBuff[1] = (byte)((20 << 3) | GetRumbleBit()); for (int i = 2; i < 22; i++) mBuff[i] = amplitude; // Amplitude //amplitude--; Drop this over time?? WriteReport(mBuff); } } /// <summary> /// Plays an audio file /// </summary> public void PlayAudioFile(string loc) { FileStream stream = new FileStream(loc, FileMode.Open, FileAccess.Read); byte[] mBuff = CreateReport(); // dump header for (int i = 0; i < 44; i++) stream.ReadByte(); while (true) { mBuff[0] = (byte)OutputReport.SpeakerDataOut; mBuff[1] = (byte)((20 << 3) | GetRumbleBit()); for (int i = 2; i < 22; i++) mBuff[i] = (byte)stream.ReadByte(); WriteReport(mBuff); } //int messageCount = 1; //TextWriter writer = new StreamWriter("MessageTimes.txt"); //byte[] mBuff = CreateReport(); //while (true) //{ // writer.WriteLine("Before message " + messageCount + ": " + DateTime.Now + " " + DateTime.Now.Second + " " + DateTime.Now.Millisecond); // for (int j = 0; j < 10; j++) // { // mBuff[0] = (byte)OutputReport.SpeakerDataOut; // mBuff[1] = (byte)((20 << 3) | GetRumbleBit()); // for (int i = 2; i < 22; i++) // mBuff[i] = 0xC3; // WriteReport(mBuff); // } // writer.WriteLine("After message " + messageCount + ": " + DateTime.Now + " " + DateTime.Now.Second + " " + DateTime.Now.Millisecond); // messageCount++; // if (messageCount > 50) // break; // Thread.Sleep(1000); //} //writer.Close(); //StreamMusicThread.Abort(); } /// <summary> /// Completes the necessary 7-step process for speaker activation /// </summary> private void BeginAudioSetup() { byte[] mBuff = CreateReport(); //1. Enable speaker (Send 0x04 to Output Report 0x14) mBuff[0] = (byte)OutputReport.SpeakerOnOff; mBuff[1] = (byte)(0x04 | GetRumbleBit()); WriteReport(mBuff); mBuff = CreateReport(); //2. Mute speaker (Send 0x04 to Output Report 0x19) mBuff[0] = (byte)OutputReport.SpeakerMute; mBuff[1] = (byte)(0x04 | GetRumbleBit()); WriteReport(mBuff); mBuff = CreateReport(); //3. Write 0x01 to register 0xa20009 (0x04a20009) WriteData(0x04a20009, 0x01); //4. Write 0x08 to register 0xa20001 (0x04a20001) WriteData(0x04a20001, 0x08); int sampleRate = 7280; int sampleRateWii = (sampleRate - 7280) / -280; //5. Write 7-byte configuration to registers 0xa20001-0xa20008 (0x04a20001) byte[] bytes = new byte[7]; bytes[0] = (byte)0x00; // Unknown bytes[1] = (byte)0x00; // Data format - 0x00 for Yamaha 4-bit ADPCM, 0x40 for signed 8-bit PCM bytes[2] = (byte)sampleRateWii; // Sample Rate - equation is y = -280x + 7280, where x is the actual sample rate. ex: sample rate of 4200 = 0x0B bytes[3] = (byte)frequency; // Frequency bytes[4] = (byte)volume; // Volume - 0x00 to 0xFF in 8-bit mode, 0x00 to 0x40 in 4-bit mode bytes[5] = (byte)0x00; // Unknown bytes[6] = (byte)0x00; // Unknown WriteData(0x04a20001, 7, bytes); //6. Write 0x01 to register 0xa20008 (0x04a20008) WriteData(0x04a20008, 0x01); mBuff = CreateReport(); //7. Unmute speaker (Send 0x00 to Output Report 0x19) mBuff[0] = (byte)OutputReport.SpeakerMute; mBuff[1] = (byte)(0x00 | GetRumbleBit()); WriteReport(mBuff); mBuff = CreateReport(); } /// <summary> /// Parse data from an extension controller /// </summary> /// <param name="buff">Data buffer</param> /// <param name="offset">Offset into data buffer</param> private void ParseExtension(byte[] buff, int offset) { switch(mWiimoteState.ExtensionType) { case ExtensionType.Nunchuk: case ExtensionType.Nunchuk2: case ExtensionType.Nunchuk3: mWiimoteState.NunchukState.RawJoystick.X = buff[offset]; mWiimoteState.NunchukState.RawJoystick.Y = buff[offset + 1]; mWiimoteState.NunchukState.AccelState.RawValues.X = buff[offset + 2]; mWiimoteState.NunchukState.AccelState.RawValues.Y = buff[offset + 3]; mWiimoteState.NunchukState.AccelState.RawValues.Z = buff[offset + 4]; mWiimoteState.NunchukState.C = (buff[offset + 5] & 0x02) == 0; mWiimoteState.NunchukState.Z = (buff[offset + 5] & 0x01) == 0; mWiimoteState.NunchukState.AccelState.Values.X = (float)((float)mWiimoteState.NunchukState.AccelState.RawValues.X - mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.X0) / ((float)mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.XG - mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.X0); mWiimoteState.NunchukState.AccelState.Values.Y = (float)((float)mWiimoteState.NunchukState.AccelState.RawValues.Y - mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.Y0) / ((float)mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.YG - mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.Y0); mWiimoteState.NunchukState.AccelState.Values.Z = (float)((float)mWiimoteState.NunchukState.AccelState.RawValues.Z - mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.Z0) / ((float)mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.ZG - mWiimoteState.NunchukState.CalibrationInfo.AccelCalibration.Z0); if(mWiimoteState.NunchukState.CalibrationInfo.MaxX != 0x00) mWiimoteState.NunchukState.Joystick.X = (float)((float)mWiimoteState.NunchukState.RawJoystick.X - mWiimoteState.NunchukState.CalibrationInfo.MidX) / ((float)mWiimoteState.NunchukState.CalibrationInfo.MaxX - mWiimoteState.NunchukState.CalibrationInfo.MinX); if(mWiimoteState.NunchukState.CalibrationInfo.MaxY != 0x00) mWiimoteState.NunchukState.Joystick.Y = (float)((float)mWiimoteState.NunchukState.RawJoystick.Y - mWiimoteState.NunchukState.CalibrationInfo.MidY) / ((float)mWiimoteState.NunchukState.CalibrationInfo.MaxY - mWiimoteState.NunchukState.CalibrationInfo.MinY); break; case ExtensionType.ClassicController: mWiimoteState.ClassicControllerState.RawJoystickL.X = (byte)(buff[offset] & 0x3f); mWiimoteState.ClassicControllerState.RawJoystickL.Y = (byte)(buff[offset + 1] & 0x3f); mWiimoteState.ClassicControllerState.RawJoystickR.X = (byte)((buff[offset + 2] >> 7) | (buff[offset + 1] & 0xc0) >> 5 | (buff[offset] & 0xc0) >> 3); mWiimoteState.ClassicControllerState.RawJoystickR.Y = (byte)(buff[offset + 2] & 0x1f); mWiimoteState.ClassicControllerState.RawTriggerL = (byte)(((buff[offset + 2] & 0x60) >> 2) | (buff[offset + 3] >> 5)); mWiimoteState.ClassicControllerState.RawTriggerR = (byte)(buff[offset + 3] & 0x1f); mWiimoteState.ClassicControllerState.ButtonState.TriggerR = (buff[offset + 4] & 0x02) == 0; mWiimoteState.ClassicControllerState.ButtonState.Plus = (buff[offset + 4] & 0x04) == 0; mWiimoteState.ClassicControllerState.ButtonState.Home = (buff[offset + 4] & 0x08) == 0; mWiimoteState.ClassicControllerState.ButtonState.Minus = (buff[offset + 4] & 0x10) == 0; mWiimoteState.ClassicControllerState.ButtonState.TriggerL = (buff[offset + 4] & 0x20) == 0; mWiimoteState.ClassicControllerState.ButtonState.Down = (buff[offset + 4] & 0x40) == 0; mWiimoteState.ClassicControllerState.ButtonState.Right = (buff[offset + 4] & 0x80) == 0; mWiimoteState.ClassicControllerState.ButtonState.Up = (buff[offset + 5] & 0x01) == 0; mWiimoteState.ClassicControllerState.ButtonState.Left = (buff[offset + 5] & 0x02) == 0; mWiimoteState.ClassicControllerState.ButtonState.ZR = (buff[offset + 5] & 0x04) == 0; mWiimoteState.ClassicControllerState.ButtonState.X = (buff[offset + 5] & 0x08) == 0; mWiimoteState.ClassicControllerState.ButtonState.A = (buff[offset + 5] & 0x10) == 0; mWiimoteState.ClassicControllerState.ButtonState.Y = (buff[offset + 5] & 0x20) == 0; mWiimoteState.ClassicControllerState.ButtonState.B = (buff[offset + 5] & 0x40) == 0; mWiimoteState.ClassicControllerState.ButtonState.ZL = (buff[offset + 5] & 0x80) == 0; if(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxXL != 0x00) mWiimoteState.ClassicControllerState.JoystickL.X = (float)((float)mWiimoteState.ClassicControllerState.RawJoystickL.X - mWiimoteState.ClassicControllerState.CalibrationInfo.MidXL) / (float)(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxXL - mWiimoteState.ClassicControllerState.CalibrationInfo.MinXL); if(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxYL != 0x00) mWiimoteState.ClassicControllerState.JoystickL.Y = (float)((float)mWiimoteState.ClassicControllerState.RawJoystickL.Y - mWiimoteState.ClassicControllerState.CalibrationInfo.MidYL) / (float)(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxYL - mWiimoteState.ClassicControllerState.CalibrationInfo.MinYL); if(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxXR != 0x00) mWiimoteState.ClassicControllerState.JoystickR.X = (float)((float)mWiimoteState.ClassicControllerState.RawJoystickR.X - mWiimoteState.ClassicControllerState.CalibrationInfo.MidXR) / (float)(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxXR - mWiimoteState.ClassicControllerState.CalibrationInfo.MinXR); if(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxYR != 0x00) mWiimoteState.ClassicControllerState.JoystickR.Y = (float)((float)mWiimoteState.ClassicControllerState.RawJoystickR.Y - mWiimoteState.ClassicControllerState.CalibrationInfo.MidYR) / (float)(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxYR - mWiimoteState.ClassicControllerState.CalibrationInfo.MinYR); if(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxTriggerL != 0x00) mWiimoteState.ClassicControllerState.TriggerL = (mWiimoteState.ClassicControllerState.RawTriggerL) / (float)(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxTriggerL - mWiimoteState.ClassicControllerState.CalibrationInfo.MinTriggerL); if(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxTriggerR != 0x00) mWiimoteState.ClassicControllerState.TriggerR = (mWiimoteState.ClassicControllerState.RawTriggerR) / (float)(mWiimoteState.ClassicControllerState.CalibrationInfo.MaxTriggerR - mWiimoteState.ClassicControllerState.CalibrationInfo.MinTriggerR); break; case ExtensionType.Guitar: mWiimoteState.GuitarState.GuitarType = ((buff[offset] & 0x80) == 0) ? GuitarType.GuitarHeroWorldTour : GuitarType.GuitarHero3; mWiimoteState.GuitarState.ButtonState.Plus = (buff[offset + 4] & 0x04) == 0; mWiimoteState.GuitarState.ButtonState.Minus = (buff[offset + 4] & 0x10) == 0; mWiimoteState.GuitarState.ButtonState.StrumDown = (buff[offset + 4] & 0x40) == 0; mWiimoteState.GuitarState.ButtonState.StrumUp = (buff[offset + 5] & 0x01) == 0; mWiimoteState.GuitarState.FretButtonState.Yellow = (buff[offset + 5] & 0x08) == 0; mWiimoteState.GuitarState.FretButtonState.Green = (buff[offset + 5] & 0x10) == 0; mWiimoteState.GuitarState.FretButtonState.Blue = (buff[offset + 5] & 0x20) == 0; mWiimoteState.GuitarState.FretButtonState.Red = (buff[offset + 5] & 0x40) == 0; mWiimoteState.GuitarState.FretButtonState.Orange = (buff[offset + 5] & 0x80) == 0; // it appears the joystick values are only 6 bits mWiimoteState.GuitarState.RawJoystick.X = (buff[offset + 0] & 0x3f); mWiimoteState.GuitarState.RawJoystick.Y = (buff[offset + 1] & 0x3f); // and the whammy bar is only 5 bits mWiimoteState.GuitarState.RawWhammyBar = (byte)(buff[offset + 3] & 0x1f); mWiimoteState.GuitarState.Joystick.X = (float)(mWiimoteState.GuitarState.RawJoystick.X - 0x1f) / 0x3f; // not fully accurate, but close mWiimoteState.GuitarState.Joystick.Y = (float)(mWiimoteState.GuitarState.RawJoystick.Y - 0x1f) / 0x3f; // not fully accurate, but close mWiimoteState.GuitarState.WhammyBar = (float)(mWiimoteState.GuitarState.RawWhammyBar) / 0x0a; // seems like there are 10 positions? mWiimoteState.GuitarState.TouchbarState.Yellow = false; mWiimoteState.GuitarState.TouchbarState.Green = false; mWiimoteState.GuitarState.TouchbarState.Blue = false; mWiimoteState.GuitarState.TouchbarState.Red = false; mWiimoteState.GuitarState.TouchbarState.Orange = false; switch(buff[offset + 2] & 0x1f) { case 0x04: mWiimoteState.GuitarState.TouchbarState.Green = true; break; case 0x07: mWiimoteState.GuitarState.TouchbarState.Green = true; mWiimoteState.GuitarState.TouchbarState.Red = true; break; case 0x0a: mWiimoteState.GuitarState.TouchbarState.Red = true; break; case 0x0c: case 0x0d: mWiimoteState.GuitarState.TouchbarState.Red = true; mWiimoteState.GuitarState.TouchbarState.Yellow = true; break; case 0x12: case 0x13: mWiimoteState.GuitarState.TouchbarState.Yellow = true; break; case 0x14: case 0x15: mWiimoteState.GuitarState.TouchbarState.Yellow = true; mWiimoteState.GuitarState.TouchbarState.Blue = true; break; case 0x17: case 0x18: mWiimoteState.GuitarState.TouchbarState.Blue = true; break; case 0x1a: mWiimoteState.GuitarState.TouchbarState.Blue = true; mWiimoteState.GuitarState.TouchbarState.Orange = true; break; case 0x1f: mWiimoteState.GuitarState.TouchbarState.Orange = true; break; } break; case ExtensionType.Drums: // it appears the joystick values are only 6 bits mWiimoteState.DrumsState.RawJoystick.X = (buff[offset + 0] & 0x3f); mWiimoteState.DrumsState.RawJoystick.Y = (buff[offset + 1] & 0x3f); mWiimoteState.DrumsState.Plus = (buff[offset + 4] & 0x04) == 0; mWiimoteState.DrumsState.Minus = (buff[offset + 4] & 0x10) == 0; mWiimoteState.DrumsState.Pedal = (buff[offset + 5] & 0x04) == 0; mWiimoteState.DrumsState.Blue = (buff[offset + 5] & 0x08) == 0; mWiimoteState.DrumsState.Green = (buff[offset + 5] & 0x10) == 0; mWiimoteState.DrumsState.Yellow = (buff[offset + 5] & 0x20) == 0; mWiimoteState.DrumsState.Red = (buff[offset + 5] & 0x40) == 0; mWiimoteState.DrumsState.Orange = (buff[offset + 5] & 0x80) == 0; mWiimoteState.DrumsState.Joystick.X = (float)(mWiimoteState.DrumsState.RawJoystick.X - 0x1f) / 0x3f; // not fully accurate, but close mWiimoteState.DrumsState.Joystick.Y = (float)(mWiimoteState.DrumsState.RawJoystick.Y - 0x1f) / 0x3f; // not fully accurate, but close if((buff[offset + 2] & 0x40) == 0) { int pad = (buff[offset + 2] >> 1) & 0x1f; int velocity = (buff[offset + 3] >> 5); if(velocity != 7) { switch(pad) { case 0x1b: mWiimoteState.DrumsState.PedalVelocity = velocity; break; case 0x19: mWiimoteState.DrumsState.RedVelocity = velocity; break; case 0x11: mWiimoteState.DrumsState.YellowVelocity = velocity; break; case 0x0f: mWiimoteState.DrumsState.BlueVelocity = velocity; break; case 0x0e: mWiimoteState.DrumsState.OrangeVelocity = velocity; break; case 0x12: mWiimoteState.DrumsState.GreenVelocity = velocity; break; } } } break; case ExtensionType.BalanceBoard: mWiimoteState.BalanceBoardState.SensorValuesRaw.TopRight = (short)((short)buff[offset + 0] << 8 | buff[offset + 1]); mWiimoteState.BalanceBoardState.SensorValuesRaw.BottomRight = (short)((short)buff[offset + 2] << 8 | buff[offset + 3]); mWiimoteState.BalanceBoardState.SensorValuesRaw.TopLeft = (short)((short)buff[offset + 4] << 8 | buff[offset + 5]); mWiimoteState.BalanceBoardState.SensorValuesRaw.BottomLeft = (short)((short)buff[offset + 6] << 8 | buff[offset + 7]); mWiimoteState.BalanceBoardState.SensorValuesKg.TopLeft = GetBalanceBoardSensorValue(mWiimoteState.BalanceBoardState.SensorValuesRaw.TopLeft, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.TopLeft, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.TopLeft, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.TopLeft); mWiimoteState.BalanceBoardState.SensorValuesKg.TopRight = GetBalanceBoardSensorValue(mWiimoteState.BalanceBoardState.SensorValuesRaw.TopRight, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.TopRight, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.TopRight, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.TopRight); mWiimoteState.BalanceBoardState.SensorValuesKg.BottomLeft = GetBalanceBoardSensorValue(mWiimoteState.BalanceBoardState.SensorValuesRaw.BottomLeft, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.BottomLeft, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.BottomLeft, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.BottomLeft); mWiimoteState.BalanceBoardState.SensorValuesKg.BottomRight = GetBalanceBoardSensorValue(mWiimoteState.BalanceBoardState.SensorValuesRaw.BottomRight, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg0.BottomRight, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg17.BottomRight, mWiimoteState.BalanceBoardState.CalibrationInfo.Kg34.BottomRight); mWiimoteState.BalanceBoardState.SensorValuesLb.TopLeft = (mWiimoteState.BalanceBoardState.SensorValuesKg.TopLeft * KG2LB); mWiimoteState.BalanceBoardState.SensorValuesLb.TopRight = (mWiimoteState.BalanceBoardState.SensorValuesKg.TopRight * KG2LB); mWiimoteState.BalanceBoardState.SensorValuesLb.BottomLeft = (mWiimoteState.BalanceBoardState.SensorValuesKg.BottomLeft * KG2LB); mWiimoteState.BalanceBoardState.SensorValuesLb.BottomRight = (mWiimoteState.BalanceBoardState.SensorValuesKg.BottomRight * KG2LB); mWiimoteState.BalanceBoardState.WeightKg = (mWiimoteState.BalanceBoardState.SensorValuesKg.TopLeft + mWiimoteState.BalanceBoardState.SensorValuesKg.TopRight + mWiimoteState.BalanceBoardState.SensorValuesKg.BottomLeft + mWiimoteState.BalanceBoardState.SensorValuesKg.BottomRight) / 4.0f; mWiimoteState.BalanceBoardState.WeightLb = (mWiimoteState.BalanceBoardState.SensorValuesLb.TopLeft + mWiimoteState.BalanceBoardState.SensorValuesLb.TopRight + mWiimoteState.BalanceBoardState.SensorValuesLb.BottomLeft + mWiimoteState.BalanceBoardState.SensorValuesLb.BottomRight) / 4.0f; float Kx = (mWiimoteState.BalanceBoardState.SensorValuesKg.TopLeft + mWiimoteState.BalanceBoardState.SensorValuesKg.BottomLeft) / (mWiimoteState.BalanceBoardState.SensorValuesKg.TopRight + mWiimoteState.BalanceBoardState.SensorValuesKg.BottomRight); float Ky = (mWiimoteState.BalanceBoardState.SensorValuesKg.TopLeft + mWiimoteState.BalanceBoardState.SensorValuesKg.TopRight) / (mWiimoteState.BalanceBoardState.SensorValuesKg.BottomLeft + mWiimoteState.BalanceBoardState.SensorValuesKg.BottomRight); mWiimoteState.BalanceBoardState.CenterOfGravity.X = ((float)(Kx - 1) / (float)(Kx + 1)) * (float)(-BSL / 2); mWiimoteState.BalanceBoardState.CenterOfGravity.Y = ((float)(Ky - 1) / (float)(Ky + 1)) * (float)(-BSW / 2); break; case ExtensionType.TaikoDrum: mWiimoteState.TaikoDrumState.OuterLeft = (buff[offset + 5] & 0x20) == 0; mWiimoteState.TaikoDrumState.InnerLeft = (buff[offset + 5] & 0x40) == 0; mWiimoteState.TaikoDrumState.InnerRight = (buff[offset + 5] & 0x10) == 0; mWiimoteState.TaikoDrumState.OuterRight = (buff[offset + 5] & 0x08) == 0; break; case ExtensionType.MotionPlus: mWiimoteState.MotionPlusState.YawFast = ((buff[offset + 3] & 0x02) >> 1) == 0; mWiimoteState.MotionPlusState.PitchFast = ((buff[offset + 3] & 0x01) >> 0) == 0; mWiimoteState.MotionPlusState.RollFast = ((buff[offset + 4] & 0x02) >> 1) == 0; mWiimoteState.MotionPlusState.RawValues.X = (buff[offset + 0] | (buff[offset + 3] & 0xfa) << 6); mWiimoteState.MotionPlusState.RawValues.Y = (buff[offset + 1] | (buff[offset + 4] & 0xfa) << 6); mWiimoteState.MotionPlusState.RawValues.Z = (buff[offset + 2] | (buff[offset + 5] & 0xfa) << 6); break; } } private float GetBalanceBoardSensorValue(short sensor, short min, short mid, short max) { if(max == mid || mid == min) return 0; if(sensor < mid) return 68.0f * ((float)(sensor - min) / (mid - min)); else return 68.0f * ((float)(sensor - mid) / (max - mid)) + 68.0f; } /// <summary> /// Parse data returned from a read report /// </summary> /// <param name="buff">Data buffer</param> private void ParseReadData(byte[] buff) { if((buff[3] & 0x08) != 0) throw new WiimoteException("Error reading data from Wiimote: Bytes do not exist."); if((buff[3] & 0x07) != 0) { Debug.WriteLine("*** read from write-only"); LastReadStatus = LastReadStatus.ReadFromWriteOnlyMemory; mReadDone.Set(); return; } // get our size and offset from the report int size = (buff[3] >> 4) + 1; int offset = (buff[4] << 8 | buff[5]); // add it to the buffer Array.Copy(buff, 6, mReadBuff, offset - mAddress, size); // if we've read it all, set the event if(mAddress + mSize == offset + size) mReadDone.Set(); LastReadStatus = LastReadStatus.Success; } /// <summary> /// Returns whether rumble is currently enabled. /// </summary> /// <returns>Byte indicating true (0x01) or false (0x00)</returns> private byte GetRumbleBit() { return (byte)(mWiimoteState.Rumble ? 0x01 : 0x00); } /// <summary> /// Read calibration information stored on Wiimote /// </summary> private void ReadWiimoteCalibration() { // this appears to change the report type to 0x31 byte[] buff = ReadData(0x0016, 7); mWiimoteState.AccelCalibrationInfo.X0 = buff[0]; mWiimoteState.AccelCalibrationInfo.Y0 = buff[1]; mWiimoteState.AccelCalibrationInfo.Z0 = buff[2]; mWiimoteState.AccelCalibrationInfo.XG = buff[4]; mWiimoteState.AccelCalibrationInfo.YG = buff[5]; mWiimoteState.AccelCalibrationInfo.ZG = buff[6]; } /// <summary> /// Set Wiimote reporting mode (if using an IR report type, IR sensitivity is set to WiiLevel3) /// </summary> /// <param name="type">Report type</param> /// <param name="continuous">Continuous data</param> public void SetReportType(InputReport type, bool continuous) { Debug.WriteLine("SetReportType: " + type); SetReportType(type, IRSensitivity.Maximum, continuous); } /// <summary> /// Set Wiimote reporting mode /// </summary> /// <param name="type">Report type</param> /// <param name="irSensitivity">IR sensitivity</param> /// <param name="continuous">Continuous data</param> public void SetReportType(InputReport type, IRSensitivity irSensitivity, bool continuous) { // only 1 report type allowed for the BB if(mWiimoteState.ExtensionType == ExtensionType.BalanceBoard) type = InputReport.ButtonsExtension; switch(type) { case InputReport.IRAccel: EnableIR(IRMode.Extended, irSensitivity); break; case InputReport.IRExtensionAccel: EnableIR(IRMode.Basic, irSensitivity); break; default: DisableIR(); break; } byte[] buff = CreateReport(); buff[0] = (byte)OutputReport.DataReportType; buff[1] = (byte)((continuous ? 0x04 : 0x00) | (byte)(mWiimoteState.Rumble ? 0x01 : 0x00)); buff[2] = (byte)type; WriteReport(buff); } /// <summary> /// Set the LEDs on the Wiimote /// </summary> /// <param name="led1">LED 1</param> /// <param name="led2">LED 2</param> /// <param name="led3">LED 3</param> /// <param name="led4">LED 4</param> public void SetLEDs(bool led1, bool led2, bool led3, bool led4) { mWiimoteState.LEDState.LED1 = led1; mWiimoteState.LEDState.LED2 = led2; mWiimoteState.LEDState.LED3 = led3; mWiimoteState.LEDState.LED4 = led4; byte[] buff = CreateReport(); buff[0] = (byte)OutputReport.LEDs; buff[1] = (byte)( (led1 ? 0x10 : 0x00) | (led2 ? 0x20 : 0x00) | (led3 ? 0x40 : 0x00) | (led4 ? 0x80 : 0x00) | GetRumbleBit()); WriteReport(buff); } /// <summary> /// Set the LEDs on the Wiimote /// </summary> /// <param name="leds">The value to be lit up in base2 on the Wiimote</param> public void SetLEDs(int leds) { mWiimoteState.LEDState.LED1 = (leds & 0x01) > 0; mWiimoteState.LEDState.LED2 = (leds & 0x02) > 0; mWiimoteState.LEDState.LED3 = (leds & 0x04) > 0; mWiimoteState.LEDState.LED4 = (leds & 0x08) > 0; byte[] buff = CreateReport(); buff[0] = (byte)OutputReport.LEDs; buff[1] = (byte)( ((leds & 0x01) > 0 ? 0x10 : 0x00) | ((leds & 0x02) > 0 ? 0x20 : 0x00) | ((leds & 0x04) > 0 ? 0x40 : 0x00) | ((leds & 0x08) > 0 ? 0x80 : 0x00) | GetRumbleBit()); WriteReport(buff); } /// <summary> /// Toggle rumble /// </summary> /// <param name="on">On or off</param> public void SetRumble(bool on) { mWiimoteState.Rumble = on; // the LED report also handles rumble SetLEDs(mWiimoteState.LEDState.LED1, mWiimoteState.LEDState.LED2, mWiimoteState.LEDState.LED3, mWiimoteState.LEDState.LED4); } /// <summary> /// Retrieve the current status of the Wiimote and extensions. Replaces GetBatteryLevel() since it was poorly named. /// </summary> public void GetStatus() { Debug.WriteLine("GetStatus"); byte[] buff = CreateReport(); buff[0] = (byte)OutputReport.Status; buff[1] = GetRumbleBit(); WriteReport(buff); // signal the status report finished if(!mStatusDone.WaitOne(3000, false)) throw new WiimoteException("Timed out waiting for status report"); } /// <summary> /// Turn on the IR sensor /// </summary> /// <param name="mode">The data report mode</param> /// <param name="irSensitivity">IR sensitivity</param> private void EnableIR(IRMode mode, IRSensitivity irSensitivity) { mWiimoteState.IRState.Mode = mode; byte[] buff = CreateReport(); buff[0] = (byte)OutputReport.IR; buff[1] = (byte)(0x04 | GetRumbleBit()); WriteReport(buff); Array.Clear(buff, 0, buff.Length); buff[0] = (byte)OutputReport.IR2; buff[1] = (byte)(0x04 | GetRumbleBit()); WriteReport(buff); WriteData(REGISTER_IR, 0x08); switch(irSensitivity) { case IRSensitivity.WiiLevel1: WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x64, 0x00, 0xfe}); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0xfd, 0x05}); break; case IRSensitivity.WiiLevel2: WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x96, 0x00, 0xb4}); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0xb3, 0x04}); break; case IRSensitivity.WiiLevel3: WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x63, 0x03}); break; case IRSensitivity.WiiLevel4: WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xc8, 0x00, 0x36}); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x35, 0x03}); break; case IRSensitivity.WiiLevel5: WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x07, 0x00, 0x00, 0x71, 0x01, 0x00, 0x72, 0x00, 0x20}); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x1, 0x03}); break; case IRSensitivity.Maximum: WriteData(REGISTER_IR_SENSITIVITY_1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x90, 0x00, 0x41}); WriteData(REGISTER_IR_SENSITIVITY_2, 2, new byte[] {0x40, 0x00}); break; default: throw new ArgumentOutOfRangeException("irSensitivity"); } WriteData(REGISTER_IR_MODE, (byte)mode); WriteData(REGISTER_IR, 0x08); } /// <summary> /// Disable the IR sensor /// </summary> private void DisableIR() { mWiimoteState.IRState.Mode = IRMode.Off; byte[] buff = CreateReport(); buff[0] = (byte)OutputReport.IR; buff[1] = GetRumbleBit(); WriteReport(buff); Array.Clear(buff, 0, buff.Length); buff[0] = (byte)OutputReport.IR2; buff[1] = GetRumbleBit(); WriteReport(buff); } /// <summary> /// Initialize the report data buffer /// </summary> private byte[] CreateReport() { return new byte[REPORT_LENGTH]; } /// <summary> /// Write a report to the Wiimote /// </summary> private void WriteReport(byte[] buff) { Debug.WriteLine("WriteReport: " + Enum.Parse(typeof(OutputReport), buff[0].ToString())); if(mAltWriteMethod) HIDImports.HidD_SetOutputReport(this.mHandle.DangerousGetHandle(), buff, (uint)buff.Length); else if(mStream != null) mStream.Write(buff, 0, REPORT_LENGTH); if(buff[0] == (byte)OutputReport.WriteMemory) { // Debug.WriteLine("Wait"); if(!mWriteDone.WaitOne(1000, false)) Debug.WriteLine("Wait failed"); //throw new WiimoteException("Error writing data to Wiimote...is it connected?"); } } /// <summary> /// Read data or register from Wiimote /// </summary> /// <param name="address">Address to read</param> /// <param name="size">Length to read</param> /// <returns>Data buffer</returns> public byte[] ReadData(int address, short size) { byte[] buff = CreateReport(); mReadBuff = new byte[size]; mAddress = address & 0xffff; mSize = size; buff[0] = (byte)OutputReport.ReadMemory; buff[1] = (byte)(((address & 0xff000000) >> 24) | GetRumbleBit()); buff[2] = (byte)((address & 0x00ff0000) >> 16); buff[3] = (byte)((address & 0x0000ff00) >> 8);
[ "\t\t\tbuff[4] = (byte)(address & 0x000000ff);" ]
5,328
lcc
csharp
null
8e0bd228e7aa848a9bf8109d86ecaf76dcf9e5dee02fba5e
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# 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/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.vo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import ims.framework.enumerations.SortOrder; /** * Linked to core.clinical.Msk Joints business object (ID: 1040100001). */ public class MskJointVoCollection extends ims.vo.ValueObjectCollection implements ims.vo.ImsCloneable, Iterable<MskJointVo> { private static final long serialVersionUID = 1L; private ArrayList<MskJointVo> col = new ArrayList<MskJointVo>(); public String getBoClassName() { return "ims.core.clinical.domain.objects.MskJoints"; } public boolean add(MskJointVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { return this.col.add(value); } return false; } public boolean add(int index, MskJointVo value) { if(value == null) return false; if(this.col.indexOf(value) < 0) { this.col.add(index, value); return true; } return false; } public void clear() { this.col.clear(); } public void remove(int index) { this.col.remove(index); } public int size() { return this.col.size(); } public int indexOf(MskJointVo instance) { return col.indexOf(instance); } public MskJointVo get(int index) { return this.col.get(index); } public boolean set(int index, MskJointVo value) { if(value == null) return false; this.col.set(index, value); return true; } public void remove(MskJointVo instance) { if(instance != null) { int index = indexOf(instance); if(index >= 0) remove(index); } } public boolean contains(MskJointVo instance) { return indexOf(instance) >= 0; } public Object clone() { MskJointVoCollection clone = new MskJointVoCollection(); for(int x = 0; x < this.col.size(); x++) { if(this.col.get(x) != null) clone.col.add((MskJointVo)this.col.get(x).clone()); else clone.col.add(null); } return clone; } public boolean isValidated() { for(int x = 0; x < col.size(); x++) if(!this.col.get(x).isValidated()) return false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(col.size() == 0) return null; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } for(int x = 0; x < col.size(); x++) { String[] listOfOtherErrors = this.col.get(x).validate(); if(listOfOtherErrors != null) { for(int y = 0; y < listOfOtherErrors.length; y++) { listOfErrors.add(listOfOtherErrors[y]); } } } int errorCount = listOfErrors.size(); if(errorCount == 0) return null; String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); return result; } public MskJointVoCollection sort() { return sort(SortOrder.ASCENDING); } public MskJointVoCollection sort(boolean caseInsensitive) { return sort(SortOrder.ASCENDING, caseInsensitive); } public MskJointVoCollection sort(SortOrder order) { return sort(new MskJointVoComparator(order)); } public MskJointVoCollection sort(SortOrder order, boolean caseInsensitive) { return sort(new MskJointVoComparator(order, caseInsensitive)); } @SuppressWarnings("unchecked") public MskJointVoCollection sort(Comparator comparator) { Collections.sort(col, comparator); return this; } public ims.core.clinical.vo.MskJointsRefVoCollection toRefVoCollection() { ims.core.clinical.vo.MskJointsRefVoCollection result = new ims.core.clinical.vo.MskJointsRefVoCollection(); for(int x = 0; x < this.col.size(); x++) { result.add(this.col.get(x)); } return result; } public MskJointVo[] toArray() { MskJointVo[] arr = new MskJointVo[col.size()]; col.toArray(arr); return arr; } public Iterator<MskJointVo> iterator() { return col.iterator(); } @Override protected ArrayList getTypedCollection() { return col; } private class MskJointVoComparator implements Comparator { private int direction = 1; private boolean caseInsensitive = true; public MskJointVoComparator() { this(SortOrder.ASCENDING); } public MskJointVoComparator(SortOrder order) { if (order == SortOrder.DESCENDING) { direction = -1; } } public MskJointVoComparator(SortOrder order, boolean caseInsensitive) {
[ "\t\t\tif (order == SortOrder.DESCENDING)" ]
641
lcc
java
null
22de4bb8a2b770879cf742cb312eaec089c2f1c8e6caf97b
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Mail; using Server; using Server.Accounting; using Server.Network; namespace Server.Misc { public class CrashGuard { private static bool Enabled = true; private static bool SaveBackup = true; private static bool RestartServer = true; private static bool GenerateReport = true; public static void Initialize() { if ( Enabled ) // If enabled, register our crash event handler EventSink.Crashed += new CrashedEventHandler( CrashGuard_OnCrash ); } public static void CrashGuard_OnCrash( CrashedEventArgs e ) { if ( GenerateReport ) GenerateCrashReport( e ); World.WaitForWriteCompletion(); if ( SaveBackup ) Backup(); /*if ( Core.Service ) e.Close = true; else */ if ( RestartServer ) Restart( e ); } private static void SendEmail( string filePath ) { Console.Write( "Crash: Sending email..." ); MailMessage message = new MailMessage( Email.FromAddress, Email.CrashAddresses ); message.Subject = "Automated RunUO Crash Report"; message.Body = "Automated RunUO Crash Report. See attachment for details."; message.Attachments.Add( new Attachment( filePath ) ); if ( Email.Send( message ) ) Console.WriteLine( "done" ); else Console.WriteLine( "failed" ); } private static string GetRoot() { try { return Path.GetDirectoryName( Environment.GetCommandLineArgs()[0] ); } catch { return ""; } } private static string Combine( string path1, string path2 ) { if ( path1.Length == 0 ) return path2; return Path.Combine( path1, path2 ); } private static void Restart( CrashedEventArgs e ) { string root = GetRoot(); Console.Write( "Crash: Restarting..." ); try { Process.Start( Core.ExePath, Core.Arguments ); Console.WriteLine( "done" ); e.Close = true; } catch { Console.WriteLine( "failed" ); } } private static void CreateDirectory( string path ) { if ( !Directory.Exists( path ) ) Directory.CreateDirectory( path ); } private static void CreateDirectory( string path1, string path2 ) { CreateDirectory( Combine( path1, path2 ) ); } private static void CopyFile( string rootOrigin, string rootBackup, string path ) { string originPath = Combine( rootOrigin, path ); string backupPath = Combine( rootBackup, path ); try { if ( File.Exists( originPath ) ) File.Copy( originPath, backupPath ); } catch { } } private static void Backup() { Console.Write( "Crash: Backing up..." ); try { string timeStamp = GetTimeStamp(); string root = GetRoot(); string rootBackup = Combine( root, String.Format( "Backups/Crashed/{0}/", timeStamp ) ); string rootOrigin = Combine( root, String.Format( "Saves/" ) ); // Create new directories CreateDirectory( rootBackup ); CreateDirectory( rootBackup, "Accounts/" ); CreateDirectory( rootBackup, "Items/" ); CreateDirectory( rootBackup, "Mobiles/" ); CreateDirectory( rootBackup, "Guilds/" ); CreateDirectory( rootBackup, "Regions/" ); // Copy files CopyFile( rootOrigin, rootBackup, "Accounts/Accounts.xml" ); CopyFile( rootOrigin, rootBackup, "Items/Items.bin" ); CopyFile( rootOrigin, rootBackup, "Items/Items.idx" ); CopyFile( rootOrigin, rootBackup, "Items/Items.tdb" ); CopyFile( rootOrigin, rootBackup, "Mobiles/Mobiles.bin" ); CopyFile( rootOrigin, rootBackup, "Mobiles/Mobiles.idx" ); CopyFile( rootOrigin, rootBackup, "Mobiles/Mobiles.tdb" ); CopyFile( rootOrigin, rootBackup, "Guilds/Guilds.bin" ); CopyFile( rootOrigin, rootBackup, "Guilds/Guilds.idx" ); CopyFile( rootOrigin, rootBackup, "Regions/Regions.bin" ); CopyFile( rootOrigin, rootBackup, "Regions/Regions.idx" ); Console.WriteLine( "done" ); } catch { Console.WriteLine( "failed" ); } } private static void GenerateCrashReport( CrashedEventArgs e ) { Console.Write( "Crash: Generating report..." ); try { string timeStamp = GetTimeStamp(); string fileName = String.Format( "Crash {0}.log", timeStamp ); string root = GetRoot(); string filePath = Combine( root, fileName ); using ( StreamWriter op = new StreamWriter( filePath ) ) { Version ver = Core.Assembly.GetName().Version; op.WriteLine( "Server Crash Report" ); op.WriteLine( "===================" ); op.WriteLine(); op.WriteLine( "RunUO Version {0}.{1}, Build {2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision ); op.WriteLine( "Operating System: {0}", Environment.OSVersion ); op.WriteLine( ".NET Framework: {0}", Environment.Version ); op.WriteLine( "Time: {0}", DateTime.Now ); try { op.WriteLine( "Mobiles: {0}", World.Mobiles.Count ); } catch {} try { op.WriteLine( "Items: {0}", World.Items.Count ); } catch {} op.WriteLine( "Exception:" ); op.WriteLine( e.Exception ); op.WriteLine(); op.WriteLine( "Clients:" ); try { List<NetState> states = NetState.Instances; op.WriteLine( "- Count: {0}", states.Count ); for ( int i = 0; i < states.Count; ++i ) { NetState state = states[i]; op.Write( "+ {0}:", state ); Account a = state.Account as Account; if ( a != null ) op.Write( " (account = {0})", a.Username ); Mobile m = state.Mobile; if ( m != null ) op.Write( " (mobile = 0x{0:X} '{1}')", m.Serial.Value, m.Name ); op.WriteLine(); } } catch { op.WriteLine( "- Failed" ); } } Console.WriteLine( "done" ); if ( Email.FromAddress != null && Email.CrashAddresses != null )
[ "\t\t\t\t\tSendEmail( filePath );" ]
677
lcc
csharp
null
85d7beeed9e180c5fcee6fa973932cd47b046a7c181b3368
using System.Data.Common; using System.Collections; using NHibernate.Cache; using NHibernate.Cfg; using NHibernate.Engine; using NUnit.Framework; namespace NHibernate.Test.SecondLevelCacheTests { using Criterion; [TestFixture] public class SecondLevelCacheTest : TestCase { protected override string MappingsAssembly { get { return "NHibernate.Test"; } } protected override IList Mappings { get { return new string[] { "SecondLevelCacheTest.Item.hbm.xml" }; } } protected override void Configure(Configuration configuration) { base.Configure(configuration); configuration.Properties[Environment.CacheProvider] = typeof(HashtableCacheProvider).AssemblyQualifiedName; configuration.Properties[Environment.UseQueryCache] = "true"; } protected override void OnSetUp() { // Clear cache at each test. RebuildSessionFactory(); using (ISession session = OpenSession()) using (ITransaction tx = session.BeginTransaction()) { Item item = new Item(); item.Id = 1; session.Save(item); for (int i = 0; i < 4; i++) { Item child = new Item(); child.Id = i + 2; child.Parent = item; session.Save(child); item.Children.Add(child); } for (int i = 0; i < 5; i++) { AnotherItem obj = new AnotherItem("Item #" + i); obj.Id = i + 1; session.Save(obj); } tx.Commit(); } Sfi.Evict(typeof(Item)); Sfi.EvictCollection(typeof(Item).FullName + ".Children"); } protected override void OnTearDown() { using (ISession session = OpenSession()) { session.Delete("from Item"); //cleaning up session.Delete("from AnotherItem"); //cleaning up session.Flush(); } } [Test] public void CachedQueriesHandlesEntitiesParametersCorrectly() { using (ISession session = OpenSession()) { Item one = (Item)session.Load(typeof(Item), 1); IList results = session.CreateQuery("from Item item where item.Parent = :parent") .SetEntity("parent", one) .SetCacheable(true).List(); Assert.AreEqual(4, results.Count); foreach (Item item in results) { Assert.AreEqual(1, item.Parent.Id); } } using (ISession session = OpenSession()) { Item two = (Item)session.Load(typeof(Item), 2); IList results = session.CreateQuery("from Item item where item.Parent = :parent") .SetEntity("parent", two) .SetCacheable(true).List(); Assert.AreEqual(0, results.Count); } } [Test] public void DeleteItemFromCollectionThatIsInTheSecondLevelCache() { using (ISession session = OpenSession()) { Item item = (Item)session.Load(typeof(Item), 1); Assert.IsTrue(item.Children.Count == 4); // just force it into the second level cache here } int childId = -1; using (ISession session = OpenSession()) { Item item = (Item)session.Load(typeof(Item), 1); Item child = (Item)item.Children[0]; childId = child.Id; session.Delete(child); item.Children.Remove(child); session.Flush(); } using (ISession session = OpenSession()) { Item item = (Item)session.Load(typeof(Item), 1); Assert.AreEqual(3, item.Children.Count); foreach (Item child in item.Children) { NHibernateUtil.Initialize(child); Assert.IsFalse(child.Id == childId); } } } [Test] public void InsertItemToCollectionOnTheSecondLevelCache() { using (ISession session = OpenSession()) { Item item = (Item)session.Load(typeof(Item), 1); Item child = new Item(); child.Id = 6; item.Children.Add(child); session.Save(child); session.Flush(); } using (ISession session = OpenSession()) { Item item = (Item)session.Load(typeof(Item), 1); int count = item.Children.Count; Assert.AreEqual(5, count); } } [Test] public void SecondLevelCacheWithCriteriaQueries() { using (ISession session = OpenSession()) { IList list = session.CreateCriteria(typeof(AnotherItem)) .Add(Expression.Gt("Id", 2)) .SetCacheable(true) .List(); Assert.AreEqual(3, list.Count); using (var cmd = session.Connection.CreateCommand()) { cmd.CommandText = "DELETE FROM AnotherItem"; cmd.ExecuteNonQuery(); } } using (ISession session = OpenSession()) { //should bring from cache IList list = session.CreateCriteria(typeof(AnotherItem)) .Add(Expression.Gt("Id", 2)) .SetCacheable(true) .List(); Assert.AreEqual(3, list.Count); } } [Test] public void SecondLevelCacheWithCriteriaQueriesForItemWithCollections() { using (ISession session = OpenSession()) { IList list = session.CreateCriteria(typeof(Item)) .Add(Expression.Gt("Id", 2)) .SetCacheable(true) .List(); Assert.AreEqual(3, list.Count); using (var cmd = session.Connection.CreateCommand()) { cmd.CommandText = "DELETE FROM Item"; cmd.ExecuteNonQuery(); } } using (ISession session = OpenSession()) { //should bring from cache
[ "\t\t\t\tIList list = session.CreateCriteria(typeof(Item))" ]
480
lcc
csharp
null
ef2256036a1a6e12b496e5e9085b2f653cfd173eb485a40e
using System; using System.Text; namespace SharpCompress.Compressors.PPMd.H { internal class SubAllocator { public virtual int FakeUnitsStart { get { return _fakeUnitsStart; } set {_fakeUnitsStart = value; }} public virtual int HeapEnd => _heapEnd; public virtual int PText { get { return _pText; } set { _pText = value; }} public virtual int UnitsStart { get { return _unitsStart; } set { _unitsStart = value; }} public virtual byte[] Heap => _heap; //UPGRADE_NOTE: Final was removed from the declaration of 'N4 '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public const int N1 = 4; public const int N2 = 4; public const int N3 = 4; public static readonly int N4 = (128 + 3 - 1 * N1 - 2 * N2 - 3 * N3) / 4; //UPGRADE_NOTE: Final was removed from the declaration of 'N_INDEXES '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" public static readonly int N_INDEXES = N1 + N2 + N3 + N4; //UPGRADE_NOTE: Final was removed from the declaration of 'UNIT_SIZE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" //UPGRADE_NOTE: The initialization of 'UNIT_SIZE' was moved to static method 'SharpCompress.Unpack.PPM.SubAllocator'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" public static readonly int UNIT_SIZE; public const int FIXED_UNIT_SIZE = 12; private int _subAllocatorSize; // byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount; private readonly int[] _indx2Units = new int[N_INDEXES]; private readonly int[] _units2Indx = new int[128]; private int _glueCount; // byte *HeapStart,*LoUnit, *HiUnit; private int _heapStart, _loUnit, _hiUnit; //UPGRADE_NOTE: Final was removed from the declaration of 'freeList '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private readonly RarNode[] _freeList = new RarNode[N_INDEXES]; // byte *pText, *UnitsStart,*HeapEnd,*FakeUnitsStart; private int _pText, _unitsStart, _heapEnd, _fakeUnitsStart; private byte[] _heap; private int _freeListPos; private int _tempMemBlockPos; // Temp fields private RarNode _tempRarNode; private RarMemBlock _tempRarMemBlock1; private RarMemBlock _tempRarMemBlock2; private RarMemBlock _tempRarMemBlock3; public SubAllocator() { Clean(); } public virtual void Clean() { _subAllocatorSize = 0; } private void InsertNode(int p, int indx) { RarNode temp = _tempRarNode; temp.Address = p; temp.SetNext(_freeList[indx].GetNext()); _freeList[indx].SetNext(temp); } public virtual void IncPText() { _pText++; } private int RemoveNode(int indx) { int retVal = _freeList[indx].GetNext(); RarNode temp = _tempRarNode; temp.Address = retVal; _freeList[indx].SetNext(temp.GetNext()); return retVal; } private int U2B(int nu) { return UNIT_SIZE * nu; } /* memblockptr */ private int MbPtr(int basePtr, int items) { return (basePtr + U2B(items)); } private void SplitBlock(int pv, int oldIndx, int newIndx) { int i, uDiff = _indx2Units[oldIndx] - _indx2Units[newIndx]; int p = pv + U2B(_indx2Units[newIndx]); if (_indx2Units[i = _units2Indx[uDiff - 1]] != uDiff) { InsertNode(p, --i); p += U2B(i = _indx2Units[i]); uDiff -= i; } InsertNode(p, _units2Indx[uDiff - 1]); } public virtual void StopSubAllocator() { if (_subAllocatorSize != 0) { _subAllocatorSize = 0; //ArrayFactory.BYTES_FACTORY.recycle(heap); _heap = null; _heapStart = 1; // rarfree(HeapStart); // Free temp fields _tempRarNode = null; _tempRarMemBlock1 = null; _tempRarMemBlock2 = null; _tempRarMemBlock3 = null; } } public virtual int GetAllocatedMemory() { return _subAllocatorSize; } public virtual bool StartSubAllocator(int saSize) { int t = saSize; if (_subAllocatorSize == t) { return true; } StopSubAllocator(); int allocSize = t / FIXED_UNIT_SIZE * UNIT_SIZE + UNIT_SIZE; // adding space for freelist (needed for poiters) // 1+ for null pointer int realAllocSize = 1 + allocSize + 4 * N_INDEXES; // adding space for an additional memblock _tempMemBlockPos = realAllocSize; realAllocSize += RarMemBlock.SIZE; _heap = new byte[realAllocSize]; _heapStart = 1; _heapEnd = _heapStart + allocSize - UNIT_SIZE; _subAllocatorSize = t; // Bug fixed _freeListPos = _heapStart + allocSize; //UPGRADE_ISSUE: The following fragment of code could not be parsed and was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1156'" //assert(realAllocSize - tempMemBlockPos == RarMemBlock.size): realAllocSize //+ + tempMemBlockPos + + RarMemBlock.size; // Init freeList for (int i = 0, pos = _freeListPos; i < _freeList.Length; i++, pos += RarNode.SIZE) { _freeList[i] = new RarNode(_heap); _freeList[i].Address = pos; } // Init temp fields _tempRarNode = new RarNode(_heap); _tempRarMemBlock1 = new RarMemBlock(_heap); _tempRarMemBlock2 = new RarMemBlock(_heap); _tempRarMemBlock3 = new RarMemBlock(_heap); return true; } private void GlueFreeBlocks() { RarMemBlock s0 = _tempRarMemBlock1; s0.Address = _tempMemBlockPos; RarMemBlock p = _tempRarMemBlock2; RarMemBlock p1 = _tempRarMemBlock3; int i, k, sz; if (_loUnit != _hiUnit) { _heap[_loUnit] = 0; } for (i = 0, s0.SetPrev(s0), s0.SetNext(s0); i < N_INDEXES; i++) { while (_freeList[i].GetNext() != 0) { p.Address = RemoveNode(i); // =(RAR_MEM_BLK*)RemoveNode(i); p.InsertAt(s0); // p->insertAt(&s0); p.Stamp = 0xFFFF; // p->Stamp=0xFFFF; p.SetNu(_indx2Units[i]); // p->NU=Indx2Units[i]; } } for (p.Address = s0.GetNext(); p.Address != s0.Address; p.Address = p.GetNext()) { // while ((p1=MBPtr(p,p->NU))->Stamp == 0xFFFF && int(p->NU)+p1->NU // < 0x10000) // Bug fixed p1.Address = MbPtr(p.Address, p.GetNu()); while (p1.Stamp == 0xFFFF && p.GetNu() + p1.GetNu() < 0x10000) { p1.Remove(); p.SetNu(p.GetNu() + p1.GetNu()); // ->NU += p1->NU; p1.Address = MbPtr(p.Address, p.GetNu()); } } // while ((p=s0.next) != &s0) // Bug fixed p.Address = s0.GetNext(); while (p.Address != s0.Address) { for (p.Remove(), sz = p.GetNu(); sz > 128; sz -= 128, p.Address = MbPtr(p.Address, 128)) { InsertNode(p.Address, N_INDEXES - 1); } if (_indx2Units[i = _units2Indx[sz - 1]] != sz) { k = sz - _indx2Units[--i]; InsertNode(MbPtr(p.Address, sz - k), k - 1); } InsertNode(p.Address, i); p.Address = s0.GetNext(); } } private int AllocUnitsRare(int indx) { if (_glueCount == 0) { _glueCount = 255; GlueFreeBlocks(); if (_freeList[indx].GetNext() != 0) { return RemoveNode(indx); } } int i = indx; do { if (++i == N_INDEXES) { _glueCount--; i = U2B(_indx2Units[indx]); int j = FIXED_UNIT_SIZE * _indx2Units[indx]; if (_fakeUnitsStart - _pText > j) { _fakeUnitsStart -= j; _unitsStart -= i; return _unitsStart; } return (0); } } while (_freeList[i].GetNext() == 0); int retVal = RemoveNode(i); SplitBlock(retVal, i, indx); return retVal; } public virtual int AllocUnits(int nu) { int indx = _units2Indx[nu - 1]; if (_freeList[indx].GetNext() != 0) { return RemoveNode(indx); } int retVal = _loUnit; _loUnit += U2B(_indx2Units[indx]); if (_loUnit <= _hiUnit) { return retVal; } _loUnit -= U2B(_indx2Units[indx]); return AllocUnitsRare(indx); } public virtual int AllocContext() { if (_hiUnit != _loUnit) { return (_hiUnit -= UNIT_SIZE); } if (_freeList[0].GetNext() != 0) { return RemoveNode(0); } return AllocUnitsRare(0); } public virtual int ExpandUnits(int oldPtr, int oldNu) { int i0 = _units2Indx[oldNu - 1]; int i1 = _units2Indx[oldNu - 1 + 1]; if (i0 == i1) { return oldPtr; } int ptr = AllocUnits(oldNu + 1); if (ptr != 0) { // memcpy(ptr,OldPtr,U2B(OldNU)); Array.Copy(_heap, oldPtr, _heap, ptr, U2B(oldNu)); InsertNode(oldPtr, i0); } return ptr; } public virtual int ShrinkUnits(int oldPtr, int oldNu, int newNu) { // System.out.println("SubAllocator.shrinkUnits(" + OldPtr + ", " + // OldNU + ", " + NewNU + ")"); int i0 = _units2Indx[oldNu - 1]; int i1 = _units2Indx[newNu - 1]; if (i0 == i1) { return oldPtr; } if (_freeList[i1].GetNext() != 0) { int ptr = RemoveNode(i1); // memcpy(ptr,OldPtr,U2B(NewNU)); // for (int i = 0; i < U2B(NewNU); i++) { // heap[ptr + i] = heap[OldPtr + i]; // } Array.Copy(_heap, oldPtr, _heap, ptr, U2B(newNu)); InsertNode(oldPtr, i0); return ptr; } SplitBlock(oldPtr, i0, i1); return oldPtr; } public virtual void FreeUnits(int ptr, int oldNu) { InsertNode(ptr, _units2Indx[oldNu - 1]); } public virtual void DecPText(int dPText) { PText = PText - dPText; } public virtual void InitSubAllocator() { int i, k; Utility.Fill(_heap, _freeListPos, _freeListPos + SizeOfFreeList(), (byte)0); _pText = _heapStart; int size2 = FIXED_UNIT_SIZE * (_subAllocatorSize / 8 / FIXED_UNIT_SIZE * 7); int realSize2 = size2 / FIXED_UNIT_SIZE * UNIT_SIZE; int size1 = _subAllocatorSize - size2; int realSize1 = size1 / FIXED_UNIT_SIZE * UNIT_SIZE + size1 % FIXED_UNIT_SIZE; _hiUnit = _heapStart + _subAllocatorSize; _loUnit = _unitsStart = _heapStart + realSize1; _fakeUnitsStart = _heapStart + size1; _hiUnit = _loUnit + realSize2; for (i = 0, k = 1; i < N1; i++, k += 1) { _indx2Units[i] = k & 0xff; } for (k++; i < N1 + N2; i++, k += 2) { _indx2Units[i] = k & 0xff; }
[ " for (k++; i < N1 + N2 + N3; i++, k += 3)" ]
1,244
lcc
csharp
null
ccb175b81d17f841ce38c2caa311f192e142ac2649f954a2
# -*- coding: utf-8 -*- # Page model for Intel->Chargeback->Rates. import attr from cached_property import cached_property from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from wait_for import TimedOutError from widgetastic.utils import ParametrizedLocator from widgetastic.utils import ParametrizedString from widgetastic.widget import ParametrizedView from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import BootstrapSelect from widgetastic_patternfly import Button from widgetastic_patternfly import CandidateNotFound from widgetastic_patternfly import Dropdown from widgetastic_patternfly import Input from cfme.exceptions import ChargebackRateNotFound from cfme.intelligence.chargeback import ChargebackView from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils import ParamClassName from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.pretty import Pretty from cfme.utils.update import Updateable from cfme.utils.version import LOWEST from cfme.utils.version import VersionPicker from widgetastic_manageiq import Select from widgetastic_manageiq import Table class RatesView(ChargebackView): title = Text("#explorer_title_text") table = Table(".//div[@id='records_div' or @class='miq-data-table']/table") @property def in_rates(self): """Determine if in the rates part of chargeback, includes check of in_chargeback""" return( self.in_chargeback and self.toolbar.configuration.is_displayed and self.rates.is_opened) @property def is_displayed(self): expected_title = "{} Chargeback Rates".format(self.context['object'].RATE_TYPE) return ( self.in_rates and self.rates.tree.currently_selected == ['Rates', self.context['object'].RATE_TYPE] and self.title.text == expected_title ) @View.nested class toolbar(View): # noqa configuration = Dropdown('Configuration') class RatesDetailView(RatesView): # TODO add widget for rate details @property def is_displayed(self): return ( self.in_rates and self.rates.tree.currently_selected == ['Rates', self.context['object'].RATE_TYPE, self.context['object'].description] and self.title.text == '{} Chargeback Rate "{}"' .format(self.context['object'].RATE_TYPE, self.context['object'].description)) class AddComputeChargebackView(RatesView): EXPECTED_TITLE = 'Compute Chargeback Rates' title = Text('#explorer_title_text') description = Input(id='description') currency = VersionPicker({ LOWEST: Select(id='currency'), '5.10': BootstrapSelect(id='currency') }) @ParametrizedView.nested class fields(ParametrizedView): # noqa PARAMETERS = ('name',) ROOT = ParametrizedLocator('.//tr[./td[contains(normalize-space(.), {name|quote})]]') @cached_property def row_id(self): dom_attr = self.browser.get_attribute( 'id', './td/select[starts-with(@id, "per_time_")]', parent=self) return int(dom_attr.rsplit('_', 1)[-1]) @cached_property def sub_row_id(self): dom_attr = self.browser.get_attribute( 'id', './td/input[starts-with(@id, "fixed_rate_")]', parent=self) return int(dom_attr.rsplit('_', 1)[-1]) per_time = Select(id=ParametrizedString('per_time_{@row_id}')) per_unit = Select(id=ParametrizedString('per_unit_{@row_id}')) start = Input(id=ParametrizedString('start_{@row_id}_{@sub_row_id}')) finish = Input(id=ParametrizedString('finish_{@row_id}_{@sub_row_id}')) fixed_rate = Input(id=ParametrizedString('fixed_rate_{@row_id}_{@sub_row_id}')) variable_rate = Input(id=ParametrizedString('variable_rate_{@row_id}_{@sub_row_id}')) action_add = Button(title='Add a new tier') action_delete = Button(title='Remove the tier') add_button = Button(title='Add') cancel_button = Button(title='Cancel') @property def is_displayed(self): result = ( self.title.text == self.EXPECTED_TITLE and self.cancel_button.is_displayed and self.description.is_displayed and self.currency.is_displayed ) return result class EditComputeChargebackView(AddComputeChargebackView): save_button = Button('Save') reset_button = Button(title='Reset Changes') @property def is_displayed(self): return ( self.in_chargeback and self.title.text == 'Compute Chargeback Rate "{}"' .format(self.context['object'].description) and self.save_button.is_displayed ) class AddStorageChargebackView(AddComputeChargebackView): EXPECTED_TITLE = 'Storage Chargeback Rates' class EditStorageChargebackView(EditComputeChargebackView): @property def is_displayed(self): return ( self.in_chargeback and self.title.text == 'Storage Chargeback Rate "{}"' .format(self.context['object'].description) and self.save_button.is_displayed ) @attr.s class ComputeRate(Updateable, Pretty, BaseEntity): """This class represents a Compute Chargeback rate. Example: .. code-block:: python >>> import cfme.intelligence.chargeback.rates as rates >>> rate = rates.ComputeRate(description=desc, fields={'Used CPU': {'per_time': 'Hourly', 'variable_rate': '3'}, 'Used Disk I/O': {'per_time': 'Hourly', 'variable_rate': '2'}, 'Used Memory': {'per_time': 'Hourly', 'variable_rate': '2'}}) >>> rate.create() >>> rate.delete() Args: description: Rate description currency: Rate currency fields : Rate fields """ pretty_attrs = ['description'] _param_name = ParamClassName('description') RATE_TYPE = 'Compute' description = attr.ib() currency = attr.ib(default=None) fields = attr.ib(default=None) def __getitem__(self, name): return self.fields.get(name) @property def exists(self): try: navigate_to(self, 'Details') except (ChargebackRateNotFound, TimedOutError): return False else: return True def copy(self, *args, **kwargs): new_rate = self.parent.instantiate(*args, **kwargs) add_view = navigate_to(self, 'Copy') add_view.fill_with( { 'description': new_rate.description, 'currency': new_rate.currency, 'fields': new_rate.fields }, on_change=add_view.add_button, no_change=add_view.cancel_button ) return new_rate def update(self, updates): # Update a rate in UI view = navigate_to(self, 'Edit') view.fill_with(updates, on_change=view.save_button, no_change=view.cancel_button) view = self.create_view(navigator.get_class(self, 'Details').VIEW) view.flash.assert_no_error() def delete(self, cancel=False): """Delete a CB rate in the UI Args: cancel: boolean, whether to cancel the action on alert """ view = navigate_to(self, 'Details') view.toolbar.configuration.item_select('Remove from the VMDB', handle_alert=(not cancel)) view = self.create_view(navigator.get_class(self.parent, 'All').VIEW, wait=10) view.flash.assert_no_error() @attr.s class ComputeRateCollection(BaseCollection): ENTITY = ComputeRate RATE_TYPE = ENTITY.RATE_TYPE def create(self, description, currency=None, fields=None): """ Create a rate in the UI Args: description (str): name of the compute rate to create currency (str): - type of currency for the rate fields (dict): - nested dictionary listing the Rate Details Key => Rate Details Description Value => dict Key => Rate Details table column names Value => Value to input in the table """ rate = self.instantiate(description, currency, fields)
[ " view = navigate_to(self, 'Add')" ]
641
lcc
python
null
2edf15bcbfcd4fcf56e4a6731116895a5ed5bb7b70ee804d
#region LGPL License /* Axiom Graphics Engine Library Copyright (C) 2003-2010 Axiom Project Team This file is part of Axiom.RenderSystems.OpenGLES C# version developed by bostich. The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion LGPL License #region SVN Version Information // <file> // <license see="http://axiomengine.sf.net/wiki/index.php/license.txt"/> // <id value="$Id$"/> // </file> #endregion SVN Version Information #region Namespace Declarations using System; using Axiom.Graphics; using Axiom.Core; using OpenTK.Graphics.ES11; using OpenGL = OpenTK.Graphics.ES11.GL; using OpenGLOES = OpenTK.Graphics.ES11.GL.Oes; #endregion Namespace Declarations namespace Axiom.RenderSystems.OpenGLES { /// <summary> /// /// </summary> public class GLESHardwareIndexBuffer : HardwareIndexBuffer { const int MapBufferThreshold = 1024 * 32; private int _bufferId = 0; IntPtr _scratchPtr; bool _lockedToScratch; bool _scratchUploadOnUnlock; int _scratchOffset; int _scratchSize; public int BufferID { get { return _bufferId; } } public GLESHardwareIndexBuffer( HardwareBufferManager mgr, IndexType idxType, int numIndexes, BufferUsage usage, bool useShadowBuffer ) : base( idxType, numIndexes, usage, false, useShadowBuffer ) { if ( idxType == IndexType.Size32 ) { throw new AxiomException( "32 bit hardware buffers are not allowed in OpenGL ES." ); } if ( !useShadowBuffer ) { throw new AxiomException( "Only support with shadowBuffer" ); } OpenGL.GenBuffers( 1, ref _bufferId ); GLESConfig.GlCheckError( this ); if ( _bufferId == 0 ) { throw new AxiomException( "Cannot create GL index buffer" ); } OpenGL.BindBuffer( All.ElementArrayBuffer, _bufferId ); GLESConfig.GlCheckError( this ); OpenGL.BufferData( All.ElementArrayBuffer, new IntPtr( sizeInBytes ), IntPtr.Zero, GLESHardwareBufferManager.GetGLUsage( usage ) ); GLESConfig.GlCheckError( this ); } /// <summary> /// /// </summary> protected override void UnlockImpl() { if ( _lockedToScratch ) { if ( _scratchUploadOnUnlock ) { // have to write the data back to vertex buffer WriteData( _scratchOffset, _scratchSize, _scratchPtr, _scratchOffset == 0 && _scratchSize == sizeInBytes ); } // deallocate from scratch buffer ( (GLESHardwareBufferManager)HardwareBufferManager.Instance ).DeallocateScratch( _scratchPtr ); _lockedToScratch = false; } else { OpenGL.BindBuffer( All.ElementArrayBuffer, _bufferId ); if ( !OpenGLOES.UnmapBuffer( All.ElementArrayBuffer ) ) { throw new AxiomException( "Buffer data corrupted, please reload" ); } } isLocked = false; } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="locking"></param> /// <returns></returns> protected override IntPtr LockImpl( int offset, int length, BufferLocking locking ) { All access = 0; if ( isLocked ) { throw new AxiomException( "Invalid attempt to lock an index buffer that has already been locked" ); } IntPtr retPtr = IntPtr.Zero; if ( length < MapBufferThreshold ) { retPtr = ( (GLESHardwareBufferManager)HardwareBufferManager.Instance ).AllocateScratch( length ); if ( retPtr != IntPtr.Zero ) { _lockedToScratch = true; _scratchOffset = offset; _scratchSize = length; _scratchPtr = retPtr; _scratchUploadOnUnlock = ( locking != BufferLocking.ReadOnly ); if ( locking != BufferLocking.Discard ) { ReadData( offset, length, retPtr ); } } } else { throw new AxiomException( "Invalid Buffer lockSize" ); } if ( retPtr == IntPtr.Zero ) { OpenGL.BindBuffer( All.ElementArrayBuffer, _bufferId ); // Use glMapBuffer if ( locking == BufferLocking.Discard ) { OpenGL.BufferData( All.ElementArrayBuffer, new IntPtr( sizeInBytes ), IntPtr.Zero, GLESHardwareBufferManager.GetGLUsage( usage ) ); } if ( ( usage & BufferUsage.WriteOnly ) != 0 ) { access = All.WriteOnlyOes; } IntPtr pBuffer = OpenGLOES.MapBuffer( All.ElementArrayBuffer, access ); if ( pBuffer == IntPtr.Zero ) { throw new AxiomException( "Index Buffer: Out of memory" ); } unsafe { // return offset retPtr = (IntPtr)( (byte*)pBuffer + offset ); } _lockedToScratch = false; } isLocked = true; return retPtr; } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="dest"></param> public override void ReadData( int offset, int length, IntPtr dest ) { if ( useShadowBuffer ) { IntPtr srcData = shadowBuffer.Lock( offset, length, BufferLocking.ReadOnly ); Memory.Copy( srcData, dest, length ); shadowBuffer.Unlock(); } else { throw new AxiomException( "Reading hardware buffer is not supported." ); } } /// <summary> /// /// </summary> /// <param name="offset"></param> /// <param name="length"></param> /// <param name="src"></param> /// <param name="discardWholeBuffer"></param> public override void WriteData( int offset, int length, IntPtr src, bool discardWholeBuffer ) {
[ "\t\t\tOpenGL.BindBuffer( All.ElementArrayBuffer, _bufferId );" ]
782
lcc
csharp
null
8abd7abbc3616f319f05d25be5a410bd9fc2bb508b68e3cb
from enigma import eDVBResourceManager,\ eDVBFrontendParametersSatellite, eDVBFrontendParametersTerrestrial from Screens.ScanSetup import ScanSetup, buildTerTransponder from Screens.ServiceScan import ServiceScan from Screens.MessageBox import MessageBox from Plugins.Plugin import PluginDescriptor from Components.Sources.FrontendStatus import FrontendStatus from Components.ActionMap import ActionMap from Components.NimManager import nimmanager, getConfigSatlist from Components.config import config, ConfigSelection, getConfigListEntry from Components.TuneTest import Tuner from Tools.Transponder import getChannelNumber, channel2frequency class Satfinder(ScanSetup, ServiceScan): def __init__(self, session): self.initcomplete = False service = session and session.nav.getCurrentService() feinfo = service and service.frontendInfo() self.frontendData = feinfo and feinfo.getAll(True) del feinfo del service self.typeOfTuningEntry = None self.systemEntry = None self.satfinderTunerEntry = None self.satEntry = None self.typeOfInputEntry = None ScanSetup.__init__(self, session) self.setTitle(_("Satfinder")) self["introduction"].setText(_("Press OK to scan")) self["Frontend"] = FrontendStatus(frontend_source = lambda : self.frontend, update_interval = 100) self["actions"] = ActionMap(["SetupActions", "ColorActions"], { "save": self.keyGoScan, "ok": self.keyGoScan, "cancel": self.keyCancel, }, -3) self.initcomplete = True self.session.postScanService = self.session.nav.getCurrentlyPlayingServiceOrGroup() self.session.nav.stopService() self.onClose.append(self.__onClose) self.onShow.append(self.prepareFrontend) def openFrontend(self): res_mgr = eDVBResourceManager.getInstance() if res_mgr: self.raw_channel = res_mgr.allocateRawChannel(self.feid) if self.raw_channel: self.frontend = self.raw_channel.getFrontend() if self.frontend: return True return False def prepareFrontend(self): self.frontend = None if not self.openFrontend(): self.session.nav.stopService() if not self.openFrontend(): if self.session.pipshown: from Screens.InfoBar import InfoBar InfoBar.instance and hasattr(InfoBar.instance, "showPiP") and InfoBar.instance.showPiP() if not self.openFrontend(): self.frontend = None # in normal case this should not happen self.tuner = Tuner(self.frontend) self.retune(None) def __onClose(self): self.session.nav.playService(self.session.postScanService) def newConfig(self): cur = self["config"].getCurrent() if cur in (self.typeOfTuningEntry, self.systemEntry, self.typeOfInputEntry): self.createSetup() elif cur == self.satfinderTunerEntry: self.feid = int(self.satfinder_scan_nims.value) self.createSetup() self.prepareFrontend() if self.frontend == None: msg = _("Tuner not available.") if self.session.nav.RecordTimer.isRecording(): msg += _("\nRecording in progress.") self.session.open(MessageBox, msg, MessageBox.TYPE_ERROR) elif cur == self.satEntry: self.createSetup() else: self.retune(None) def createSetup(self): self.list = [] self.satfinderTunerEntry = getConfigListEntry(_("Tuner"), self.satfinder_scan_nims) self.list.append(self.satfinderTunerEntry) if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-S"): self.tuning_sat = self.scan_satselection[self.getSelectedSatIndex(self.feid)] self.satEntry = getConfigListEntry(_('Satellite'), self.tuning_sat) self.list.append(self.satEntry) self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type) if len(nimmanager.getTransponders(int(self.tuning_sat.value))) < 1: # Only offer 'predefined transponder' if some transponders exist self.tuning_type.value = "single_transponder" else: self.list.append(self.typeOfTuningEntry) nim = nimmanager.nim_slots[self.feid] if self.tuning_type.value == "single_transponder": if nim.isCompatible("DVB-S2"): self.systemEntry = getConfigListEntry(_('System'), self.scan_sat.system) self.list.append(self.systemEntry) else: # downgrade to dvb-s, in case a -s2 config was active self.scan_sat.system.value = eDVBFrontendParametersSatellite.System_DVB_S self.list.append(getConfigListEntry(_('Frequency'), self.scan_sat.frequency)) self.list.append(getConfigListEntry(_('Polarization'), self.scan_sat.polarization)) self.list.append(getConfigListEntry(_('Symbol rate'), self.scan_sat.symbolrate)) self.list.append(getConfigListEntry(_('Inversion'), self.scan_sat.inversion)) if self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S: self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec)) elif self.scan_sat.system.value == eDVBFrontendParametersSatellite.System_DVB_S2: self.list.append(getConfigListEntry(_("FEC"), self.scan_sat.fec_s2)) self.modulationEntry = getConfigListEntry(_('Modulation'), self.scan_sat.modulation) self.list.append(self.modulationEntry) self.list.append(getConfigListEntry(_('Roll-off'), self.scan_sat.rolloff)) self.list.append(getConfigListEntry(_('Pilot'), self.scan_sat.pilot)) elif self.tuning_type.value == "predefined_transponder": self.updatePreDefTransponders() self.list.append(getConfigListEntry(_("Transponder"), self.preDefTransponders)) elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-C"): self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type) if config.Nims[self.feid].cable.scan_type.value != "provider" or len(nimmanager.getTranspondersCable(int(self.satfinder_scan_nims.value))) < 1: # only show 'predefined transponder' if in provider mode and transponders exist self.tuning_type.value = "single_transponder" else: self.list.append(self.typeOfTuningEntry) if self.tuning_type.value == "single_transponder": self.list.append(getConfigListEntry(_("Frequency"), self.scan_cab.frequency)) self.list.append(getConfigListEntry(_("Inversion"), self.scan_cab.inversion)) self.list.append(getConfigListEntry(_("Symbol rate"), self.scan_cab.symbolrate)) self.list.append(getConfigListEntry(_("Modulation"), self.scan_cab.modulation)) self.list.append(getConfigListEntry(_("FEC"), self.scan_cab.fec)) elif self.tuning_type.value == "predefined_transponder": self.scan_nims.value = self.satfinder_scan_nims.value self.predefinedCabTranspondersList() self.list.append(getConfigListEntry(_('Transponder'), self.CableTransponders)) elif nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T"): self.typeOfTuningEntry = getConfigListEntry(_('Tune'), self.tuning_type) region = nimmanager.getTerrestrialDescription(int(self.satfinder_scan_nims.value)) if len(nimmanager.getTranspondersTerrestrial(region)) < 1: # Only offer 'predefined transponder' if some transponders exist self.tuning_type.value = "single_transponder" else: self.list.append(self.typeOfTuningEntry) if self.tuning_type.value == "single_transponder": if nimmanager.nim_slots[int(self.satfinder_scan_nims.value)].isCompatible("DVB-T2"): self.systemEntryTerr = getConfigListEntry(_('System'), self.scan_ter.system) self.list.append(self.systemEntryTerr) else: self.scan_ter.system.value = eDVBFrontendParametersTerrestrial.System_DVB_T self.typeOfInputEntry = getConfigListEntry(_("Use frequency or channel"), self.scan_input_as) if self.ter_channel_input: self.list.append(self.typeOfInputEntry) else: self.scan_input_as.value = self.scan_input_as.choices[0] if self.ter_channel_input and self.scan_input_as.value == "channel": channel = getChannelNumber(self.scan_ter.frequency.value*1000, self.ter_tnumber) if channel: self.scan_ter.channel.value = int(channel.replace("+","").replace("-","")) self.list.append(getConfigListEntry(_("Channel"), self.scan_ter.channel)) else: prev_val = self.scan_ter.frequency.value self.scan_ter.frequency.value = channel2frequency(self.scan_ter.channel.value, self.ter_tnumber)/1000 if self.scan_ter.frequency.value == 474000: self.scan_ter.frequency.value = prev_val self.list.append(getConfigListEntry(_("Frequency"), self.scan_ter.frequency)) self.list.append(getConfigListEntry(_("Inversion"), self.scan_ter.inversion)) self.list.append(getConfigListEntry(_("Bandwidth"), self.scan_ter.bandwidth)) self.list.append(getConfigListEntry(_("Code rate HP"), self.scan_ter.fechigh)) self.list.append(getConfigListEntry(_("Code rate LP"), self.scan_ter.feclow)) self.list.append(getConfigListEntry(_("Modulation"), self.scan_ter.modulation)) self.list.append(getConfigListEntry(_("Transmission mode"), self.scan_ter.transmission)) self.list.append(getConfigListEntry(_("Guard interval"), self.scan_ter.guard)) self.list.append(getConfigListEntry(_("Hierarchy info"), self.scan_ter.hierarchy)) if self.scan_ter.system.value == eDVBFrontendParametersTerrestrial.System_DVB_T2: self.list.append(getConfigListEntry(_('PLP ID'), self.scan_ter.plp_id)) elif self.tuning_type.value == "predefined_transponder": self.scan_nims.value = self.satfinder_scan_nims.value self.predefinedTerrTranspondersList() self.list.append(getConfigListEntry(_('Transponder'), self.TerrestrialTransponders)) self.retune(None) self["config"].list = self.list self["config"].l.setList(self.list) def createConfig(self, foo): self.tuning_type = ConfigSelection(default = "predefined_transponder", choices = [("single_transponder", _("User defined transponder")), ("predefined_transponder", _("Predefined transponder"))]) self.orbital_position = 192 if self.frontendData and self.frontendData.has_key('orbital_position'): self.orbital_position = self.frontendData['orbital_position'] ScanSetup.createConfig(self, self.frontendData) for x in (self.scan_sat.frequency, self.scan_sat.inversion, self.scan_sat.symbolrate, self.scan_sat.polarization, self.scan_sat.fec, self.scan_sat.pilot, self.scan_sat.fec_s2, self.scan_sat.fec, self.scan_sat.modulation, self.scan_sat.rolloff, self.scan_sat.system, self.scan_ter.channel, self.scan_ter.frequency, self.scan_ter.inversion, self.scan_ter.bandwidth, self.scan_ter.fechigh, self.scan_ter.feclow, self.scan_ter.modulation, self.scan_ter.transmission, self.scan_ter.guard, self.scan_ter.hierarchy, self.scan_ter.plp_id, self.scan_cab.frequency, self.scan_cab.inversion, self.scan_cab.symbolrate, self.scan_cab.modulation, self.scan_cab.fec): x.addNotifier(self.retune, initial_call = False) satfinder_nim_list = [] for n in nimmanager.nim_slots: if not (n.isCompatible("DVB-S") or n.isCompatible("DVB-T") or n.isCompatible("DVB-C")): continue if n.config_mode in ("loopthrough", "satposdepends", "nothing"): continue if n.isCompatible("DVB-S") and n.config_mode == "advanced" and len(nimmanager.getSatListForNim(n.slot)) < 1: continue satfinder_nim_list.append((str(n.slot), n.friendly_full_description)) self.satfinder_scan_nims = ConfigSelection(choices = satfinder_nim_list) if self.frontendData is not None and len(satfinder_nim_list) > 0: # open the plugin with the currently active NIM as default self.satfinder_scan_nims.setValue(str(self.frontendData.get("tuner_number", satfinder_nim_list[0][0])))
[ "\t\tself.feid = int(self.satfinder_scan_nims.value)" ]
673
lcc
python
null
f8ded3af8ef3545db8175306e099fcfdecc9a38e3633b747
/* Copyright (c) 2007-2014 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ 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. 0MQ 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, see <http://www.gnu.org/licenses/>. */ package zmq; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import zmq.TcpAddress.TcpAddressMask; public class Options { // High-water marks for message pipes. int sendHwm; int recvHwm; // I/O thread affinity. long affinity; // Socket identity byte identitySize; byte[] identity; // [256]; // Last socket endpoint resolved URI String lastEndpoint; // Maximum tranfer rate [kb/s]. Default 100kb/s. int rate; // Reliability time interval [ms]. Default 10 seconds. int recoveryIvl; // Sets the time-to-live field in every multicast packet sent. int multicastHops; // SO_SNDBUF and SO_RCVBUF to be passed to underlying transport sockets. int sndbuf; int rcvbuf; // Socket type. int type; // Linger time, in milliseconds. int linger; // Minimum interval between attempts to reconnect, in milliseconds. // Default 100ms int reconnectIvl; // Maximum interval between attempts to reconnect, in milliseconds. // Default 0 (unused) int reconnectIvlMax; // Maximum backlog for pending connections. int backlog; // Maximal size of message to handle. long maxMsgSize; // The timeout for send/recv operations for this socket. int recvTimeout; int sendTimeout; // If 1, indicates the use of IPv4 sockets only, it will not be // possible to communicate with IPv6-only hosts. If 0, the socket can // connect to and accept connections from both IPv4 and IPv6 hosts. int ipv4only; // If 1, connecting pipes are not attached immediately, meaning a send() // on a socket with only connecting pipes would block int delayAttachOnConnect; // If true, session reads all the pending messages from the pipe and // sends them to the network when socket is closed. boolean delayOnClose; // If true, socket reads all the messages from the pipe and delivers // them to the user when the peer terminates. boolean delayOnDisconnect; // If 1, (X)SUB socket should filter the messages. If 0, it should not. boolean filter; // If true, the identity message is forwarded to the socket. boolean recvIdentity; // TCP keep-alive settings. // Defaults to -1 = do not change socket options int tcpKeepAlive; int tcpKeepAliveCnt; int tcpKeepAliveIdle; int tcpKeepAliveIntvl; // TCP accept() filters //typedef std::vector <tcp_address_mask_t> tcp_accept_filters_t; final List<TcpAddress.TcpAddressMask> tcpAcceptFilters; // ID of the socket. int socketId; Class<? extends DecoderBase> decoder; Class<? extends EncoderBase> encoder; MsgAllocator msgAllocator; public Options() { sendHwm = 1000; recvHwm = 1000; affinity = 0; identitySize = 0; rate = 100; recoveryIvl = 10000; multicastHops = 1; sndbuf = 0; rcvbuf = 0; type = -1; linger = -1; reconnectIvl = 100; reconnectIvlMax = 0; backlog = 100; maxMsgSize = -1; recvTimeout = -1; sendTimeout = -1; ipv4only = 1; delayAttachOnConnect = 0; delayOnClose = true; delayOnDisconnect = true; filter = false; recvIdentity = false; tcpKeepAlive = -1; tcpKeepAliveCnt = -1; tcpKeepAliveIdle = -1; tcpKeepAliveIntvl = -1; socketId = 0; identity = null; tcpAcceptFilters = new ArrayList<TcpAddress.TcpAddressMask>(); decoder = null; encoder = null; msgAllocator = null; } @SuppressWarnings("unchecked") public void setSocketOpt(int option, Object optval) { switch (option) { case ZMQ.ZMQ_SNDHWM: sendHwm = (Integer) optval; if (sendHwm < 0) { throw new IllegalArgumentException("sendHwm " + optval); } return; case ZMQ.ZMQ_RCVHWM: recvHwm = (Integer) optval; if (recvHwm < 0) { throw new IllegalArgumentException("recvHwm " + optval); } return; case ZMQ.ZMQ_AFFINITY: affinity = (Long) optval; return; case ZMQ.ZMQ_IDENTITY: byte[] val; if (optval instanceof String) { val = ((String) optval).getBytes(ZMQ.CHARSET); } else if (optval instanceof byte[]) { val = (byte[]) optval; } else { throw new IllegalArgumentException("identity " + optval); } if (val == null || val.length > 255) { throw new IllegalArgumentException("identity must not be null or less than 255 " + optval); } identity = Arrays.copyOf(val, val.length); identitySize = (byte) identity.length; return; case ZMQ.ZMQ_RATE: rate = (Integer) optval; return; case ZMQ.ZMQ_RECOVERY_IVL: recoveryIvl = (Integer) optval; return; case ZMQ.ZMQ_SNDBUF: sndbuf = (Integer) optval; return; case ZMQ.ZMQ_RCVBUF: rcvbuf = (Integer) optval; return; case ZMQ.ZMQ_LINGER: linger = (Integer) optval; return; case ZMQ.ZMQ_RECONNECT_IVL: reconnectIvl = (Integer) optval; if (reconnectIvl < -1) { throw new IllegalArgumentException("reconnectIvl " + optval); } return; case ZMQ.ZMQ_RECONNECT_IVL_MAX: reconnectIvlMax = (Integer) optval; if (reconnectIvlMax < 0) { throw new IllegalArgumentException("reconnectIvlMax " + optval); } return; case ZMQ.ZMQ_BACKLOG: backlog = (Integer) optval; return; case ZMQ.ZMQ_MAXMSGSIZE: maxMsgSize = (Long) optval; return; case ZMQ.ZMQ_MULTICAST_HOPS: multicastHops = (Integer) optval; return; case ZMQ.ZMQ_RCVTIMEO: recvTimeout = (Integer) optval; return; case ZMQ.ZMQ_SNDTIMEO: sendTimeout = (Integer) optval; return; case ZMQ.ZMQ_IPV4ONLY: ipv4only = (Integer) optval; if (ipv4only != 0 && ipv4only != 1) { throw new IllegalArgumentException("ipv4only only accepts 0 or 1 " + optval); } return; case ZMQ.ZMQ_TCP_KEEPALIVE: tcpKeepAlive = (Integer) optval; if (tcpKeepAlive != -1 && tcpKeepAlive != 0 && tcpKeepAlive != 1) { throw new IllegalArgumentException("tcpKeepAlive only accepts one of -1,0,1 " + optval); } return; case ZMQ.ZMQ_DELAY_ATTACH_ON_CONNECT: delayAttachOnConnect = (Integer) optval; if (delayAttachOnConnect != 0 && delayAttachOnConnect != 1) { throw new IllegalArgumentException("delayAttachOnConnect only accept 0 or 1 " + optval); } return; case ZMQ.ZMQ_TCP_KEEPALIVE_CNT: case ZMQ.ZMQ_TCP_KEEPALIVE_IDLE: case ZMQ.ZMQ_TCP_KEEPALIVE_INTVL: // not supported return; case ZMQ.ZMQ_TCP_ACCEPT_FILTER: String filterStr = (String) optval; if (filterStr == null) { tcpAcceptFilters.clear(); }
[ " else if (filterStr.length() == 0 || filterStr.length() > 255) {" ]
931
lcc
java
null
e183058d346d8baf870f97d2f9f4a343610cbd294e8bc9ff
using System; using System.Collections; using System.Security.Cryptography; using System.Net; using System.Text; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf.intern; using iTextSharp.text.pdf.interfaces; using System.util; using System.util.zlib; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Cms; using Org.BouncyCastle.X509; /* * $Id: PdfReader.cs,v 1.28 2007/02/09 15:34:38 psoares33 Exp $ * $Name: $ * * Copyright 2001, 2002 Paulo Soares * * The contents of this file are subject to the Mozilla Public License Version 1.1 * (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the License. * * The Original Code is 'iText, a free JAVA-PDF library'. * * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. * All Rights Reserved. * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. * * Contributor(s): all the names of the contributors are added in the source code * where applicable. * * Alternatively, the contents of this file may be used under the terms of the * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * provisions of LGPL are applicable instead of those above. If you wish to * allow use of your version of this file only under the terms of the LGPL * License and not to allow others to use your version of this file under * the MPL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the LGPL. * If you do not delete the provisions above, a recipient may use your version * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. * * This library is free software; you can redistribute it and/or modify it * under the terms of the MPL as stated above or under the terms of the GNU * Library General Public License as published by the Free Software Foundation; * either version 2 of the License, or any later version. * * This library 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. * * If you didn't download this code from the following link, you should check if * you aren't using an obsolete version: * http://www.lowagie.com/iText/ */ namespace iTextSharp.text.pdf { /** Reads a PDF document. * @author Paulo Soares (psoares@consiste.pt) * @author Kazuya Ujihara */ public class PdfReader : IPdfViewerPreferences { static PdfName[] pageInhCandidates = { PdfName.MEDIABOX, PdfName.ROTATE, PdfName.RESOURCES, PdfName.CROPBOX }; static byte[] endstream = PdfEncodings.ConvertToBytes("endstream", null); static byte[] endobj = PdfEncodings.ConvertToBytes("endobj", null); protected internal PRTokeniser tokens; // Each xref pair is a position // type 0 -> -1, 0 // type 1 -> offset, 0 // type 2 -> index, obj num protected internal int[] xref; protected internal Hashtable objStmMark; protected internal IntHashtable objStmToOffset; protected internal bool newXrefType; private ArrayList xrefObj; PdfDictionary rootPages; protected internal PdfDictionary trailer; //protected internal ArrayList pages; protected internal PdfDictionary catalog; protected internal PageRefs pageRefs; protected internal PRAcroForm acroForm = null; protected internal bool acroFormParsed = false; protected internal ArrayList pageInh; protected internal bool encrypted = false; protected internal bool rebuilt = false; protected internal int freeXref; protected internal bool tampered = false; protected internal int lastXref; protected internal int eofPos; protected internal char pdfVersion; protected internal PdfEncryption decrypt; protected internal byte[] password = null; //added by ujihara for decryption protected ICipherParameters certificateKey = null; //added by Aiken Sam for certificate decryption protected X509Certificate certificate = null; //added by Aiken Sam for certificate decryption protected internal ArrayList strings = new ArrayList(); protected internal bool sharedStreams = true; protected internal bool consolidateNamedDestinations = false; protected internal int rValue; protected internal int pValue; private int objNum; private int objGen; private int fileLength; private bool hybridXref; private int lastXrefPartial = -1; private bool partial; private PRIndirectReference cryptoRef; private PdfViewerPreferencesImp viewerPreferences = new PdfViewerPreferencesImp(); /** * Holds value of property appendable. */ private bool appendable; protected internal PdfReader() { } /** Reads and parses a PDF document. * @param filename the file name of the document * @throws IOException on error */ public PdfReader(String filename) : this(filename, null) { } /** Reads and parses a PDF document. * @param filename the file name of the document * @param ownerPassword the password to read the document * @throws IOException on error */ public PdfReader(String filename, byte[] ownerPassword) { password = ownerPassword; tokens = new PRTokeniser(filename); ReadPdf(); } /** Reads and parses a PDF document. * @param pdfIn the byte array with the document * @throws IOException on error */ public PdfReader(byte[] pdfIn) : this(pdfIn, null) { } /** Reads and parses a PDF document. * @param pdfIn the byte array with the document * @param ownerPassword the password to read the document * @throws IOException on error */ public PdfReader(byte[] pdfIn, byte[] ownerPassword) { password = ownerPassword; tokens = new PRTokeniser(pdfIn); ReadPdf(); } /** Reads and parses a PDF document. * @param filename the file name of the document * @param certificate the certificate to read the document * @param certificateKey the private key of the certificate * @param certificateKeyProvider the security provider for certificateKey * @throws IOException on error */ public PdfReader(String filename, X509Certificate certificate, ICipherParameters certificateKey) { this.certificate = certificate; this.certificateKey = certificateKey; tokens = new PRTokeniser(filename); ReadPdf(); } /** Reads and parses a PDF document. * @param url the Uri of the document * @throws IOException on error */ public PdfReader(Uri url) : this(url, null) { } /** Reads and parses a PDF document. * @param url the Uri of the document * @param ownerPassword the password to read the document * @throws IOException on error */ public PdfReader(Uri url, byte[] ownerPassword) { password = ownerPassword; tokens = new PRTokeniser(new RandomAccessFileOrArray(url)); ReadPdf(); } /** * Reads and parses a PDF document. * @param is the <CODE>InputStream</CODE> containing the document. The stream is read to the * end but is not closed * @param ownerPassword the password to read the document * @throws IOException on error */ public PdfReader(Stream isp, byte[] ownerPassword) { password = ownerPassword; tokens = new PRTokeniser(new RandomAccessFileOrArray(isp)); ReadPdf(); } /** * Reads and parses a PDF document. * @param isp the <CODE>InputStream</CODE> containing the document. The stream is read to the * end but is not closed * @throws IOException on error */ public PdfReader(Stream isp) : this(isp, null) { } /** * Reads and parses a pdf document. Contrary to the other constructors only the xref is read * into memory. The reader is said to be working in "partial" mode as only parts of the pdf * are read as needed. The pdf is left open but may be closed at any time with * <CODE>PdfReader.Close()</CODE>, reopen is automatic. * @param raf the document location * @param ownerPassword the password or <CODE>null</CODE> for no password * @throws IOException on error */ public PdfReader(RandomAccessFileOrArray raf, byte[] ownerPassword) { password = ownerPassword; partial = true; tokens = new PRTokeniser(raf); ReadPdfPartial(); } /** Creates an independent duplicate. * @param reader the <CODE>PdfReader</CODE> to duplicate */ public PdfReader(PdfReader reader) { this.appendable = reader.appendable; this.consolidateNamedDestinations = reader.consolidateNamedDestinations; this.encrypted = reader.encrypted; this.rebuilt = reader.rebuilt; this.sharedStreams = reader.sharedStreams; this.tampered = reader.tampered; this.password = reader.password; this.pdfVersion = reader.pdfVersion; this.eofPos = reader.eofPos; this.freeXref = reader.freeXref; this.lastXref = reader.lastXref; this.tokens = new PRTokeniser(reader.tokens.SafeFile); if (reader.decrypt != null) this.decrypt = new PdfEncryption(reader.decrypt); this.pValue = reader.pValue; this.rValue = reader.rValue; this.xrefObj = new ArrayList(reader.xrefObj); for (int k = 0; k < reader.xrefObj.Count; ++k) { this.xrefObj[k] = DuplicatePdfObject((PdfObject)reader.xrefObj[k], this); } this.pageRefs = new PageRefs(reader.pageRefs, this); this.trailer = (PdfDictionary)DuplicatePdfObject(reader.trailer, this); this.catalog = (PdfDictionary)GetPdfObject(trailer.Get(PdfName.ROOT)); this.rootPages = (PdfDictionary)GetPdfObject(catalog.Get(PdfName.PAGES)); this.fileLength = reader.fileLength; this.partial = reader.partial; this.hybridXref = reader.hybridXref; this.objStmToOffset = reader.objStmToOffset; this.xref = reader.xref; this.cryptoRef = (PRIndirectReference)DuplicatePdfObject(reader.cryptoRef, this); } /** Gets a new file instance of the original PDF * document. * @return a new file instance of the original PDF document */ public RandomAccessFileOrArray SafeFile { get { return tokens.SafeFile; } } protected internal PdfReaderInstance GetPdfReaderInstance(PdfWriter writer) { return new PdfReaderInstance(this, writer); } /** Gets the number of pages in the document. * @return the number of pages in the document */ public int NumberOfPages { get { return pageRefs.Size; } } /** Returns the document's catalog. This dictionary is not a copy, * any changes will be reflected in the catalog. * @return the document's catalog */ public PdfDictionary Catalog { get { return catalog; } } /** Returns the document's acroform, if it has one. * @return the document's acroform */ public PRAcroForm AcroForm { get { if (!acroFormParsed) { acroFormParsed = true; PdfObject form = catalog.Get(PdfName.ACROFORM); if (form != null) { try { acroForm = new PRAcroForm(this); acroForm.ReadAcroForm((PdfDictionary)GetPdfObject(form)); } catch { acroForm = null; } } } return acroForm; } } /** * Gets the page rotation. This value can be 0, 90, 180 or 270. * @param index the page number. The first page is 1 * @return the page rotation */ public int GetPageRotation(int index) { return GetPageRotation(pageRefs.GetPageNRelease(index)); } internal int GetPageRotation(PdfDictionary page) { PdfNumber rotate = (PdfNumber)GetPdfObject(page.Get(PdfName.ROTATE)); if (rotate == null) return 0; else { int n = rotate.IntValue; n %= 360; return n < 0 ? n + 360 : n; } } /** Gets the page size, taking rotation into account. This * is a <CODE>Rectangle</CODE> with the value of the /MediaBox and the /Rotate key. * @param index the page number. The first page is 1 * @return a <CODE>Rectangle</CODE> */ public Rectangle GetPageSizeWithRotation(int index) { return GetPageSizeWithRotation(pageRefs.GetPageNRelease(index)); } /** * Gets the rotated page from a page dictionary. * @param page the page dictionary * @return the rotated page */ public Rectangle GetPageSizeWithRotation(PdfDictionary page) { Rectangle rect = GetPageSize(page); int rotation = GetPageRotation(page); while (rotation > 0) { rect = rect.Rotate(); rotation -= 90; } return rect; } /** Gets the page size without taking rotation into account. This * is the value of the /MediaBox key. * @param index the page number. The first page is 1 * @return the page size */ public Rectangle GetPageSize(int index) { return GetPageSize(pageRefs.GetPageNRelease(index)); } /** * Gets the page from a page dictionary * @param page the page dictionary * @return the page */ public Rectangle GetPageSize(PdfDictionary page) { PdfArray mediaBox = (PdfArray)GetPdfObject(page.Get(PdfName.MEDIABOX)); return GetNormalizedRectangle(mediaBox); } /** Gets the crop box without taking rotation into account. This * is the value of the /CropBox key. The crop box is the part * of the document to be displayed or printed. It usually is the same * as the media box but may be smaller. If the page doesn't have a crop * box the page size will be returned. * @param index the page number. The first page is 1 * @return the crop box */ public Rectangle GetCropBox(int index) { PdfDictionary page = pageRefs.GetPageNRelease(index); PdfArray cropBox = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.CROPBOX)); if (cropBox == null) return GetPageSize(page); return GetNormalizedRectangle(cropBox); } /** Gets the box size. Allowed names are: "crop", "trim", "art", "bleed" and "media". * @param index the page number. The first page is 1 * @param boxName the box name * @return the box rectangle or null */ public Rectangle GetBoxSize(int index, String boxName) { PdfDictionary page = pageRefs.GetPageNRelease(index); PdfArray box = null; if (boxName.Equals("trim")) box = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.TRIMBOX)); else if (boxName.Equals("art")) box = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.ARTBOX)); else if (boxName.Equals("bleed")) box = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.BLEEDBOX)); else if (boxName.Equals("crop")) box = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.CROPBOX)); else if (boxName.Equals("media")) box = (PdfArray)GetPdfObjectRelease(page.Get(PdfName.MEDIABOX)); if (box == null) return null; return GetNormalizedRectangle(box); } /** Returns the content of the document information dictionary as a <CODE>Hashtable</CODE> * of <CODE>String</CODE>. * @return content of the document information dictionary */ public Hashtable Info { get { Hashtable map = new Hashtable(); PdfDictionary info = (PdfDictionary)GetPdfObject(trailer.Get(PdfName.INFO)); if (info == null) return map; foreach (PdfName key in info.Keys) { PdfObject obj = GetPdfObject(info.Get(key)); if (obj == null) continue; String value = obj.ToString(); switch (obj.Type) { case PdfObject.STRING: { value = ((PdfString)obj).ToUnicodeString(); break; } case PdfObject.NAME: { value = PdfName.DecodeName(value); break; } } map[PdfName.DecodeName(key.ToString())] = value; } return map; } } /** Normalizes a <CODE>Rectangle</CODE> so that llx and lly are smaller than urx and ury. * @param box the original rectangle * @return a normalized <CODE>Rectangle</CODE> */ public static Rectangle GetNormalizedRectangle(PdfArray box) { ArrayList rect = box.ArrayList; float llx = ((PdfNumber)rect[0]).FloatValue; float lly = ((PdfNumber)rect[1]).FloatValue; float urx = ((PdfNumber)rect[2]).FloatValue; float ury = ((PdfNumber)rect[3]).FloatValue; return new Rectangle(Math.Min(llx, urx), Math.Min(lly, ury), Math.Max(llx, urx), Math.Max(lly, ury)); } protected internal virtual void ReadPdf() { try { fileLength = tokens.File.Length; pdfVersion = tokens.CheckPdfHeader(); try { ReadXref(); } catch (Exception e) { try { rebuilt = true; RebuildXref(); lastXref = -1; } catch (Exception ne) { throw new IOException("Rebuild failed: " + ne.Message + "; Original message: " + e.Message); } } try { ReadDocObj(); } catch (Exception ne) { if (rebuilt) throw ne; rebuilt = true; encrypted = false; RebuildXref(); lastXref = -1; ReadDocObj(); } strings.Clear(); ReadPages(); EliminateSharedStreams(); RemoveUnusedObjects(); } finally { try { tokens.Close(); } catch { // empty on purpose } } } protected internal void ReadPdfPartial() { try { fileLength = tokens.File.Length; pdfVersion = tokens.CheckPdfHeader(); try { ReadXref(); } catch (Exception e) { try { rebuilt = true; RebuildXref(); lastXref = -1; } catch (Exception ne) { throw new IOException("Rebuild failed: " + ne.Message + "; Original message: " + e.Message); } } ReadDocObjPartial(); ReadPages(); } catch (IOException e) { try{tokens.Close();}catch{} throw e; } } private bool EqualsArray(byte[] ar1, byte[] ar2, int size) { for (int k = 0; k < size; ++k) { if (ar1[k] != ar2[k]) return false; } return true; } /** * @throws IOException */ private void ReadDecryptedDocObj() { if (encrypted) return; PdfObject encDic = trailer.Get(PdfName.ENCRYPT); if (encDic == null || encDic.ToString().Equals("null")) return; byte[] encryptionKey = null; encrypted = true; PdfDictionary enc = (PdfDictionary)GetPdfObject(encDic); String s; PdfObject o; PdfArray documentIDs = (PdfArray)GetPdfObject(trailer.Get(PdfName.ID)); byte[] documentID = null; if (documentIDs != null) { o = (PdfObject)documentIDs.ArrayList[0]; strings.Remove(o); s = o.ToString(); documentID = DocWriter.GetISOBytes(s); if (documentIDs.Size > 1) strings.Remove(documentIDs.ArrayList[1]); } byte[] uValue = null; byte[] oValue = null; int cryptoMode = PdfWriter.ENCRYPTION_RC4_40; int lengthValue = 0; PdfObject filter = GetPdfObjectRelease(enc.Get(PdfName.FILTER)); if (filter.Equals(PdfName.STANDARD)) { s = enc.Get(PdfName.U).ToString(); strings.Remove(enc.Get(PdfName.U)); uValue = DocWriter.GetISOBytes(s); s = enc.Get(PdfName.O).ToString(); strings.Remove(enc.Get(PdfName.O)); oValue = DocWriter.GetISOBytes(s); o = enc.Get(PdfName.R); if (!o.IsNumber()) throw new IOException("Illegal R value."); rValue = ((PdfNumber)o).IntValue; if (rValue != 2 && rValue != 3 && rValue != 4) throw new IOException("Unknown encryption type (" + rValue + ")"); o = enc.Get(PdfName.P); if (!o.IsNumber()) throw new IOException("Illegal P value."); pValue = ((PdfNumber)o).IntValue; if ( rValue == 3 ){ o = enc.Get(PdfName.LENGTH); if (!o.IsNumber()) throw new IOException("Illegal Length value."); lengthValue = ((PdfNumber)o).IntValue; if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0) throw new IOException("Illegal Length value."); cryptoMode = PdfWriter.ENCRYPTION_RC4_128; } else if (rValue == 4) { lengthValue = 128; PdfDictionary dic = (PdfDictionary)enc.Get(PdfName.CF); if (dic == null) throw new IOException("/CF not found (encryption)"); dic = (PdfDictionary)dic.Get(PdfName.STDCF); if (dic == null) throw new IOException("/StdCF not found (encryption)"); if (PdfName.V2.Equals(dic.Get(PdfName.CFM))) cryptoMode = PdfWriter.ENCRYPTION_RC4_128; else if (PdfName.AESV2.Equals(dic.Get(PdfName.CFM))) cryptoMode = PdfWriter.ENCRYPTION_AES_128; else throw new IOException("No compatible encryption found"); PdfObject em = enc.Get(PdfName.ENCRYPTMETADATA); if (em != null && em.ToString().Equals("false")) cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA; } else { cryptoMode = PdfWriter.ENCRYPTION_RC4_40; } } else if (filter.Equals(PdfName.PUBSEC)) { bool foundRecipient = false; byte[] envelopedData = null; PdfArray recipients = null; o = enc.Get(PdfName.V); if (!o.IsNumber()) throw new IOException("Illegal V value."); int vValue = ((PdfNumber)o).IntValue; if (vValue != 1 && vValue != 2 && vValue != 4) throw new IOException("Unknown encryption type V = " + rValue); if ( vValue == 2 ){ o = enc.Get(PdfName.LENGTH); if (!o.IsNumber()) throw new IOException("Illegal Length value."); lengthValue = ((PdfNumber)o).IntValue; if (lengthValue > 128 || lengthValue < 40 || lengthValue % 8 != 0) throw new IOException("Illegal Length value."); cryptoMode = PdfWriter.ENCRYPTION_RC4_128; recipients = (PdfArray)enc.Get(PdfName.RECIPIENTS); } else if (vValue == 4) { PdfDictionary dic = (PdfDictionary)enc.Get(PdfName.CF); if (dic == null) throw new IOException("/CF not found (encryption)"); dic = (PdfDictionary)dic.Get(PdfName.DEFAULTCRYPTFILER); if (dic == null) throw new IOException("/DefaultCryptFilter not found (encryption)"); if (PdfName.V2.Equals(dic.Get(PdfName.CFM))) { cryptoMode = PdfWriter.ENCRYPTION_RC4_128; lengthValue = 128; } else if (PdfName.AESV2.Equals(dic.Get(PdfName.CFM))) { cryptoMode = PdfWriter.ENCRYPTION_AES_128; lengthValue = 128; } else throw new IOException("No compatible encryption found"); PdfObject em = dic.Get(PdfName.ENCRYPTMETADATA); if (em != null && em.ToString().Equals("false")) cryptoMode |= PdfWriter.DO_NOT_ENCRYPT_METADATA; recipients = (PdfArray)dic.Get(PdfName.RECIPIENTS); } else { cryptoMode = PdfWriter.ENCRYPTION_RC4_40; lengthValue = 40; recipients = (PdfArray)enc.Get(PdfName.RECIPIENTS); } for (int i = 0; i<recipients.Size; i++) { PdfObject recipient = (PdfObject)recipients.ArrayList[i]; strings.Remove(recipient); CmsEnvelopedData data = null; data = new CmsEnvelopedData(recipient.GetBytes()); foreach (RecipientInformation recipientInfo in data.GetRecipientInfos().GetRecipients()) { if (recipientInfo.RecipientID.Match(certificate) && !foundRecipient) { envelopedData = recipientInfo.GetContent(certificateKey); foundRecipient = true; } } } if(!foundRecipient || envelopedData == null) { throw new IOException("Bad certificate and key."); } SHA1 sh = new SHA1CryptoServiceProvider(); sh.TransformBlock(envelopedData, 0, 20, envelopedData, 0); for (int i=0; i<recipients.Size; i++) { byte[] encodedRecipient = ((PdfObject)recipients.ArrayList[i]).GetBytes(); sh.TransformBlock(encodedRecipient, 0, encodedRecipient.Length, encodedRecipient, 0); } if ((cryptoMode & PdfWriter.DO_NOT_ENCRYPT_METADATA) != 0) sh.TransformBlock(PdfEncryption.metadataPad, 0, PdfEncryption.metadataPad.Length, PdfEncryption.metadataPad, 0); sh.TransformFinalBlock(envelopedData, 0, 0); encryptionKey = sh.Hash; } decrypt = new PdfEncryption(); decrypt.SetCryptoMode(cryptoMode, lengthValue); if (filter.Equals(PdfName.STANDARD)) { //check by user password decrypt.SetupByUserPassword(documentID, password, oValue, pValue); if (!EqualsArray(uValue, decrypt.userKey, (rValue == 3 || rValue == 4) ? 16 : 32)) { //check by owner password decrypt.SetupByOwnerPassword(documentID, password, uValue, oValue, pValue); if (!EqualsArray(uValue, decrypt.userKey, (rValue == 3 || rValue == 4) ? 16 : 32)) { throw new IOException("Bad user password"); } } } else if (filter.Equals(PdfName.PUBSEC)) { decrypt.SetupByEncryptionKey(encryptionKey, lengthValue); } for (int k = 0; k < strings.Count; ++k) { PdfString str = (PdfString)strings[k]; str.Decrypt(this); } if (encDic.IsIndirect()) { cryptoRef = (PRIndirectReference)encDic; xrefObj[cryptoRef.Number] = null; } } /** * @param obj * @return a PdfObject */ public static PdfObject GetPdfObjectRelease(PdfObject obj) { PdfObject obj2 = GetPdfObject(obj); ReleaseLastXrefPartial(obj); return obj2; } /** * Reads a <CODE>PdfObject</CODE> resolving an indirect reference * if needed. * @param obj the <CODE>PdfObject</CODE> to read * @return the resolved <CODE>PdfObject</CODE> */ public static PdfObject GetPdfObject(PdfObject obj) { if (obj == null) return null; if (!obj.IsIndirect()) return obj; PRIndirectReference refi = (PRIndirectReference)obj; int idx = refi.Number; bool appendable = refi.Reader.appendable; obj = refi.Reader.GetPdfObject(idx); if (obj == null) { return null; } else { if (appendable) { switch (obj.Type) { case PdfObject.NULL: obj = new PdfNull(); break; case PdfObject.BOOLEAN: obj = new PdfBoolean(((PdfBoolean)obj).BooleanValue); break; case PdfObject.NAME: obj = new PdfName(obj.GetBytes()); break; } obj.IndRef = refi; } return obj; } } /** * Reads a <CODE>PdfObject</CODE> resolving an indirect reference * if needed. If the reader was opened in partial mode the object will be released * to save memory. * @param obj the <CODE>PdfObject</CODE> to read * @param parent * @return a PdfObject */ public static PdfObject GetPdfObjectRelease(PdfObject obj, PdfObject parent) { PdfObject obj2 = GetPdfObject(obj, parent); ReleaseLastXrefPartial(obj); return obj2; } /** * @param obj * @param parent * @return a PdfObject */ public static PdfObject GetPdfObject(PdfObject obj, PdfObject parent) { if (obj == null) return null; if (!obj.IsIndirect()) { PRIndirectReference refi = null; if (parent != null && (refi = parent.IndRef) != null && refi.Reader.Appendable) { switch (obj.Type) { case PdfObject.NULL: obj = new PdfNull(); break; case PdfObject.BOOLEAN: obj = new PdfBoolean(((PdfBoolean)obj).BooleanValue); break; case PdfObject.NAME: obj = new PdfName(obj.GetBytes()); break; } obj.IndRef = refi; } return obj; } return GetPdfObject(obj); } /** * @param idx * @return a PdfObject */ public PdfObject GetPdfObjectRelease(int idx) { PdfObject obj = GetPdfObject(idx); ReleaseLastXrefPartial(); return obj; } /** * @param idx * @return aPdfObject */ public PdfObject GetPdfObject(int idx) { lastXrefPartial = -1; if (idx < 0 || idx >= xrefObj.Count) return null; PdfObject obj = (PdfObject)xrefObj[idx]; if (!partial || obj != null) return obj; if (idx * 2 >= xref.Length) return null; obj = ReadSingleObject(idx); lastXrefPartial = -1; if (obj != null) lastXrefPartial = idx; return obj; } /** * */ public void ResetLastXrefPartial() { lastXrefPartial = -1; } /** * */ public void ReleaseLastXrefPartial() { if (partial && lastXrefPartial != -1) { xrefObj[lastXrefPartial] = null; lastXrefPartial = -1; } } /** * @param obj */ public static void ReleaseLastXrefPartial(PdfObject obj) { if (obj == null) return; if (!obj.IsIndirect()) return; PRIndirectReference refi = (PRIndirectReference)obj; PdfReader reader = refi.Reader; if (reader.partial && reader.lastXrefPartial != -1 && reader.lastXrefPartial == refi.Number) { reader.xrefObj[reader.lastXrefPartial] = null; } reader.lastXrefPartial = -1; } private void SetXrefPartialObject(int idx, PdfObject obj) { if (!partial || idx < 0) return; xrefObj[idx] = obj; } /** * @param obj * @return an indirect reference */ public PRIndirectReference AddPdfObject(PdfObject obj) { xrefObj.Add(obj); return new PRIndirectReference(this, xrefObj.Count - 1); } protected internal void ReadPages() { pageInh = new ArrayList(); catalog = (PdfDictionary)GetPdfObject(trailer.Get(PdfName.ROOT)); rootPages = (PdfDictionary)GetPdfObject(catalog.Get(PdfName.PAGES)); pageRefs = new PageRefs(this); } protected internal void ReadDocObjPartial() { xrefObj = // MASC 20070308. CF compatibility patch #if !NETCF ArrayList.Repeat( #else ArrayListEx.Repeat( #endif null, xref.Length / 2 ); ReadDecryptedDocObj(); if (objStmToOffset != null) { int[] keys = objStmToOffset.GetKeys(); for (int k = 0; k < keys.Length; ++k) { int n = keys[k]; objStmToOffset[n] = xref[n * 2]; xref[n * 2] = -1; } } } protected internal PdfObject ReadSingleObject(int k) { strings.Clear(); int k2 = k * 2; int pos = xref[k2]; if (pos < 0) return null; if (xref[k2 + 1] > 0) pos = objStmToOffset[xref[k2 + 1]]; if (pos == 0) return null; tokens.Seek(pos); tokens.NextValidToken(); if (tokens.TokenType != PRTokeniser.TK_NUMBER) tokens.ThrowError("Invalid object number."); objNum = tokens.IntValue; tokens.NextValidToken(); if (tokens.TokenType != PRTokeniser.TK_NUMBER) tokens.ThrowError("Invalid generation number."); objGen = tokens.IntValue; tokens.NextValidToken(); if (!tokens.StringValue.Equals("obj")) tokens.ThrowError("Token 'obj' expected."); PdfObject obj; try { obj = ReadPRObject(); for (int j = 0; j < strings.Count; ++j) { PdfString str = (PdfString)strings[j]; str.Decrypt(this); } if (obj.IsStream()) { CheckPRStreamLength((PRStream)obj); } } catch { obj = null; } if (xref[k2 + 1] > 0) { obj = ReadOneObjStm((PRStream)obj, xref[k2]); } xrefObj[k] = obj; return obj; } protected internal PdfObject ReadOneObjStm(PRStream stream, int idx) { int first = ((PdfNumber)GetPdfObject(stream.Get(PdfName.FIRST))).IntValue; byte[] b = GetStreamBytes(stream, tokens.File); PRTokeniser saveTokens = tokens; tokens = new PRTokeniser(b); try { int address = 0; bool ok = true; ++idx; for (int k = 0; k < idx; ++k) { ok = tokens.NextToken(); if (!ok) break; if (tokens.TokenType != PRTokeniser.TK_NUMBER) { ok = false; break; } ok = tokens.NextToken(); if (!ok) break; if (tokens.TokenType != PRTokeniser.TK_NUMBER) { ok = false; break; } address = tokens.IntValue + first; } if (!ok) throw new IOException("Error reading ObjStm"); tokens.Seek(address); return ReadPRObject(); } finally { tokens = saveTokens; } } /** * @return the percentage of the cross reference table that has been read */ public double DumpPerc() { int total = 0; for (int k = 0; k < xrefObj.Count; ++k) { if (xrefObj[k] != null) ++total; } return (total * 100.0 / xrefObj.Count); } protected internal void ReadDocObj() { ArrayList streams = new ArrayList(); xrefObj = // MASC 20070308. CF compatibility patch #if !NETCF ArrayList.Repeat( #else ArrayListEx.Repeat( #endif null, xref.Length / 2 ); for (int k = 2; k < xref.Length; k += 2) { int pos = xref[k]; if (pos <= 0 || xref[k + 1] > 0) continue; tokens.Seek(pos); tokens.NextValidToken(); if (tokens.TokenType != PRTokeniser.TK_NUMBER) tokens.ThrowError("Invalid object number."); objNum = tokens.IntValue; tokens.NextValidToken(); if (tokens.TokenType != PRTokeniser.TK_NUMBER) tokens.ThrowError("Invalid generation number."); objGen = tokens.IntValue; tokens.NextValidToken(); if (!tokens.StringValue.Equals("obj")) tokens.ThrowError("Token 'obj' expected."); PdfObject obj; try { obj = ReadPRObject(); if (obj.IsStream()) { streams.Add(obj); } } catch { obj = null; } xrefObj[k / 2] = obj; } for (int k = 0; k < streams.Count; ++k) { CheckPRStreamLength((PRStream)streams[k]); } ReadDecryptedDocObj(); if (objStmMark != null) { foreach (DictionaryEntry entry in objStmMark) { int n = (int)entry.Key; IntHashtable h = (IntHashtable)entry.Value; ReadObjStm((PRStream)xrefObj[n], h); xrefObj[n] = null; } objStmMark = null; } xref = null; } private void CheckPRStreamLength(PRStream stream) { int fileLength = tokens.Length; int start = stream.Offset; bool calc = false; int streamLength = 0; PdfObject obj = GetPdfObjectRelease(stream.Get(PdfName.LENGTH)); if (obj != null && obj.Type == PdfObject.NUMBER) { streamLength = ((PdfNumber)obj).IntValue; if (streamLength + start > fileLength - 20) calc = true; else { tokens.Seek(start + streamLength); String line = tokens.ReadString(20); if (!line.StartsWith("\nendstream") && !line.StartsWith("\r\nendstream") && !line.StartsWith("\rendstream") && !line.StartsWith("endstream")) calc = true; } } else calc = true; if (calc) { byte[] tline = new byte[16]; tokens.Seek(start); while (true) { int pos = tokens.FilePointer; if (!tokens.ReadLineSegment(tline)) break; if (Equalsn(tline, endstream)) { streamLength = pos - start; break; } if (Equalsn(tline, endobj)) { tokens.Seek(pos - 16); String s = tokens.ReadString(16); int index = s.IndexOf("endstream"); if (index >= 0) pos = pos - 16 + index; streamLength = pos - start; break; } } } stream.Length = streamLength; } protected internal void ReadObjStm(PRStream stream, IntHashtable map) { int first = ((PdfNumber)GetPdfObject(stream.Get(PdfName.FIRST))).IntValue; int n = ((PdfNumber)GetPdfObject(stream.Get(PdfName.N))).IntValue; byte[] b = GetStreamBytes(stream, tokens.File); PRTokeniser saveTokens = tokens; tokens = new PRTokeniser(b); try { int[] address = new int[n]; int[] objNumber = new int[n]; bool ok = true; for (int k = 0; k < n; ++k) { ok = tokens.NextToken(); if (!ok) break; if (tokens.TokenType != PRTokeniser.TK_NUMBER) { ok = false; break; } objNumber[k] = tokens.IntValue; ok = tokens.NextToken(); if (!ok) break; if (tokens.TokenType != PRTokeniser.TK_NUMBER) { ok = false; break; } address[k] = tokens.IntValue + first; } if (!ok) throw new IOException("Error reading ObjStm"); for (int k = 0; k < n; ++k) { if (map.ContainsKey(k)) { tokens.Seek(address[k]); PdfObject obj = ReadPRObject(); xrefObj[objNumber[k]] = obj; } } } finally { tokens = saveTokens; } } /** * Eliminates the reference to the object freeing the memory used by it and clearing * the xref entry. * @param obj the object. If it's an indirect reference it will be eliminated * @return the object or the already erased dereferenced object */ public static PdfObject KillIndirect(PdfObject obj) { if (obj == null || obj.IsNull()) return null; PdfObject ret = GetPdfObjectRelease(obj); if (obj.IsIndirect()) { PRIndirectReference refi = (PRIndirectReference)obj; PdfReader reader = refi.Reader; int n = refi.Number; reader.xrefObj[n] = null; if (reader.partial) reader.xref[n * 2] = -1; } return ret; } private void EnsureXrefSize(int size) { if (size == 0) return; if (xref == null) xref = new int[size]; else { if (xref.Length < size) { int[] xref2 = new int[size]; Array.Copy(xref, 0, xref2, 0, xref.Length); xref = xref2; } } } protected internal void ReadXref() { hybridXref = false; newXrefType = false; tokens.Seek(tokens.Startxref); tokens.NextToken(); if (!tokens.StringValue.Equals("startxref")) throw new IOException("startxref not found."); tokens.NextToken(); if (tokens.TokenType != PRTokeniser.TK_NUMBER) throw new IOException("startxref is not followed by a number."); int startxref = tokens.IntValue; lastXref = startxref; eofPos = tokens.FilePointer; try { if (ReadXRefStream(startxref)) { newXrefType = true; return; } } catch {} xref = null; tokens.Seek(startxref); trailer = ReadXrefSection(); PdfDictionary trailer2 = trailer; while (true) { PdfNumber prev = (PdfNumber)trailer2.Get(PdfName.PREV); if (prev == null) break; tokens.Seek(prev.IntValue); trailer2 = ReadXrefSection(); } } protected internal PdfDictionary ReadXrefSection() { tokens.NextValidToken(); if (!tokens.StringValue.Equals("xref")) tokens.ThrowError("xref subsection not found"); int start = 0; int end = 0; int pos = 0; int gen = 0; while (true) { tokens.NextValidToken(); if (tokens.StringValue.Equals("trailer")) break; if (tokens.TokenType != PRTokeniser.TK_NUMBER) tokens.ThrowError("Object number of the first object in this xref subsection not found"); start = tokens.IntValue; tokens.NextValidToken(); if (tokens.TokenType != PRTokeniser.TK_NUMBER) tokens.ThrowError("Number of entries in this xref subsection not found"); end = tokens.IntValue + start; if (start == 1) { // fix incorrect start number int back = tokens.FilePointer; tokens.NextValidToken(); pos = tokens.IntValue; tokens.NextValidToken(); gen = tokens.IntValue; if (pos == 0 && gen == 65535) { --start; --end; } tokens.Seek(back); } EnsureXrefSize(end * 2); for (int k = start; k < end; ++k) { tokens.NextValidToken(); pos = tokens.IntValue; tokens.NextValidToken(); gen = tokens.IntValue; tokens.NextValidToken(); int p = k * 2; if (tokens.StringValue.Equals("n")) { if (xref[p] == 0 && xref[p + 1] == 0) { // if (pos == 0) // tokens.ThrowError("File position 0 cross-reference entry in this xref subsection"); xref[p] = pos; } } else if (tokens.StringValue.Equals("f")) { if (xref[p] == 0 && xref[p + 1] == 0) xref[p] = -1; } else tokens.ThrowError("Invalid cross-reference entry in this xref subsection"); } } PdfDictionary trailer = (PdfDictionary)ReadPRObject(); PdfNumber xrefSize = (PdfNumber)trailer.Get(PdfName.SIZE); EnsureXrefSize(xrefSize.IntValue * 2); PdfObject xrs = trailer.Get(PdfName.XREFSTM); if (xrs != null && xrs.IsNumber()) { int loc = ((PdfNumber)xrs).IntValue; try { ReadXRefStream(loc); newXrefType = true; hybridXref = true; } catch (IOException e) { xref = null; throw e; } } return trailer; } protected internal bool ReadXRefStream(int ptr) { tokens.Seek(ptr); int thisStream = 0; if (!tokens.NextToken()) return false; if (tokens.TokenType != PRTokeniser.TK_NUMBER) return false; thisStream = tokens.IntValue; if (!tokens.NextToken() || tokens.TokenType != PRTokeniser.TK_NUMBER) return false; if (!tokens.NextToken() || !tokens.StringValue.Equals("obj")) return false; PdfObject objecto = ReadPRObject(); PRStream stm = null; if (objecto.IsStream()) { stm = (PRStream)objecto; if (!PdfName.XREF.Equals(stm.Get(PdfName.TYPE))) return false; } else return false; if (trailer == null) { trailer = new PdfDictionary(); trailer.Merge(stm); } stm.Length = ((PdfNumber)stm.Get(PdfName.LENGTH)).IntValue; int size = ((PdfNumber)stm.Get(PdfName.SIZE)).IntValue; PdfArray index; PdfObject obj = stm.Get(PdfName.INDEX); if (obj == null) { index = new PdfArray(); index.Add(new int[]{0, size}); } else index = (PdfArray)obj; PdfArray w = (PdfArray)stm.Get(PdfName.W); int prev = -1; obj = stm.Get(PdfName.PREV); if (obj != null) prev = ((PdfNumber)obj).IntValue; // Each xref pair is a position // type 0 -> -1, 0 // type 1 -> offset, 0 // type 2 -> index, obj num EnsureXrefSize(size * 2); if (objStmMark == null && !partial) objStmMark = new Hashtable(); if (objStmToOffset == null && partial) objStmToOffset = new IntHashtable(); byte[] b = GetStreamBytes(stm, tokens.File); int bptr = 0; ArrayList wa = w.ArrayList; int[] wc = new int[3]; for (int k = 0; k < 3; ++k) wc[k] = ((PdfNumber)wa[k]).IntValue; ArrayList sections = index.ArrayList; for (int idx = 0; idx < sections.Count; idx += 2) { int start = ((PdfNumber)sections[idx]).IntValue; int length = ((PdfNumber)sections[idx + 1]).IntValue; EnsureXrefSize((start + length) * 2); while (length-- > 0) { int type = 1; if (wc[0] > 0) { type = 0; for (int k = 0; k < wc[0]; ++k) type = (type << 8) + (b[bptr++] & 0xff); } int field2 = 0; for (int k = 0; k < wc[1]; ++k) field2 = (field2 << 8) + (b[bptr++] & 0xff); int field3 = 0; for (int k = 0; k < wc[2]; ++k) field3 = (field3 << 8) + (b[bptr++] & 0xff); int baseb = start * 2; if (xref[baseb] == 0 && xref[baseb + 1] == 0) { switch (type) { case 0: xref[baseb] = -1; break; case 1: xref[baseb] = field2; break; case 2: xref[baseb] = field3; xref[baseb + 1] = field2; if (partial) { objStmToOffset[field2] = 0; } else { IntHashtable seq = (IntHashtable)objStmMark[field2]; if (seq == null) { seq = new IntHashtable(); seq[field3] = 1; objStmMark[field2] = seq; } else seq[field3] = 1; } break; } } ++start; } } thisStream *= 2; if (thisStream < xref.Length) xref[thisStream] = -1; if (prev == -1) return true; return ReadXRefStream(prev); } protected internal void RebuildXref() { hybridXref = false; newXrefType = false; tokens.Seek(0); int[][] xr = new int[1024][]; int top = 0; trailer = null; byte[] line = new byte[64]; for (;;) { int pos = tokens.FilePointer; if (!tokens.ReadLineSegment(line)) break; if (line[0] == 't') { if (!PdfEncodings.ConvertToString(line, null).StartsWith("trailer")) continue; tokens.Seek(pos); tokens.NextToken(); pos = tokens.FilePointer; try { PdfDictionary dic = (PdfDictionary)ReadPRObject(); if (dic.Get(PdfName.ROOT) != null) trailer = dic; else tokens.Seek(pos); } catch { tokens.Seek(pos); } } else if (line[0] >= '0' && line[0] <= '9') { int[] obj = PRTokeniser.CheckObjectStart(line); if (obj == null) continue; int num = obj[0]; int gen = obj[1]; if (num >= xr.Length) { int newLength = num * 2; int[][] xr2 = new int[newLength][]; Array.Copy(xr, 0, xr2, 0, top); xr = xr2; } if (num >= top) top = num + 1; if (xr[num] == null || gen >= xr[num][1]) { obj[0] = pos; xr[num] = obj; } } } if (trailer == null) throw new IOException("trailer not found."); xref = new int[top * 2]; for (int k = 0; k < top; ++k) { int[] obj = xr[k]; if (obj != null) xref[k * 2] = obj[0]; } } protected internal PdfDictionary ReadDictionary() { PdfDictionary dic = new PdfDictionary(); while (true) { tokens.NextValidToken(); if (tokens.TokenType == PRTokeniser.TK_END_DIC) break; if (tokens.TokenType != PRTokeniser.TK_NAME) tokens.ThrowError("Dictionary key is not a name."); PdfName name = new PdfName(tokens.StringValue, false); PdfObject obj = ReadPRObject(); int type = obj.Type; if (-type == PRTokeniser.TK_END_DIC) tokens.ThrowError("Unexpected '>>'"); if (-type == PRTokeniser.TK_END_ARRAY) tokens.ThrowError("Unexpected ']'"); dic.Put(name, obj); } return dic; } protected internal PdfArray ReadArray() { PdfArray array = new PdfArray(); while (true) { PdfObject obj = ReadPRObject(); int type = obj.Type; if (-type == PRTokeniser.TK_END_ARRAY) break; if (-type == PRTokeniser.TK_END_DIC) tokens.ThrowError("Unexpected '>>'"); array.Add(obj); } return array; } protected internal PdfObject ReadPRObject() { tokens.NextValidToken(); int type = tokens.TokenType; switch (type) { case PRTokeniser.TK_START_DIC: { PdfDictionary dic = ReadDictionary(); int pos = tokens.FilePointer; // be careful in the trailer. May not be a "next" token. if (tokens.NextToken() && tokens.StringValue.Equals("stream")) { int ch = tokens.Read(); if (ch != '\n') ch = tokens.Read(); if (ch != '\n') tokens.BackOnePosition(ch); PRStream stream = new PRStream(this, tokens.FilePointer); stream.Merge(dic); stream.ObjNum = objNum; stream.ObjGen = objGen; return stream; } else { tokens.Seek(pos); return dic; } } case PRTokeniser.TK_START_ARRAY: return ReadArray(); case PRTokeniser.TK_NUMBER: return new PdfNumber(tokens.StringValue); case PRTokeniser.TK_STRING: PdfString str = new PdfString(tokens.StringValue, null).SetHexWriting(tokens.IsHexString()); str.SetObjNum(objNum, objGen); if (strings != null) strings.Add(str); return str; case PRTokeniser.TK_NAME: return new PdfName(tokens.StringValue, false); case PRTokeniser.TK_REF: int num = tokens.Reference; PRIndirectReference refi = new PRIndirectReference(this, num, tokens.Generation); return refi; default: String sv = tokens.StringValue; if ("null".Equals(sv)) return PdfNull.PDFNULL; else if ("true".Equals(sv)) return PdfBoolean.PDFTRUE; else if ("false".Equals(sv)) return PdfBoolean.PDFFALSE; return new PdfLiteral(-type, tokens.StringValue); } } /** Decodes a stream that has the FlateDecode filter. * @param in the input data * @return the decoded data */ public static byte[] FlateDecode(byte[] inp) { byte[] b = FlateDecode(inp, true); if (b == null) return FlateDecode(inp, false); return b; } /** * @param in * @param dicPar * @return a byte array */ public static byte[] DecodePredictor(byte[] inp, PdfObject dicPar) { if (dicPar == null || !dicPar.IsDictionary()) return inp; PdfDictionary dic = (PdfDictionary)dicPar; PdfObject obj = GetPdfObject(dic.Get(PdfName.PREDICTOR)); if (obj == null || !obj.IsNumber()) return inp; int predictor = ((PdfNumber)obj).IntValue; if (predictor < 10) return inp; int width = 1; obj = GetPdfObject(dic.Get(PdfName.COLUMNS)); if (obj != null && obj.IsNumber()) width = ((PdfNumber)obj).IntValue; int colors = 1; obj = GetPdfObject(dic.Get(PdfName.COLORS)); if (obj != null && obj.IsNumber()) colors = ((PdfNumber)obj).IntValue; int bpc = 8; obj = GetPdfObject(dic.Get(PdfName.BITSPERCOMPONENT)); if (obj != null && obj.IsNumber()) bpc = ((PdfNumber)obj).IntValue; MemoryStream dataStream = new MemoryStream(inp); MemoryStream fout = new MemoryStream(inp.Length); int bytesPerPixel = colors * bpc / 8; int bytesPerRow = (colors*width*bpc + 7)/8; byte[] curr = new byte[bytesPerRow]; byte[] prior = new byte[bytesPerRow]; // Decode the (sub)image row-by-row while (true) { // Read the filter type byte and a row of data int filter = 0; try { filter = dataStream.ReadByte(); if (filter < 0) { return fout.ToArray(); } int tot = 0; while (tot < bytesPerRow) { int n = dataStream.Read(curr, tot, bytesPerRow - tot); if (n <= 0) return fout.ToArray(); tot += n; } } catch { return fout.ToArray(); } switch (filter) { case 0: //PNG_FILTER_NONE break; case 1: //PNG_FILTER_SUB for (int i = bytesPerPixel; i < bytesPerRow; i++) { curr[i] += curr[i - bytesPerPixel]; } break; case 2: //PNG_FILTER_UP for (int i = 0; i < bytesPerRow; i++) { curr[i] += prior[i]; } break; case 3: //PNG_FILTER_AVERAGE for (int i = 0; i < bytesPerPixel; i++) { curr[i] += (byte)(prior[i] / 2); } for (int i = bytesPerPixel; i < bytesPerRow; i++) { curr[i] += (byte)(((curr[i - bytesPerPixel] & 0xff) + (prior[i] & 0xff))/2); } break; case 4: //PNG_FILTER_PAETH for (int i = 0; i < bytesPerPixel; i++) { curr[i] += prior[i]; } for (int i = bytesPerPixel; i < bytesPerRow; i++) { int a = curr[i - bytesPerPixel] & 0xff; int b = prior[i] & 0xff; int c = prior[i - bytesPerPixel] & 0xff; int p = a + b - c; int pa = Math.Abs(p - a); int pb = Math.Abs(p - b); int pc = Math.Abs(p - c); int ret; if ((pa <= pb) && (pa <= pc)) { ret = a; } else if (pb <= pc) { ret = b; } else { ret = c; } curr[i] += (byte)(ret); } break; default: // Error -- uknown filter type throw new Exception("PNG filter unknown."); }
[ " fout.Write(curr, 0, curr.Length);" ]
6,006
lcc
csharp
null
0cc866de4a40f62e0dc2031e25487c87a06027728f76c5a9
#!/usr/bin/env python """Tests that don't need an active D-Bus connection to run, but can be run in isolation. """ # Copyright (C) 2006 Collabora Ltd. <http://www.collabora.co.uk/> # # 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. from __future__ import unicode_literals import sys import os import unittest builddir = os.path.normpath(os.environ["DBUS_TOP_BUILDDIR"]) pydir = os.path.normpath(os.environ["DBUS_TOP_SRCDIR"]) import _dbus_bindings import dbus import dbus.lowlevel as lowlevel import dbus.types as types from dbus._compat import is_py2, is_py3 if is_py3: def make_long(n): return n else: def make_long(n): return long(n) # Check that we're using the right versions if not dbus.__file__.startswith(pydir): raise Exception("DBus modules (%s) are not being picked up from the package"%dbus.__file__) if not _dbus_bindings.__file__.startswith(builddir): raise Exception("DBus modules (%s) are not being picked up from the package"%_dbus_bindings.__file__) assert (_dbus_bindings._python_version & 0xffff0000 == sys.hexversion & 0xffff0000), \ '_dbus_bindings was compiled for Python %x but this is Python %x, '\ 'a different major version'\ % (_dbus_bindings._python_version, sys.hexversion) assert _dbus_bindings.__version__ == os.environ['DBUS_PYTHON_VERSION'], \ '_dbus_bindings was compiled as version %s but Automake says '\ 'we should be version %s' \ % (_dbus_bindings.__version__, os.environ['DBUS_PYTHON_VERSION']) class TestTypes(unittest.TestCase): def test_Dictionary(self): self.assertEqual(types.Dictionary({'foo':'bar'}), {'foo':'bar'}) self.assertEqual(types.Dictionary({}, variant_level=2), {}) self.assertEqual(types.Dictionary({}, variant_level=2).variant_level, 2) def test_Array(self): self.assertEqual(types.Array(['foo','bar']), ['foo','bar']) self.assertEqual(types.Array([], variant_level=2), []) self.assertEqual(types.Array([], variant_level=2).variant_level, 2) def test_Double(self): self.assertEqual(types.Double(0.0), 0.0) self.assertEqual(types.Double(0.125, variant_level=2), 0.125) self.assertEqual(types.Double(0.125, variant_level=2).variant_level, 2) def test_Struct(self): x = types.Struct(('',)) self.assertEqual(x.variant_level, 0) self.assertEqual(x, ('',)) x = types.Struct('abc', variant_level=42) self.assertEqual(x.variant_level, 42) self.assertEqual(x, ('a','b','c')) def test_Byte(self): self.assertEqual(types.Byte(b'x', variant_level=2), types.Byte(ord('x'))) self.assertEqual(types.Byte(1), 1) self.assertEqual(types.Byte(make_long(1)), 1) self.assertRaises(Exception, lambda: types.Byte(b'ab')) self.assertRaises(TypeError, types.Byte, '\x12xxxxxxxxxxxxx') # Byte from a unicode object: what would that even mean? self.assertRaises(Exception, lambda: types.Byte(b'a'.decode('latin-1'))) def test_ByteArray(self): self.assertEqual(types.ByteArray(b''), b'') def test_object_path_attr(self): class MyObject(object): __dbus_object_path__ = '/foo' from _dbus_bindings import SignalMessage self.assertEqual(SignalMessage.guess_signature(MyObject()), 'o') def test_integers(self): subclasses = [int] if is_py2: subclasses.append(long) subclasses = tuple(subclasses) # This is an API guarantee. Note that exactly which of these types # are ints and which of them are longs is *not* guaranteed. for cls in (types.Int16, types.UInt16, types.Int32, types.UInt32, types.Int64, types.UInt64): self.assertTrue(issubclass(cls, subclasses)) self.assertTrue(isinstance(cls(0), subclasses)) self.assertEqual(cls(0), 0) self.assertEqual(cls(23, variant_level=1), 23) self.assertEqual(cls(23, variant_level=1).variant_level, 1) def test_integer_limits_16(self): self.assertEqual(types.Int16(0x7fff), 0x7fff) self.assertEqual(types.Int16(-0x8000), -0x8000) self.assertEqual(types.UInt16(0xffff), 0xffff) self.assertRaises(Exception, types.Int16, 0x8000) self.assertRaises(Exception, types.Int16, -0x8001) self.assertRaises(Exception, types.UInt16, 0x10000) def test_integer_limits_32(self): self.assertEqual(types.Int32(0x7fffffff), 0x7fffffff) self.assertEqual(types.Int32(make_long(-0x80000000)), make_long(-0x80000000)) self.assertEqual(types.UInt32(make_long(0xffffffff)), make_long(0xffffffff)) self.assertRaises(Exception, types.Int32, make_long(0x80000000)) self.assertRaises(Exception, types.Int32, make_long(-0x80000001)) self.assertRaises(Exception, types.UInt32, make_long(0x100000000)) def test_integer_limits_64(self): self.assertEqual(types.Int64(make_long(0x7fffffffffffffff)), make_long(0x7fffffffffffffff)) self.assertEqual(types.Int64(make_long(-0x8000000000000000)), make_long(-0x8000000000000000)) self.assertEqual(types.UInt64(make_long(0xffffffffffffffff)), make_long(0xffffffffffffffff)) self.assertRaises(Exception, types.Int16, make_long(0x8000000000000000)) self.assertRaises(Exception, types.Int16, make_long(-0x8000000000000001)) self.assertRaises(Exception, types.UInt16, make_long(0x10000000000000000)) def test_Signature(self): self.assertRaises(Exception, types.Signature, 'a') self.assertEqual(types.Signature('ab', variant_level=23), 'ab') self.assertTrue(isinstance(types.Signature('ab'), str)) self.assertEqual(tuple(types.Signature('ab(xt)a{sv}')), ('ab', '(xt)', 'a{sv}')) self.assertTrue(isinstance(tuple(types.Signature('ab'))[0], types.Signature)) class TestMessageMarshalling(unittest.TestCase): def test_path(self): s = lowlevel.SignalMessage('/a/b/c', 'foo.bar', 'baz') self.assertEqual(s.get_path(), types.ObjectPath('/a/b/c')) self.assertEqual(type(s.get_path()), types.ObjectPath) self.assertEqual(s.get_path_decomposed(), ['a', 'b', 'c']) # this is true in both major versions: it's a bytestring in # Python 2 and a Unicode string in Python 3 self.assertEqual(type(s.get_path_decomposed()[0]), str) self.assertTrue(s.has_path('/a/b/c')) self.assertFalse(s.has_path('/a/b')) self.assertFalse(s.has_path('/a/b/c/d')) s = lowlevel.SignalMessage('/', 'foo.bar', 'baz') self.assertEqual(s.get_path(), types.ObjectPath('/')) self.assertEqual(s.get_path().__class__, types.ObjectPath) self.assertEqual(s.get_path_decomposed(), []) self.assertTrue(s.has_path('/')) self.assertFalse(s.has_path(None)) def test_sender(self): s = lowlevel.SignalMessage('/a/b/c', 'foo.bar', 'baz') self.assertEqual(s.get_sender(), None) self.assertFalse(s.has_sender(':1.23')) s.set_sender(':1.23') self.assertEqual(s.get_sender(), ':1.23') # bytestring in Python 2, Unicode string in Python 3 self.assertEqual(type(s.get_sender()), str) self.assertTrue(s.has_sender(':1.23')) def test_destination(self): s = lowlevel.SignalMessage('/a/b/c', 'foo.bar', 'baz') self.assertEqual(s.get_destination(), None) self.assertFalse(s.has_destination(':1.23')) s.set_destination(':1.23') self.assertEqual(s.get_destination(), ':1.23') # bytestring in Python 2, Unicode string in Python 3 self.assertEqual(type(s.get_destination()), str) self.assertTrue(s.has_destination(':1.23')) def test_interface(self):
[ " s = lowlevel.SignalMessage('/a/b/c', 'foo.bar', 'baz')" ]
677
lcc
python
null
fdfc363818ce22cc623b576870180ec881f0a75f716cd8a8
from pickle_storage import * from options import * from module_map import * from E2_page import * from db.etwo import EtwoStore import os.path try: from plot_page import * except (ImportError, RuntimeError): pass class MASS(object): def __init__(self, options = None): if not options: self.options = Options.default("Real") else: self.options = options self.resolution_flag = False self.resolution_loaded_flag = False self.resolution_no_mat_flag = False self.resolution_no_mat_loaded_flag = False self.E_2_page_flag = False self.E_2_page_no_mat_flag = False def get_options(self): return self.options def set_case(self, case): self.get_options().case = case def set_comm_db(self, database): self.get_options().commutativity_database = database def set_adem_db(self, database): self.get_options().adem_database = database def set_degree_bounds(self, bounds): self.get_options().degree_bounds = bounds self.resolution_flag = False def set_log_file(self, filename): self.get_options().log_file = filename def set_logging_level(self, level): self.get_options().logging_level = level def set_resolution_file(self, filename): self.get_options().resolution_file = filename def set_dual_resolution_file(self, filename): self.get_options().dual_resolution_file = filename def set_t(self, t): self.get_options().t =t def set_p(self, p): self.get_options().p = p def set_p_dual(self, p_dual): self.get_options().p_dual = p_dual def set_t_dual(self, t_dual): self.get_options().t_dual = t_dual def set_degree_dictionary(self, dictionary): self.get_options().degree_dictionary = dictionary def set_numpcs(self, number): self.get_options().numpcs = number def start_session(self): """ This starts the various shared database servers """ self.get_options().get_comm_db() self.get_options().get_adem_db() def stop_session(self): """ This method properly closes out of shared dictionary servers, and pickles any modifications to the dictionaries. """ self.get_options().get_comm_db().shutdown() self.get_options().get_adem_db().shutdown() self.get_E_2_page_no_mat().pickle_lol_storage(self.get_options()) #which E_2_page gets the LOL? def initialize_resolution(self): module_map = make_initial_map(self.get_options()) pickle_file = open(self.get_options().get_resolution_file(), "wb") new_resolution = Resolution([module_map], self.get_options()) pickle.dump(new_resolution, pickle_file, -1) pickle_file.close() def load_pickled_resolution(self): logging.basicConfig(filename=self.get_options().get_log_file(), level=self.get_options().get_logging_level()) logging.warning("loading pickled resolution") pickle_file = open(self.get_options().get_resolution_file(), "rb") self.resolution = pickle.load(pickle_file) pickle_file.close() self.resolution_loaded_flag = True def compute_resolution(self, length): logging.basicConfig(filename=self.get_options().get_log_file(), level=self.get_options().get_logging_level()) logging.warning("continuing resolution") logging.warning(time.ctime()) if not self.resolution_loaded_flag: self.load_pickled_resolution() current_length = self.resolution.get_length() logging.warning("i'm at " + str(current_length)) logging.warning(time.ctime()) while current_length <= length: logging.warning("moving on to next resolvant") logging.warning(time.ctime()) last_map = self.resolution.get_map_list()[-1] self.resolution.get_map_list().append( last_map.get_next_resolvant( "h" + str(current_length), self.get_options())) current_length = current_length + 1 pickle_filename = self.get_options().get_resolution_file() pickle_file = open(pickle_filename, "wb") pickle.dump(self.resolution, pickle_file, -1) pickle_file.close() logging.warning(time.ctime()) logging.warning("DONE!!!") def extend_resolution(self, new_degree_bounds): logging.basicConfig(filename=self.get_options().get_log_file(), level=self.get_options().get_logging_level()) if not self.resolution_loaded_flag: self.load_pickled_resolution() logging.warning("continuing resolution") logging.warning(time.ctime()) new_resolution = [] new_resolution.append(extend_initial_map( new_degree_bounds, self.get_options())) for index in xrange(len(self.resolution.get_map_list()) - 1): logging.warning("moving on to next resolvant") logging.warning(time.ctime()) _map = new_resolution[index] logging.warning("got the map") new_resolution.append( _map.extend_next_resolvant( self.resolution.get_map_list()[index+1], "h" + str(index+2), new_degree_bounds, self.get_options())) logging.warning("extended resolution") pickle_file = open(self.get_options().get_resolution_file(), "wb") the_resolution = Resolution(new_resolution, self.get_options()) pickle.dump(the_resolution, pickle_file, -1) pickle_file.close() self.resolution = the_resolution self.get_options().degree_bounds = new_degree_bounds def make_resolution(self): if os.path.isfile(self.get_options( ).get_resolution_file()): if not self.resolution_loaded_flag: self.load_pickled_resolution() first_map = self.resolution.get_map_list()[0] old_bounds = first_map.get_domain().get_deg_bounds() new_bounds = self.get_options().get_degree_bounds() if (old_bounds[0] < new_bounds[0] or old_bounds[1] < new_bounds[1]): self.get_options().degree_bounds = old_bounds self.extend_resolution(new_bounds) self.compute_resolution( self.get_options().get_degree_bounds()[0]/2 + 1) elif (len(self.resolution.get_map_list()) < self.get_options().get_degree_bounds()[0]/2 + 1): self.compute_resolution( self.get_options().get_degree_bounds()[0]/2 + 1) self.resolution_flag = True self.resolution_loaded_flag = True self.resolution_no_mat_flag = False self.resolution_no_mat_loaded_flag = False self.E_2_page_flag = False self.E_2_page_no_mat_flag = False else: self.initialize_resolution() self.compute_resolution( self.get_options().get_degree_bounds()[0]/2 + 1) self.resolution_flag = True self.resolution_loaded_flag = True def get_resolution(self): if not self.resolution_flag or not self.resolution_loaded_flag: self.make_resolution() return self.resolution def make_no_mat_resolution(self): if not self.resolution_no_mat_flag: newres = [] for amap in self.get_resolution().get_map_list(): domain = amap.domain codomain = amap.codomain generator_map = amap.generator_map amap_copy = FreeAModuleMap(domain, codomain, generator_map) newres.append(amap_copy) resolution = Resolution(newres, self.get_options()) pickle_file = open(self.get_options().get_resolution_file_no_mat(), "wb") pickle.dump(resolution, pickle_file, -1) pickle_file.close() def load_no_mat_resolution(self): if not self.resolution_no_mat_loaded_flag: try: pickle_file = open(self.get_options().get_resolution_file_no_mat(), "rb") self.resolution_no_mat = pickle.load(pickle_file) pickle_file.close() first_map = self.resolution_no_mat.get_map_list()[0] old_bounds = first_map.get_domain().get_deg_bounds() new_bounds = self.get_options().get_degree_bounds() if (old_bounds[0] == new_bounds[0] and old_bounds[1] == new_bounds[1]): self.resolution_no_mat_loaded_flag = True else: self.make_no_mat_resolution() except (IOError, EOFError): self.make_no_mat_resolution() else: first_map = self.resolution_no_mat.get_map_list()[0] old_bounds = first_map.get_domain().get_deg_bounds() new_bounds = self.get_options().get_degree_bounds() if (old_bounds[0] == new_bounds[0] and old_bounds[1] == new_bounds[1]): self.resolution_no_mat_loaded_flag = True else: self.make_no_mat_resolution() def get_no_mat_resolution(self): if (not self.resolution_no_mat_loaded_flag or not self.resolution_no_mat_flag): self.load_no_mat_resolution() return self.resolution_no_mat def compute_E_2_page(self): self.E_2_page = E2Page(self.get_resolution(), self.get_options()) self.E_2_page_flag = True def get_E_2_page(self): if not self.E_2_page_flag: self.compute_E_2_page() return self.E_2_page def compute_E_2_page_no_mat(self): self.E_2_page_no_mat = E2Page(self.get_no_mat_resolution(), self.get_options()) self.E_2_page_no_mat_flag = True def get_E_2_page_no_mat(self): if not self.E_2_page_no_mat_flag: self.compute_E_2_page_no_mat() return self.E_2_page_no_mat def make_dual_resolution(self): self.get_E_2_page_no_mat().make_dual_resolution(self.get_options()) def get_printout(self, filename): self.get_E_2_page_no_mat().printout(filename, self.get_options()) def make_charts(self): charts(self.get_E_2_page_no_mat(), self.options) def make_charts_with_mat(self): #Important note: list of lifts is only saved for #E_2 page without mat! charts(self.get_E_2_page(), self.options) def make_isaksen_chart(self): if self.options.get_case() == "Classical": return for diff in range(0, self.options.get_degree_bounds()[0]): isaksen_chart(self.get_E_2_page(), diff, self.options) def make_classical_chart(self): if self.options.get_case() != "Classical": return classical_chart(self.get_E_2_page(), self.options) def cohomology_info(self, level, position): output = "" e2 = self.get_E_2_page() cohom = e2.get_cohomology(self.options)[level][position] output += "outgoing matrix \n" output += str(cohom.get_B()) + "\n" output += "incoming matrix \n" output += str(cohom.get_A()) + "\n" output += "kernel basis \n" for vect in cohom.get_kernel().get_basis(): output += str(e2.element_from_vector(vect, level, position, self.options)) + "\n" output += "image basis \n" for vect in cohom.get_image().get_basis(): output += str(e2.element_from_vector(vect, level, position, self.options)) + "\n" prev_cohom = e2.get_cohomology(self.options)[level-1][position] output += "what is mapping in to 0 under A \n" for vect in prev_cohom.get_kernel().get_basis(): output += str(e2.element_from_vector(vect, level - 1, position, self.options)) + "\n" mod_basis = e2.get_dual_resolution(self.options).get_map_list()[level - 1].get_domain().get_array(self.options)[position].get_basis() output += "basis for domain of A \n" if mod_basis: for thing in mod_basis: output += str(thing) + "\n" else: output += "the basis is empty \n" mod_basis = e2.get_dual_resolution(self.options).get_map_list()[level].get_domain().get_array(self.options)[position].get_basis() output += "basis for domain of B \n" if mod_basis: for thing in mod_basis: output += str(thing) + "\n" else: output += "the basis is empty\n" mod_basis = e2.get_dual_resolution(self.options).get_map_list()[level - 1].get_domain().get_generator_list() output += "basis for h-dual module for A \n" if mod_basis: for thing in mod_basis: output += str(thing) + "\n" mod_basis = e2.get_dual_resolution(self.options).get_map_list()[level].get_domain().get_generator_list() output += "basis for h-dual module for B \n" if mod_basis: for thing in mod_basis: output += str(thing) + "\n" return output def cohomology_printout(self, filename): output = "" e2 = self.get_E_2_page() for level in xrange(len(e2.get_cohomology(self.options))): for position in e2.get_cohomology(self.options)[level].keys(): output += "At level " + str(level) + " position " + str(position) + "\n" output += self.cohomology_info(level, position) _file = open(filename, 'w+') _file.write(output) _file.close() def compute_product_structure(self): self.get_E_2_page_no_mat().compute_product_structure(self.get_options()) def make_product_database(self): e2 = self.get_E_2_page_no_mat() EtwoStore.prepare() for z_index in xrange(len(e2.get_cohomology(self.options))): z_level = e2.get_cohomology(self.options)[z_index] for position in z_level.keys(): if e2.get_dual_resolution(self.options).get_map_list()[z_index].get_domain().get_array(self.options)[position].get_basis(): for thing in z_level[position].get_product().get_basis(): elt = e2.get_dual_resolution(self.options\ ).get_map_list()[z_index].get_domain(\ ).element_from_vector(position, thing, self.options) for product in e2.product_description_string(elt, self.options): EtwoStore.save(elt, z_index, product, self.options) def p_operator(self, xx, pos_xx): h3 = ModElt(ModuleMonomial(RSq(), Generator("h1(8, 4)0", (8, 4)))) h04 = ModElt(ModuleMonomial(RSq(), Generator("h4(4, 0)0", (4, 0)))) if self.options.get_case() == "Classical": h3 = ModElt(ModuleMonomial(RSq(), Generator("h1(8, 0)0", (8, 0)))) massey_out = self.get_E_2_page().level_one_m_product( h3, 1, h04, 4, xx, pos_xx, self.get_options()) return massey_out def massey_product_printout(self, filename): output = "" map_list = self.get_E_2_page().get_dual_resolution(self.options).get_map_list() for index in xrange(len(map_list)-5): amap = map_list[index] for element in amap.get_domain().get_generator_list(): output += "<h1(8, 4)0, h4(4, 0), " + str(element) output += "> contains " try: m_product = self.p_operator(element, index) output += str(m_product) + "\n"
[ " except (KeyError, AttributeError):" ]
1,017
lcc
python
null
78fd6bbd4847ea904de30d888739147fe917202829362e1d
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google 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. #endregion using System; using System.IO; using Google.ProtocolBuffers.TestProtos; using NUnit.Framework; namespace Google.ProtocolBuffers { public class TextFormatTest { private static readonly string AllFieldsSetText = TestResources.text_format_unittest_data; private static readonly string AllExtensionsSetText = TestResources.text_format_unittest_extensions_data; /// <summary> /// Note that this is slightly different to the Java - 123.0 becomes 123, and 1.23E17 becomes 1.23E+17. /// Both of these differences can be parsed by the Java and the C++, and we can parse their output too. /// </summary> private const string ExoticText = "repeated_int32: -1\n" + "repeated_int32: -2147483648\n" + "repeated_int64: -1\n" + "repeated_int64: -9223372036854775808\n" + "repeated_uint32: 4294967295\n" + "repeated_uint32: 2147483648\n" + "repeated_uint64: 18446744073709551615\n" + "repeated_uint64: 9223372036854775808\n" + "repeated_double: 123\n" + "repeated_double: 123.5\n" + "repeated_double: 0.125\n" + "repeated_double: 1.23E+17\n" + "repeated_double: 1.235E+22\n" + "repeated_double: 1.235E-18\n" + "repeated_double: 123.456789\n" + "repeated_double: Infinity\n" + "repeated_double: -Infinity\n" + "repeated_double: NaN\n" + "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" + "\\341\\210\\264\"\n" + "repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n"; private const string MessageSetText = "[protobuf_unittest.TestMessageSetExtension1] {\n" + " i: 123\n" + "}\n" + "[protobuf_unittest.TestMessageSetExtension2] {\n" + " str: \"foo\"\n" + "}\n"; /// <summary> /// Print TestAllTypes and compare with golden file. /// </summary> [Test] public void PrintMessage() { TestUtil.TestInMultipleCultures(() => { string text = TextFormat.PrintToString(TestUtil.GetAllSet()); Assert.AreEqual(AllFieldsSetText.Replace("\r\n", "\n").Trim(), text.Replace("\r\n", "\n").Trim()); }); } /// <summary> /// Tests that a builder prints the same way as a message. /// </summary> [Test] public void PrintBuilder() { TestUtil.TestInMultipleCultures(() => { string messageText = TextFormat.PrintToString(TestUtil.GetAllSet()); string builderText = TextFormat.PrintToString(TestUtil.GetAllSet().ToBuilder()); Assert.AreEqual(messageText, builderText); }); } /// <summary> /// Print TestAllExtensions and compare with golden file. /// </summary> [Test] public void PrintExtensions() { string text = TextFormat.PrintToString(TestUtil.GetAllExtensionsSet()); Assert.AreEqual(AllExtensionsSetText.Replace("\r\n", "\n").Trim(), text.Replace("\r\n", "\n").Trim()); } /// <summary> /// Test printing of unknown fields in a message. /// </summary> [Test] public void PrintUnknownFields() { TestEmptyMessage message = TestEmptyMessage.CreateBuilder() .SetUnknownFields( UnknownFieldSet.CreateBuilder() .AddField(5, UnknownField.CreateBuilder() .AddVarint(1) .AddFixed32(2) .AddFixed64(3) .AddLengthDelimited(ByteString.CopyFromUtf8("4")) .AddGroup( UnknownFieldSet.CreateBuilder() .AddField(10, UnknownField.CreateBuilder() .AddVarint(5) .Build()) .Build()) .Build()) .AddField(8, UnknownField.CreateBuilder() .AddVarint(1) .AddVarint(2) .AddVarint(3) .Build()) .AddField(15, UnknownField.CreateBuilder() .AddVarint(0xABCDEF1234567890L) .AddFixed32(0xABCD1234) .AddFixed64(0xABCDEF1234567890L) .Build()) .Build()) .Build(); Assert.AreEqual( "5: 1\n" + "5: 0x00000002\n" + "5: 0x0000000000000003\n" + "5: \"4\"\n" + "5 {\n" + " 10: 5\n" + "}\n" + "8: 1\n" + "8: 2\n" + "8: 3\n" + "15: 12379813812177893520\n" + "15: 0xabcd1234\n" + "15: 0xabcdef1234567890\n", TextFormat.PrintToString(message)); } /// <summary> /// Helper to construct a ByteString from a string containing only 8-bit /// characters. The characters are converted directly to bytes, *not* /// encoded using UTF-8. /// </summary> private static ByteString Bytes(string str) { byte[] bytes = new byte[str.Length]; for (int i = 0; i < bytes.Length; i++) bytes[i] = (byte)str[i]; return ByteString.CopyFrom(bytes); } [Test] public void PrintExotic() { IMessage message = TestAllTypes.CreateBuilder() // Signed vs. unsigned numbers. .AddRepeatedInt32(-1) .AddRepeatedUint32(uint.MaxValue) .AddRepeatedInt64(-1) .AddRepeatedUint64(ulong.MaxValue) .AddRepeatedInt32(1 << 31) .AddRepeatedUint32(1U << 31) .AddRepeatedInt64(1L << 63) .AddRepeatedUint64(1UL << 63) // Floats of various precisions and exponents. .AddRepeatedDouble(123) .AddRepeatedDouble(123.5) .AddRepeatedDouble(0.125) .AddRepeatedDouble(123e15) .AddRepeatedDouble(123.5e20) .AddRepeatedDouble(123.5e-20) .AddRepeatedDouble(123.456789) .AddRepeatedDouble(Double.PositiveInfinity) .AddRepeatedDouble(Double.NegativeInfinity) .AddRepeatedDouble(Double.NaN) // Strings and bytes that needing escaping. .AddRepeatedString("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u1234") .AddRepeatedBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u00fe")) .Build(); Assert.AreEqual(ExoticText, message.ToString()); } [Test] public void PrintMessageSet() { TestMessageSet messageSet = TestMessageSet.CreateBuilder() .SetExtension( TestMessageSetExtension1.MessageSetExtension, TestMessageSetExtension1.CreateBuilder().SetI(123).Build()) .SetExtension( TestMessageSetExtension2.MessageSetExtension, TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build()) .Build(); Assert.AreEqual(MessageSetText, messageSet.ToString()); } // ================================================================= [Test] public void Parse() { TestUtil.TestInMultipleCultures(() => { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge(AllFieldsSetText, builder); TestUtil.AssertAllFieldsSet(builder.Build()); }); } [Test] public void ParseReader() { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge(new StringReader(AllFieldsSetText), builder); TestUtil.AssertAllFieldsSet(builder.Build()); } [Test] public void ParseExtensions() { TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); TextFormat.Merge(AllExtensionsSetText, TestUtil.CreateExtensionRegistry(), builder); TestUtil.AssertAllExtensionsSet(builder.Build()); } [Test] public void ParseCompatibility() { string original = "repeated_float: inf\n" + "repeated_float: -inf\n" + "repeated_float: nan\n" + "repeated_float: inff\n" + "repeated_float: -inff\n" + "repeated_float: nanf\n" + "repeated_float: 1.0f\n" + "repeated_float: infinityf\n" + "repeated_float: -Infinityf\n" + "repeated_double: infinity\n" + "repeated_double: -infinity\n" + "repeated_double: nan\n"; string canonical = "repeated_float: Infinity\n" + "repeated_float: -Infinity\n" + "repeated_float: NaN\n" + "repeated_float: Infinity\n" + "repeated_float: -Infinity\n" + "repeated_float: NaN\n" + "repeated_float: 1\n" + // Java has 1.0; this is fine "repeated_float: Infinity\n" + "repeated_float: -Infinity\n" + "repeated_double: Infinity\n" + "repeated_double: -Infinity\n" + "repeated_double: NaN\n"; TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge(original, builder); Assert.AreEqual(canonical, builder.Build().ToString()); } [Test] public void ParseExotic() { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge(ExoticText, builder); // Too lazy to check things individually. Don't try to debug this // if testPrintExotic() is Assert.Failing. Assert.AreEqual(ExoticText, builder.Build().ToString()); } [Test] public void ParseMessageSet() { ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance(); extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension); extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension); TestMessageSet.Builder builder = TestMessageSet.CreateBuilder(); TextFormat.Merge(MessageSetText, extensionRegistry, builder); TestMessageSet messageSet = builder.Build(); Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension1.MessageSetExtension)); Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I); Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension2.MessageSetExtension)); Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str); } [Test] public void ParseNumericEnum() { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge("optional_nested_enum: 2", builder); Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, builder.OptionalNestedEnum); } [Test] public void ParseAngleBrackets() { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge("OptionalGroup: < a: 1 >", builder); Assert.IsTrue(builder.HasOptionalGroup); Assert.AreEqual(1, builder.OptionalGroup.A); } [Test] public void ParseComment() { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); TextFormat.Merge( "# this is a comment\n" + "optional_int32: 1 # another comment\n" + "optional_int64: 2\n" + "# EOF comment", builder); Assert.AreEqual(1, builder.OptionalInt32); Assert.AreEqual(2, builder.OptionalInt64); } private static void AssertParseError(string error, string text) { TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); Exception exception = Assert.Throws<FormatException>(() => TextFormat.Merge(text, TestUtil.CreateExtensionRegistry(), builder)); Assert.AreEqual(error, exception.Message); } [Test] public void ParseErrors() { AssertParseError( "1:16: Expected \":\".", "optional_int32 123"); AssertParseError( "1:23: Expected identifier.", "optional_nested_enum: ?"); AssertParseError( "1:18: Couldn't parse integer: Number must be positive: -1", "optional_uint32: -1"); AssertParseError( "1:17: Couldn't parse integer: Number out of range for 32-bit signed " + "integer: 82301481290849012385230157", "optional_int32: 82301481290849012385230157"); AssertParseError( "1:16: Expected \"true\" or \"false\".", "optional_bool: maybe"); AssertParseError( "1:18: Expected string.", "optional_string: 123"); AssertParseError( "1:18: String missing ending quote.", "optional_string: \"ueoauaoe"); AssertParseError( "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\n" + "optional_int32: 123"); AssertParseError( "1:18: Invalid escape sequence: '\\z'", "optional_string: \"\\z\""); AssertParseError( "1:18: String missing ending quote.", "optional_string: \"ueoauaoe\n" + "optional_int32: 123"); AssertParseError( "1:2: Extension \"nosuchext\" not found in the ExtensionRegistry.", "[nosuchext]: 123"); AssertParseError( "1:20: Extension \"protobuf_unittest.optional_int32_extension\" " + "not found in the ExtensionRegistry.", "[protobuf_unittest.optional_int32_extension]: 123"); AssertParseError( "1:1: Message type \"protobuf_unittest.TestAllTypes\" has no field " + "named \"nosuchfield\".", "nosuchfield: 123"); AssertParseError(
[ " \"1:21: Expected \\\">\\\".\"," ]
1,187
lcc
csharp
null
2be88ed1d82791123566d7fc244876523ea87a620301c93a
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, 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 distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.collection.internal; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.loader.CollectionAliases; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.type.Type; /** * A persistent wrapper for a <tt>java.util.Map</tt>. Underlying collection * is a <tt>HashMap</tt>. * * @see java.util.HashMap * @author Gavin King */ public class PersistentMap extends AbstractPersistentCollection implements Map { protected Map map; /** * Empty constructor. * <p/> * Note: this form is not ever ever ever used by Hibernate; it is, however, * needed for SOAP libraries and other such marshalling code. */ public PersistentMap() { // intentionally empty } /** * Instantiates a lazy map (the underlying map is un-initialized). * * @param session The session to which this map will belong. */ public PersistentMap(SessionImplementor session) { super( session ); } /** * Instantiates a non-lazy map (the underlying map is constructed * from the incoming map reference). * * @param session The session to which this map will belong. * @param map The underlying map data. */ public PersistentMap(SessionImplementor session, Map map) { super( session ); this.map = map; setInitialized(); setDirectlyAccessible( true ); } @Override @SuppressWarnings( {"unchecked"}) public Serializable getSnapshot(CollectionPersister persister) throws HibernateException { final HashMap clonedMap = new HashMap( map.size() ); for ( Object o : map.entrySet() ) { final Entry e = (Entry) o; final Object copy = persister.getElementType().deepCopy( e.getValue(), persister.getFactory() ); clonedMap.put( e.getKey(), copy ); } return clonedMap; } @Override public Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException { final Map sn = (Map) snapshot; return getOrphans( sn.values(), map.values(), entityName, getSession() ); } @Override public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException { final Type elementType = persister.getElementType(); final Map snapshotMap = (Map) getSnapshot(); if ( snapshotMap.size() != this.map.size() ) { return false; } for ( Object o : map.entrySet() ) { final Entry entry = (Entry) o; if ( elementType.isDirty( entry.getValue(), snapshotMap.get( entry.getKey() ), getSession() ) ) { return false; } } return true; } @Override public boolean isSnapshotEmpty(Serializable snapshot) { return ( (Map) snapshot ).isEmpty(); } @Override public boolean isWrapper(Object collection) { return map==collection; } @Override public void beforeInitialize(CollectionPersister persister, int anticipatedSize) { this.map = (Map) persister.getCollectionType().instantiate( anticipatedSize ); } @Override public int size() { return readSize() ? getCachedSize() : map.size(); } @Override public boolean isEmpty() { return readSize() ? getCachedSize()==0 : map.isEmpty(); } @Override public boolean containsKey(Object key) { final Boolean exists = readIndexExistence( key ); return exists == null ? map.containsKey( key ) : exists; } @Override public boolean containsValue(Object value) { final Boolean exists = readElementExistence( value ); return exists == null ? map.containsValue( value ) : exists; } @Override public Object get(Object key) { final Object result = readElementByIndex( key ); return result == UNKNOWN ? map.get( key ) : result; } @Override @SuppressWarnings("unchecked") public Object put(Object key, Object value) { if ( isPutQueueEnabled() ) { final Object old = readElementByIndex( key ); if ( old != UNKNOWN ) { queueOperation( new Put( key, value, old ) ); return old; } } initialize( true ); final Object old = map.put( key, value ); // would be better to use the element-type to determine // whether the old and the new are equal here; the problem being // we do not necessarily have access to the element type in all // cases if ( value != old ) { dirty(); } return old; } @Override @SuppressWarnings("unchecked") public Object remove(Object key) { if ( isPutQueueEnabled() ) { final Object old = readElementByIndex( key ); if ( old != UNKNOWN ) { queueOperation( new Remove( key, old ) ); return old; } } // TODO : safe to interpret "map.remove(key) == null" as non-dirty? initialize( true ); if ( map.containsKey( key ) ) { dirty(); }
[ "\t\treturn map.remove( key );" ]
794
lcc
java
null
b68fb107dd4b16b9e62aee193e5d5452796850436d17aaef
#region AuthorHeader // // Auction version 2.1, by Xanthos and Arya // // Based on original ideas and code by Arya // #endregion AuthorHeader using System; using System.IO; using Server; namespace Arya.Auction { /// <summary> /// Summary description for AuctionLog. /// </summary> public class AuctionLog { private static StreamWriter m_Writer; private static bool m_Enabled = false; public static void Initialize() { if ( AuctionSystem.Running && AuctionConfig.EnableLogging ) { // Create the log writer try { string folder = Path.Combine( Core.BaseDirectory, @"Logs\Auction" ); if ( ! Directory.Exists( folder ) ) Directory.CreateDirectory( folder ); string name = string.Format( "{0}.txt", DateTime.UtcNow.ToLongDateString() ); string file = Path.Combine( folder, name ); m_Writer = new StreamWriter( file, true ); m_Writer.AutoFlush = true; m_Writer.WriteLine( "###############################" ); m_Writer.WriteLine( "# {0} - {1}", DateTime.UtcNow.ToShortDateString(), DateTime.UtcNow.ToShortTimeString() ); m_Writer.WriteLine(); m_Enabled = true; } catch ( Exception err ) { Console.WriteLine( "Couldn't initialize auction system log. Reason:" ); Console.WriteLine( err.ToString() ); m_Enabled = false; } } } /// <summary> /// Records the creation of a new auction item /// </summary> /// <param name="auction">The new auction</param> public static void WriteNewAuction( AuctionItem auction ) { if ( !m_Enabled || m_Writer == null ) return; try { m_Writer.WriteLine( "## New Auction : {0}", auction.ID ); m_Writer.WriteLine( "# {0}", auction.ItemName ); m_Writer.WriteLine( "# Created on {0} at {1}", DateTime.UtcNow.ToShortDateString(), DateTime.UtcNow.ToShortTimeString() ); m_Writer.WriteLine( "# Owner : {0} [{1}] Account: {2}", auction.Owner.Name, auction.Owner.Serial.ToString(), auction.Account.Username ); m_Writer.WriteLine( "# Expires on {0} at {1}", auction.EndTime.ToShortDateString(), auction.EndTime.ToShortTimeString() ); m_Writer.WriteLine( "# Starting Bid: {0}. Reserve: {1}. Buy Now: {2}", auction.MinBid, auction.Reserve, auction.AllowBuyNow ? auction.BuyNow.ToString() : "Disabled" ); m_Writer.WriteLine( "# Owner Description : {0}", auction.Description ); m_Writer.WriteLine( "# Web Link : {0}", auction.WebLink != null ? auction.WebLink : "N/A" ); if ( auction.Creature ) { // Selling a pet m_Writer.WriteLine( "#### Selling 1 Creature" ); m_Writer.WriteLine( "# Type : {0}. Serial : {1}. Name : {2} Hue : {3}", auction.Pet.GetType().Name, auction.Pet.Serial.ToString(), auction.Pet.Name != null ? auction.Pet.Name : "Unnamed", auction.Pet.Hue ); m_Writer.WriteLine( "# Statuette Serial : {0}", auction.Item.Serial.ToString() ); m_Writer.WriteLine( "# Properties: {0}", auction.Items[ 0 ].Properties ); } else { // Selling items m_Writer.WriteLine( "#### Selling {0} Items", auction.ItemCount ); for ( int i = 0; i < auction.ItemCount; i++ ) { AuctionItem.ItemInfo info = auction.Items[ i ]; m_Writer.WriteLine( "# {0}. {1} [{2}] Type {3} Hue {4}", i, info.Name, info.Item.Serial, info.Item.GetType().Name, info.Item.Hue ); m_Writer.WriteLine( "Properties: {0}", info.Properties ); } } m_Writer.WriteLine(); } catch {} } /// <summary> /// Writes the current highest bid in an auction /// </summary> /// <param name="auction">The auction corresponding to the bid</param> public static void WriteBid( AuctionItem auction ) { if ( !m_Enabled || m_Writer == null ) return; try { m_Writer.WriteLine( "> [{0}] Bid Amount : {1}, Mobile : {2} [{3}] Account : {4}", auction.ID.ToString(), auction.HighestBidValue.ToString("#,0" ), auction.HighestBidder.Name, auction.HighestBidder.Serial.ToString(), ( auction.HighestBidder.Account as Server.Accounting.Account ).Username ); } catch {} } /// <summary> /// Changes the /// </summary> /// <param name="auction">The auction switching to pending</param> /// <param name="reason">The reason why the auction is set to pending</param> public static void WritePending( AuctionItem auction, string reason ) { if ( !m_Enabled || m_Writer == null ) return; try { m_Writer.WriteLine( "] [{0}] Becoming Pending on {1} at {2}. Reason : {3}", auction.ID.ToString(), DateTime.UtcNow.ToShortDateString(), DateTime.UtcNow.ToShortTimeString(), reason ); } catch {} } /// <summary> /// Writes the end of the auction to the log /// </summary> /// <param name="auction">The auction ending</param> /// <param name="reason">The AuctionResult stating why the auction is ending</param> /// <param name="m">The Mobile forcing the end of the auction (can be null)</param> /// <param name="comments">Additional comments on the ending (can be null)</param> public static void WriteEnd( AuctionItem auction, AuctionResult reason, Mobile m, string comments ) { if ( !m_Enabled || m_Writer == null ) return; try { m_Writer .WriteLine( "## Ending Auction {0}", auction.ID.ToString() ); m_Writer .WriteLine( "# Status : {0}", reason.ToString() ); if ( m != null ) m_Writer .WriteLine( "# Ended by {0} [{1}], {2}, Account : {3}", m.Name, m.Serial.ToString(), m.AccessLevel.ToString(), ( m.Account as Server.Accounting.Account ).Username ); if ( comments != null ) m_Writer .WriteLine( "# Comments : {0}", comments ); m_Writer .WriteLine(); } catch {} } /// <summary> /// Records a staff member viewing an item /// </summary> /// <param name="auction">The auction item</param> /// <param name="m">The mobile viewing the item</param> public static void WriteViewItem( AuctionItem auction, Mobile m ) { if ( !m_Enabled || m_Writer == null ) return; try { m_Writer .WriteLine( "} Vieweing item [{0}] Mobile: {1} [2], {3}, Account : {4}", auction.ID.ToString(), m.Name, m.Serial.ToString(), m.AccessLevel.ToString(), ( m.Account as Server.Accounting.Account ).Username ); } catch {} } /// <summary> /// Records a staff member returning an item /// </summary> /// <param name="auction">The auction</param> /// <param name="m">The mobile returning the item</param> public static void WriteReturnItem( AuctionItem auction, Mobile m ) { if ( !m_Enabled || m_Writer == null ) return; try { m_Writer .WriteLine( "} Returning item [{0}] Mobile: {1} [2], {3}, Account : {4}", auction.ID.ToString(), m.Name, m.Serial.ToString(), m.AccessLevel.ToString(),
[ "\t\t\t\t\t( m.Account as Server.Accounting.Account ).Username );" ]
805
lcc
csharp
null
3eb19d43291f949e184ce7a5465a8640ad3cc4cd277ab5ce
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2016 - now Bytebrand Outsourcing AG (<http://www.bytebrand.net>). # # This program 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 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 Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from random import choice from string import digits import logging from odoo import exceptions, SUPERUSER_ID from datetime import date from odoo import api, fields, models, _ from odoo.exceptions import ValidationError _logger = logging.getLogger(__name__) class HrEmployee(models.Model): _inherit = "hr.employee" _description = "Employee" @api.multi def _compute_timesheet_count(self): for employee in self: employee.timesheet_count = employee.env[ 'hr_timesheet_sheet.sheet'].search_count( [('employee_id', '=', employee.id)]) def _default_random_pin(self): return ("".join(choice(digits) for i in range(4))) def _default_random_barcode(self): barcode = None while not barcode or self.env['hr.employee'].search( [('barcode', '=', barcode)]): barcode = "".join(choice(digits) for i in range(8)) return barcode timesheet_count = fields.Integer(compute='_compute_timesheet_count', string='Timesheets') barcode = fields.Char(string="Badge ID", help="ID used for employee identification.", default=_default_random_barcode, copy=False) pin = fields.Char(string="PIN", default=_default_random_pin, help="PIN used to Check In/Out in Kiosk Mode " "(if enabled in Configuration).", copy=False) attendance_ids = fields.One2many('hr.attendance', 'employee_id', string="Attendances", help='list of attendances for the employee') last_attendance_id = fields.Many2one('hr.attendance', compute='_compute_last_attendance_id') attendance_state = fields.Selection( string="Attendance", compute='_compute_attendance_state', selection=[('checked_out', "Checked out"), ('checked_in', "Checked in")]) manual_attendance = fields.Boolean( string='Manual Attendance', compute='_compute_manual_attendance', inverse='_inverse_manual_attendance', help='The employee will have access to the "My Attendances" ' 'menu to check in and out from his session') start_time_different = fields.Float(string='Start Time Different', default=0.00) _sql_constraints = [('barcode_uniq', 'unique (barcode)', "The Badge ID must be unique, this one is " "already assigned to another employee.")] start_overtime_different = fields.Integer(string='Start Overtime Count', default=0.00) @api.multi def _compute_manual_attendance(self): for employee in self: employee.manual_attendance = employee.user_id.has_group( 'hr_attendance.group_hr_attendance') \ if employee.user_id else False @api.multi def _inverse_manual_attendance(self): manual_attendance_group = self.env.ref( 'hr_attendance.group_hr_attendance') for employee in self: if employee.user_id: if employee.manual_attendance: manual_attendance_group.users = [ (4, employee.user_id.id, 0)] else: manual_attendance_group.users = [ (3, employee.user_id.id, 0)] @api.depends('attendance_ids') def _compute_last_attendance_id(self): for employee in self: employee.last_attendance_id = employee.attendance_ids \ and employee.attendance_ids[ 0] or False @api.one def initial_overtime(self): """ Checks if timezone is set for each user. Checks if each employee has related user. Rewrites all attendances of current employee to initialise recalculation of bonus, night shift worked hours. """ if not self.user_id: raise ValidationError(_("Employee must have related user.")) if not self.user_id.tz: raise ValidationError(_("Timezone for {user} is not set.".format( user=self.user_id.name))) attendances = self.env['hr.attendance'].search( [('employee_id', '=', self.id)]) for attendance in attendances: attendance.write({'check_out': attendance.check_out}) @api.depends('last_attendance_id.check_in', 'last_attendance_id.check_out', 'last_attendance_id') def _compute_attendance_state(self): for employee in self: employee.attendance_state = ( employee.last_attendance_id and not employee.last_attendance_id.check_out and 'checked_in' or 'checked_out') @api.constrains('pin') def _verify_pin(self): for employee in self: if employee.pin and not employee.pin.isdigit(): raise exceptions.ValidationError( _("The PIN must be a sequence of digits.")) @api.model def attendance_scan(self, barcode): """ Receive a barcode scanned from the Kiosk Mode and change the attendances of corresponding employee. Returns either an action or a warning. """ employee = self.search([('barcode', '=', barcode)], limit=1) return employee and employee.attendance_action( 'hr_attendance.hr_attendance_action_kiosk_mode') or \ {'warning': _('No employee corresponding to ' 'barcode %(barcode)s') % {'barcode': barcode}} @api.multi def attendance_manual(self, next_action, entered_pin=None): self.ensure_one() if not (entered_pin is None) or self.env['res.users'].browse( SUPERUSER_ID).has_group( 'hr_attendance.group_hr_attendance_use_pin') \ and (self.user_id and self.user_id.id != self._uid or not self.user_id): if entered_pin != self.pin: return {'warning': _('Wrong PIN')} ctx = self.env.context.copy() ctx['attendance_manual'] = True return self.with_context(ctx).attendance_action(next_action) @api.multi def attendance_action(self, next_action): """ Changes the attendance of the employee. Returns an action to the check in/out message, next_action defines which menu the check in/out message should return to. ("My Attendances" or "Kiosk Mode") """ self.ensure_one() action_message = self.env.ref( 'hr_attendance.hr_attendance_action_greeting_message').read()[0] action_message['previous_attendance_change_date'] = ( self.last_attendance_id and (self.last_attendance_id.check_out or self.last_attendance_id.check_in) or False) if action_message['previous_attendance_change_date']: action_message['previous_attendance_change_date'] = \ fields.Datetime.to_string(fields.Datetime.context_timestamp( self, fields.Datetime.from_string( action_message['previous_attendance_change_date']))) action_message['employee_name'] = self.name action_message['next_action'] = next_action if self.user_id: modified_attendance = self.sudo( self.user_id.id).attendance_action_change() else: modified_attendance = self.sudo().attendance_action_change() action_message['attendance'] = modified_attendance.read()[0]
[ " return {'action': action_message}" ]
686
lcc
python
null
774c2fcb277e8f0e9c0b13c51982a14cc5f1ec168baf9c7e
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# 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/>. # //# # //############################################################################# //#EOH // This code was generated by Daniel Laffan using IMS Development Environment (version 1.65 build 3163.31063) // Copyright (C) 1995-2008 IMS MAXIMS plc. All rights reserved. package ims.ocrr.forms.investigationscomponent; import ims.ocrr.forms.investigationscomponent.GenForm.grdResultsRow; import ims.ocrr.forms.investigationscomponent.GenForm.grdResultsRowCollection; import ims.configuration.gen.ConfigFlag; import ims.domain.exceptions.DomainInterfaceException; import ims.framework.exceptions.CodingRuntimeException; import ims.framework.utils.Color; import ims.framework.utils.Date; import ims.framework.utils.DateTime; import ims.framework.utils.Image; import ims.ocrr.vo.OcsPathRadResultVo; import ims.ocrr.vo.OcsPathRadResultVoCollection; import ims.ocrr.vo.OrderInvestigationLiteVo; import ims.ocrr.vo.OrderInvestigationLiteVoCollection; import ims.ocrr.vo.OrderSpecimenLiteVo; import ims.ocrr.vo.OrderSpecimenLiteVoCollection; import ims.ocrr.vo.OrderedInvestigationStatusVo; import ims.ocrr.vo.lookups.OrderInvStatus; public class Logic extends BaseLogic { private static final long serialVersionUID = 1L; //----------------------------------------------------------------------------------------------------------------------------------------- // Component interface methods below here //----------------------------------------------------------------------------------------------------------------------------------------- /** * WDEV-13944 * Initialise component (decide to list investigation for selected referral or all referrals) */ public void initialise(Boolean canViewConfidentialInvsResults, Boolean canViewConfidentialInvsOrdered) { if(canViewConfidentialInvsOrdered == null || canViewConfidentialInvsResults == null) throw new CodingRuntimeException("mandatory params are null in method initialise"); form.getLocalContext().setcanViewConfidentialInvsResults(canViewConfidentialInvsResults); form.getLocalContext().setcanViewConfidentialInvsOrdered(canViewConfidentialInvsOrdered); populateScreenFromData(); } //----------------------------------------------------------------------------------------------------------------------------------------- protected void onFormOpen(Object[] args) throws ims.framework.exceptions.PresentationLogicException { } /** * WDEV-13944 * Function used to populate screen with investigation * Component might be used in more than one form - that is why is populating based on parameter */ private void populateScreenFromData() { form.grdResults().getRows().clear(); form.grdResults().setReadOnly(false); OrderInvestigationLiteVoCollection results; try { results = domain.listResults(form.getGlobalContext().Core.getPatientShort()); } catch (DomainInterfaceException e) { updateTotal(); engine.showMessage(e.getMessage()); return; } if (results == null || results.size() == 0) { updateTotal(); return; } Integer nNewResUnseenDays = new Integer(ConfigFlag.DOM.OCS_NEWRES_UNSEEN_CUTOFF.getValue()); Date dateUnseen = new Date().addDay(-1 * nNewResUnseenDays.intValue()); for (int x = 0; x < results.size(); x++) { addResult(results.get(x), dateUnseen); } cleanUpResultGrid(); updateTotal(); } private void updateTotal() { StringBuffer total = new StringBuffer(); total.append("<b>"); total.append("Total: "); total.append(form.grdResults().getRows().size()); total.append("</b>"); form.grdResults().setFooterValue(total.toString()); } /** * if there are any parent rows with no children - remove them ie. there are * no viewable results for this specimen - WDEV-3953 */ private void cleanUpResultGrid() { grdResultsRow pRow; for (int i = form.grdResults().getRows().size(); i > 0; i--) { pRow = form.grdResults().getRows().get(i - 1); if (pRow.getRows().size() == 0 && pRow.getColTestName() == null) form.grdResults().getRows().remove(i - 1); } } private void addResult(OrderInvestigationLiteVo orderInvestigationLiteVo, Date dateUnseen) { if (orderInvestigationLiteVo == null) return; // WDEV-3953 /*boolean isConfidentialInv = orderInvestigationLiteVo.getInvestigationIsNotNull() && orderInvestigationLiteVo.getInvestigation().getInvestigationIndexIsNotNull() && orderInvestigationLiteVo.getInvestigation().getInvestigationIndex().getConfidentialTestIsNotNull() && orderInvestigationLiteVo.getInvestigation().getInvestigationIndex().getConfidentialTest().booleanValue(); if (isConfidentialInv) { if (!form.getLocalContext().getcanViewConfidentialInvsOrdered()) { return; } if (orderInvestigationLiteVo.getPathResultDetailsIsNotNull() || orderInvestigationLiteVo.getRadReportingDetailsIsNotNull()) { if (!form.getLocalContext().getcanViewConfidentialInvsResults()) { return; } } }*/ grdResultsRow parentRow = createOrFindSpecimenGridRow(orderInvestigationLiteVo); if (parentRow == null) return; grdResultsRow row = null; if (parentRow.getColTestName() == null) row = parentRow; else { row = parentRow.getRows().newRow(); row.setSelectable(false); } OcsPathRadResultVo res = new OcsPathRadResultVo(); if(orderInvestigationLiteVo.getInvestigationIsNotNull() && orderInvestigationLiteVo.getInvestigation().getInvestigationIndexIsNotNull()) res.setCategory(orderInvestigationLiteVo.getInvestigation().getInvestigationIndex().getCategory()); res.setOrderInvestigation(orderInvestigationLiteVo); row.setValue(res); // Test Name if (orderInvestigationLiteVo.getInvestigationIsNotNull() && orderInvestigationLiteVo.getInvestigation().getInvestigationIndexIsNotNull() && orderInvestigationLiteVo.getInvestigation().getInvestigationIndex().getNameIsNotNull()) { row.setColTestName(orderInvestigationLiteVo.getInvestigation().getInvestigationIndex().getName()); } // ABN // WDEV-16224 - modifications following OCS DFT model changes if (orderInvestigationLiteVo.getResultDetailsIsNotNull() && orderInvestigationLiteVo.getResultDetails().getPathologyResultDetailsIsNotNull()) { for (int i=0; i<orderInvestigationLiteVo.getResultDetails().getPathologyResultDetails().size(); i++) { if (orderInvestigationLiteVo.getResultDetails().getPathologyResultDetails().get(i).getIsAbnormalIsNotNull() && orderInvestigationLiteVo.getResultDetails().getPathologyResultDetails().get(i).getIsAbnormal().booleanValue()) { row.setColABN(form.getImages().Core.CriticalError); row.setTooltipForColABN("Abnormal Result"); break; } } } // Status if (orderInvestigationLiteVo.getOrdInvCurrentStatusIsNotNull() && orderInvestigationLiteVo.getOrdInvCurrentStatus().getOrdInvStatusIsNotNull()) { OrderInvStatus currStat = orderInvestigationLiteVo.getOrdInvCurrentStatus().getOrdInvStatus(); Image image = currStat.getImage(); String szTooltip = generateStatusTooltip(orderInvestigationLiteVo.getOrdInvCurrentStatus()); if (orderInvestigationLiteVo.getRepDateTimeIsNotNull() && dateUnseen != null) { if (currStat.equals(OrderInvStatus.NEW_RESULT) || currStat.equals(OrderInvStatus.UPDATED_RESULT)) { if (orderInvestigationLiteVo.getRepDateTime().getDate().isLessThan(dateUnseen)) { row.setBold(true); szTooltip = (szTooltip + "<br>Unseen"); } } else if (currStat.equals(OrderInvStatus.REVIEW)) { if (orderInvestigationLiteVo.getOrdInvCurrentStatus().getChangeDateTime().getDate().isLessThan(dateUnseen)) { row.setBold(true); szTooltip = (szTooltip + "<br>Requires Attention"); } else szTooltip = (szTooltip + "<br>" + OrderInvStatus.REVIEW.toString()); } } row.setColStatus(image); row.setTooltipForColStatus(szTooltip); if(orderInvestigationLiteVo.getOrdInvCurrentStatusIsNotNull() && orderInvestigationLiteVo.getOrdInvCurrentStatus().getOrdInvStatusIsNotNull() && (orderInvestigationLiteVo.getOrdInvCurrentStatus().getOrdInvStatus().equals(OrderInvStatus.CANCEL_REQUEST) || orderInvestigationLiteVo.getOrdInvCurrentStatus().getOrdInvStatus().equals(OrderInvStatus.CANCELLED))) row.setBackColor(ConfigFlag.UI.CANCELLED_INVESTIGATION_ROW_COLOUR.getValue()); else row.setBackColor(parentRow.getBackColor()); row.setReadOnly(false); } } private grdResultsRow createOrFindSpecimenGridRow(OrderInvestigationLiteVo orderInvestigationLiteVo) {
[ "\t\tif (orderInvestigationLiteVo == null)" ]
667
lcc
java
null
e0bcde61d9adb5375395d14f33e7ca8fe874d965c734b2ac
/* * ManagedWinapi - A collection of .NET components that wrap PInvoke calls to * access native API by managed code. http://mwinapi.sourceforge.net/ * Copyright (C) 2006 Michael Schierl * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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 library; see the file COPYING. if not, visit * http://www.gnu.org/licenses/lgpl.html or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Drawing; namespace ManagedWinapi.Windows { /// <summary> /// Any list view, including those from other applications. /// </summary> public class SystemListView { /// <summary> /// Get a SystemListView reference from a SystemWindow (which is a list view) /// </summary> public static SystemListView FromSystemWindow(SystemWindow sw) { if (sw.SendGetMessage(LVM_GETITEMCOUNT) == 0) return null; return new SystemListView(sw); } readonly SystemWindow sw; private SystemListView(SystemWindow sw) { this.sw = sw; } /// <summary> /// The number of items (icons) in this list view. /// </summary> public int Count { get { return sw.SendGetMessage(LVM_GETITEMCOUNT); } } /// <summary> /// An item of this list view. /// </summary> public SystemListViewItem this[int index] { get { return this[index, 0]; } } /// <summary> /// A subitem (a column value) of an item of this list view. /// </summary> public SystemListViewItem this[int index, int subIndex] { get { LVITEM lvi = new LVITEM(); lvi.cchTextMax = 300; lvi.iItem = index; lvi.iSubItem = subIndex; lvi.stateMask = 0xffffffff; lvi.mask = LVIF_IMAGE | LVIF_STATE | LVIF_TEXT; ProcessMemoryChunk tc = ProcessMemoryChunk.Alloc(sw.Process, 301); lvi.pszText = tc.Location; ProcessMemoryChunk lc = ProcessMemoryChunk.AllocStruct(sw.Process, lvi); ApiHelper.FailIfZero(SystemWindow.SendMessage(new HandleRef(sw, sw.HWnd), SystemListView.LVM_GETITEM, IntPtr.Zero, lc.Location)); lvi = (LVITEM)lc.ReadToStructure(0, typeof(LVITEM)); lc.Dispose(); if (lvi.pszText != tc.Location) { tc.Dispose(); tc = new ProcessMemoryChunk(sw.Process, lvi.pszText, lvi.cchTextMax); } byte[] tmp = tc.Read(); string title = Encoding.Default.GetString(tmp); if (title.IndexOf('\0') != -1) title = title.Substring(0, title.IndexOf('\0')); int image = lvi.iImage; uint state = lvi.state; tc.Dispose(); return new SystemListViewItem(sw, index, title, state, image); } } /// <summary> /// All columns of this list view, if it is in report view. /// </summary> public SystemListViewColumn[] Columns { get { List<SystemListViewColumn> result = new List<SystemListViewColumn>(); LVCOLUMN lvc = new LVCOLUMN(); lvc.cchTextMax = 300; lvc.mask = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH; ProcessMemoryChunk tc = ProcessMemoryChunk.Alloc(sw.Process, 301); lvc.pszText = tc.Location; ProcessMemoryChunk lc = ProcessMemoryChunk.AllocStruct(sw.Process, lvc); for (int i = 0; ; i++) { IntPtr ok = SystemWindow.SendMessage(new HandleRef(sw, sw.HWnd), LVM_GETCOLUMN, new IntPtr(i), lc.Location); if (ok == IntPtr.Zero) break; lvc = (LVCOLUMN)lc.ReadToStructure(0, typeof(LVCOLUMN)); byte[] tmp = tc.Read(); string title = Encoding.Default.GetString(tmp); if (title.IndexOf('\0') != -1) title = title.Substring(0, title.IndexOf('\0')); result.Add(new SystemListViewColumn(lvc.fmt, lvc.cx, lvc.iSubItem, title)); } tc.Dispose(); lc.Dispose(); return result.ToArray(); } } #region PInvoke Declarations internal static readonly uint LVM_GETITEMRECT = (0x1000 + 14), LVM_SETITEMPOSITION = (0x1000 + 15), LVM_GETITEMPOSITION = (0x1000 + 16), LVM_GETITEMCOUNT = (0x1000 + 4), LVM_GETITEM = 0x1005, LVM_GETCOLUMN = (0x1000 + 25); private static readonly uint LVIF_TEXT = 0x1, LVIF_IMAGE = 0x2, LVIF_STATE = 0x8, LVCF_FMT = 0x1, LVCF_WIDTH = 0x2, LVCF_TEXT = 0x4, LVCF_SUBITEM = 0x8; [StructLayout(LayoutKind.Sequential)] private struct LVCOLUMN { public UInt32 mask; public Int32 fmt; public Int32 cx; public IntPtr pszText; public Int32 cchTextMax; public Int32 iSubItem; } [StructLayout(LayoutKind.Sequential)] private struct LVITEM { public UInt32 mask; public Int32 iItem; public Int32 iSubItem; public UInt32 state; public UInt32 stateMask; public IntPtr pszText; public Int32 cchTextMax; public Int32 iImage; public IntPtr lParam; } #endregion } /// <summary> /// An item of a list view. /// </summary> public class SystemListViewItem { readonly string title; readonly uint state; readonly int image, index; readonly SystemWindow sw; internal SystemListViewItem(SystemWindow sw, int index, string title, uint state, int image) { this.sw = sw; this.index = index; this.title = title; this.state = state; this.image = image; } /// <summary> /// The title of this item /// </summary> public string Title { get { return title; } } /// <summary> /// The index of this item's image in the image list of this list view. /// </summary> public int Image { get { return image; } } /// <summary> /// State bits of this item. /// </summary> public uint State { get { return state; } } /// <summary> /// Position of the upper left corner of this item. /// </summary> public Point Position { get { POINT pt = new POINT(); ProcessMemoryChunk c = ProcessMemoryChunk.AllocStruct(sw.Process, pt); ApiHelper.FailIfZero(SystemWindow.SendMessage(new HandleRef(sw, sw.HWnd), SystemListView.LVM_GETITEMPOSITION, new IntPtr(index), c.Location));
[ " pt = (POINT)c.ReadToStructure(0, typeof(POINT));" ]
808
lcc
csharp
null
faeb4c1f5b91b0308378f17f35d5be9bb0bb461449205814
#!/usr/bin/env python2 # Terminator by Chris Jones <cmsj@tenshu.net> # GPL v2 only """window.py - class for the main Terminator window""" import copy import time import uuid import gi from gi.repository import GObject from gi.repository import Gtk, Gdk, GdkX11 from util import dbg, err, make_uuid, display_manager import util from translation import _ from version import APP_NAME from container import Container from factory import Factory from terminator import Terminator if display_manager() == 'X11': try: gi.require_version('Keybinder', '3.0') from gi.repository import Keybinder Keybinder.init() except (ImportError, ValueError): err('Unable to load Keybinder module. This means the \ hide_window shortcut will be unavailable') # pylint: disable-msg=R0904 class Window(Container, Gtk.Window): """Class implementing a top-level Terminator window""" terminator = None title = None isfullscreen = None ismaximised = None hidebound = None hidefunc = None losefocus_time = 0 position = None ignore_startup_show = None set_pos_by_ratio = None last_active_term = None zoom_data = None term_zoomed = False __gproperties__ = { 'term_zoomed': (GObject.TYPE_BOOLEAN, 'terminal zoomed', 'whether the terminal is zoomed', False, GObject.PARAM_READWRITE) } def __init__(self): """Class initialiser""" self.terminator = Terminator() self.terminator.register_window(self) Container.__init__(self) GObject.GObject.__init__(self) GObject.type_register(Window) self.register_signals(Window) self.get_style_context().add_class("terminator-terminal-window") # self.set_property('allow-shrink', True) # FIXME FOR GTK3, or do we need this actually? icon_to_apply='' self.register_callbacks() self.apply_config() self.title = WindowTitle(self) self.title.update() options = self.config.options_get() if options: if options.forcedtitle: self.title.force_title(options.forcedtitle) if options.role: self.set_role(options.role) # if options.classname is not None: # self.set_wmclass(options.classname, self.wmclass_class) if options.forcedicon is not None: icon_to_apply = options.forcedicon if options.geometry: if not self.parse_geometry(options.geometry): err('Window::__init__: Unable to parse geometry: %s' % options.geometry) self.apply_icon(icon_to_apply) self.pending_set_rough_geometry_hint = False def do_get_property(self, prop): """Handle gobject getting a property""" if prop.name in ['term_zoomed', 'term-zoomed']: return(self.term_zoomed) else: raise AttributeError('unknown property %s' % prop.name) def do_set_property(self, prop, value): """Handle gobject setting a property""" if prop.name in ['term_zoomed', 'term-zoomed']: self.term_zoomed = value else: raise AttributeError('unknown property %s' % prop.name) def register_callbacks(self): """Connect the GTK+ signals we care about""" self.connect('key-press-event', self.on_key_press) self.connect('button-press-event', self.on_button_press) self.connect('delete_event', self.on_delete_event) self.connect('destroy', self.on_destroy_event) self.connect('window-state-event', self.on_window_state_changed) self.connect('focus-out-event', self.on_focus_out) self.connect('focus-in-event', self.on_focus_in) # Attempt to grab a global hotkey for hiding the window. # If we fail, we'll never hide the window, iconifying instead. if self.config['keybindings']['hide_window'] != None: if display_manager() == 'X11': try: self.hidebound = Keybinder.bind( self.config['keybindings']['hide_window'].replace('<Shift>',''), self.on_hide_window) except (KeyError, NameError): pass if not self.hidebound: err('Unable to bind hide_window key, another instance/window has it.') self.hidefunc = self.iconify else: self.hidefunc = self.hide def apply_config(self): """Apply various configuration options""" options = self.config.options_get() maximise = self.config['window_state'] == 'maximise' fullscreen = self.config['window_state'] == 'fullscreen' hidden = self.config['window_state'] == 'hidden' borderless = self.config['borderless'] skiptaskbar = self.config['hide_from_taskbar'] alwaysontop = self.config['always_on_top'] sticky = self.config['sticky'] if options: if options.maximise: maximise = True if options.fullscreen: fullscreen = True if options.hidden: hidden = True if options.borderless: borderless = True self.set_fullscreen(fullscreen) self.set_maximised(maximise) self.set_borderless(borderless) self.set_always_on_top(alwaysontop) self.set_real_transparency() self.set_sticky(sticky) if self.hidebound: self.set_hidden(hidden) self.set_skip_taskbar_hint(skiptaskbar) else: self.set_iconified(hidden) def apply_icon(self, requested_icon): """Set the window icon""" icon_theme = Gtk.IconTheme.get_default() icon_name_list = [APP_NAME] # disable self.wmclass_name, n/a in GTK3 if requested_icon: try: self.set_icon_from_file(requested_icon) return except (NameError, GObject.GError): dbg('Unable to load %s icon as file' % (repr(requested_icon))) icon_name_list.insert(0, requested_icon) for icon_name in icon_name_list: # Test if the icon is available first if icon_theme.lookup_icon(icon_name, 48, 0): self.set_icon_name(icon_name) return # Success! We're done. else: dbg('Unable to load %s icon' % (icon_name)) icon = self.render_icon(Gtk.STOCK_DIALOG_INFO, Gtk.IconSize.BUTTON) self.set_icon(icon) def on_key_press(self, window, event): """Handle a keyboard event""" maker = Factory() self.set_urgency_hint(False) mapping = self.terminator.keybindings.lookup(event) if mapping: dbg('Window::on_key_press: looked up %r' % mapping) if mapping == 'full_screen': self.set_fullscreen(not self.isfullscreen) elif mapping == 'close_window': if not self.on_delete_event(window, Gdk.Event.new(Gdk.EventType.DELETE)): self.on_destroy_event(window, Gdk.Event.new(Gdk.EventType.DESTROY)) else: return(False) return(True) def on_button_press(self, window, event): """Handle a mouse button event. Mainly this is just a clean way to cancel any urgency hints that are set.""" self.set_urgency_hint(False) return(False) def on_focus_out(self, window, event): """Focus has left the window""" for terminal in self.get_visible_terminals(): terminal.on_window_focus_out() self.losefocus_time = time.time() if self.config['hide_on_lose_focus'] and self.get_property('visible'): self.position = self.get_position() self.hidefunc() def on_focus_in(self, window, event): """Focus has entered the window""" self.set_urgency_hint(False) if not self.terminator.doing_layout: self.terminator.last_active_window = self.uuid # FIXME: Cause the terminal titlebars to update here def is_child_notebook(self): """Returns True if this Window's child is a Notebook""" maker = Factory() return(maker.isinstance(self.get_child(), 'Notebook')) def tab_new(self, widget=None, debugtab=False, _param1=None, _param2=None): """Make a new tab""" cwd = None profile = None if self.get_property('term_zoomed') == True: err("You can't create a tab while a terminal is maximised/zoomed") return if widget: cwd = widget.get_cwd() profile = widget.get_profile() maker = Factory()
[ " if not self.is_child_notebook():" ]
689
lcc
python
null
febfe4f9eeaaa6cc696611fb0204abdaa2ec61fd7fcb43fa
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using AutoJIT.Contrib; using AutoJITRuntime.Exceptions; using AutoJITRuntime.Variants; using IndexOutOfRangeException = AutoJITRuntime.Exceptions.IndexOutOfRangeException; namespace AutoJITRuntime.Services { public class MarshalService { private readonly Dictionary<string, Type> _delegateStore = new Dictionary<string, Type>(); private readonly ModuleBuilder _dynamicMod; private readonly Dictionary<string, UnmanagedType> _marshalAttributeMapping = new Dictionary<string, UnmanagedType> { { "STR", UnmanagedType.LPStr }, { "WSTR", UnmanagedType.LPWStr } }; private readonly Dictionary<string, Type> _structStore = new Dictionary<string, Type>(); private readonly Dictionary<string, Type> _typeMapping = new Dictionary<string, Type> { { "NONE", typeof (void) }, { "BYTE", typeof (byte) }, { "BOOLEAN", typeof (byte) }, { "CHAR", typeof (char) }, { "WCHAR", typeof (char) }, { "SHORT", typeof (Int16) }, { "USHORT", typeof (UInt16) }, { "WORD", typeof (UInt16) }, { "INT", typeof (Int32) }, { "LONG", typeof (Int32) }, { "BOOL", typeof (Int32) }, { "UINT", typeof (UInt32) }, { "ULONG", typeof (UInt32) }, { "DWORD", typeof (UInt32) }, { "INT64", typeof (Int64) }, { "UINT64", typeof (UInt64) }, { "PTR", typeof (IntPtr) }, { "HWND", typeof (IntPtr) }, { "HANDLE", typeof (IntPtr) }, { "FLOAT", typeof (Single) }, { "DOUBLE", typeof (double) }, { "INT_PTR", typeof (IntPtr) }, { "LONG_PTR", typeof (IntPtr) }, { "LRESULT", typeof (IntPtr) }, { "LPARAM", typeof (IntPtr) }, { "UINT_PTR", typeof (UIntPtr) }, { "ULONG_PTR", typeof (UIntPtr) }, { "DWORD_PTR", typeof (UIntPtr) }, { "WPARAM", typeof (UIntPtr) }, { "WSTR", typeof (StringBuilder) }, { "STR", typeof (StringBuilder) } }; public MarshalService() { AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( "an" ), AssemblyBuilderAccess.Run ); _dynamicMod = assemblyBuilder.DefineDynamicModule( "MainModule" ); } [DllImport( "kernel32.dll", SetLastError = true )] public static extern IntPtr LoadLibrary( string dllToLoad ); [DllImport( "kernel32.dll", SetLastError = true )] public static extern IntPtr GetProcAddress( IntPtr hModule, string procedureName ); [DllImport( "kernel32.dll", SetLastError = true )] public static extern bool FreeLibrary( IntPtr hModule ); [DllImport( "user32.dll" )] [return: MarshalAs( UnmanagedType.Bool )] public static extern bool IsWindow( IntPtr hWnd ); public Variant DllCall( Variant dll, string returnType, string function, Variant[] paramtypen ) { Variant handle; if ( dll.IsPtr ) { handle = dll.GetIntPtr(); } else { handle = DllOpen( dll ); if ( !handle.IsPtr ) { throw new UnableToUseTheDllFileException( 1, null, string.Empty ); } } IntPtr procAddress = GetProcAddress( handle, function ); Variant toReturn = DllCallAddressInternal( returnType, procAddress, paramtypen ); if ( dll.IsPtr ) { return toReturn; } DllClose( handle ); return toReturn; } public Variant DllCallAddress( Variant returntype, Variant address, Variant[] paramtypen ) { if ( !address.IsPtr ) { throw new AddressParameterIsNotAPointerException( 1, null, string.Empty ); } IntPtr ptr = address.GetIntPtr(); string returnType = returntype.GetString(); return DllCallAddressInternal( returnType, ptr, paramtypen ); } private Variant DllCallAddressInternal( string returnType, IntPtr ptr, Variant[] paramtypen ) { if ( ptr == IntPtr.Zero ) { throw new ProcAddressZeroException( 3, null, string.Empty ); } List<MarshalInfo> parameterMarshalInfo = GetParameterInfo( paramtypen ); Type callingConvention = typeof (CallConvStdcall); if ( returnType.Contains( ":" ) ) { string[] split = returnType.Split( ':' ); string customCallingConvention = split[1]; returnType = split[0]; callingConvention = GetCallingConvention( customCallingConvention ); } MarshalInfo returnMarshalInfo = GetReturnTypeInfo( returnType ); Delegate @delegate = GetFunctionDelegate( returnMarshalInfo, parameterMarshalInfo, callingConvention, ptr ); object[] args = parameterMarshalInfo.Select( x => x.Parameter ).ToArray(); object result = @delegate.DynamicInvoke( args ); Variant[] toReturn = MapReturnValues( args, result ); return toReturn; } public Variant DllOpen( Variant dll ) { try { IntPtr library = LoadLibrary( dll.GetString() ); if ( library == IntPtr.Zero ) { int error = Marshal.GetLastWin32Error(); } return library; } catch (Exception) { return -1; } } private static Variant[] MapReturnValues( object[] args, object result ) { var toReturn = new Variant[args.Length+1]; toReturn[0] = Variant.Create( result ); Array.Copy( args.Select( Variant.Create ).ToArray(), 0, toReturn, 1, args.Length ); return toReturn; } private Delegate GetFunctionDelegate( MarshalInfo returnMarshalInfo, List<MarshalInfo> parameterMarshalInfo, Type callingConvention, IntPtr procAddress ) { Type delegateType = CreateDelegate( returnMarshalInfo, parameterMarshalInfo, callingConvention ); Delegate @delegate; try { @delegate = Marshal.GetDelegateForFunctionPointer( procAddress, delegateType ); } catch (Exception ex) { throw new BadNumberOfParameterException( 4, null, string.Empty ); } return @delegate; } private MarshalInfo GetReturnTypeInfo( string returnType ) { MarshalInfo returnMarshalInfo; try { returnMarshalInfo = GetMarshalInfo( returnType, null ); } catch (UnknowTypeNameException) { throw new BadReturnTypeException( 2, null, string.Empty ); } return returnMarshalInfo; } private List<MarshalInfo> GetParameterInfo( Variant[] paramtypen ) { var parameterMarshalInfo = new List<MarshalInfo>(); for ( int i = 0; i < paramtypen.Length; i += 2 ) { Variant typePart = paramtypen[i]; Variant value = paramtypen[i+1]; MarshalInfo marshalInfo; try { marshalInfo = GetMarshalInfo( typePart, value ); } catch (UnknowTypeNameException) { throw new BadParameterException( 5, null, string.Empty ); } parameterMarshalInfo.Add( marshalInfo ); } return parameterMarshalInfo; } private Type GetCallingConvention( string customCallingConvention ) { switch (customCallingConvention.ToUpper()) { case "CDECL": return typeof (CallConvCdecl); case "STDCALL": return typeof (CallConvStdcall); case "FASTCALL": return typeof (CallConvFastcall); case "THISCALL": return typeof (CallConvThiscall); case "WINAPI": return typeof (CallConvStdcall); default: throw new UnknowCallConvException( customCallingConvention ); } } private Type CreateDelegate( MarshalInfo returntype, List<MarshalInfo> paramtypes, Type callingConvention ) { string cacheKey = String.Format( "Delegate_{0}{1}{2}", returntype.Type, String.Join( String.Empty, paramtypes.Select( x => x.Type ) ), callingConvention ); if ( _delegateStore.ContainsKey( cacheKey ) ) { return _delegateStore[cacheKey]; } TypeBuilder tb = _dynamicMod.DefineType( String.Format( "_{0}", Guid.NewGuid().ToString( "N" ) ), TypeAttributes.Public|TypeAttributes.Sealed, typeof (MulticastDelegate) ); tb.DefineConstructor( MethodAttributes.RTSpecialName|MethodAttributes.SpecialName|MethodAttributes.Public|MethodAttributes.HideBySig, CallingConventions.Standard, new[] { typeof (object), typeof (IntPtr) } ).SetImplementationFlags( MethodImplAttributes.Runtime ); MethodBuilder inv = tb.DefineMethod( "Invoke", MethodAttributes.Public|MethodAttributes.Virtual|MethodAttributes.NewSlot|MethodAttributes.HideBySig, CallingConventions.Standard, returntype.Type, null, new[] { callingConvention }, paramtypes.Select( x => x.Type ).ToArray(), null, null ); for ( int index = 0; index < paramtypes.Count; index++ ) { MarshalInfo paramtype = paramtypes[index]; ParameterAttributes parameterAttributes = paramtype.IsRef ? ParameterAttributes.Out : ParameterAttributes.In; if ( paramtype.Type == typeof (StringBuilder) ) { parameterAttributes |= ParameterAttributes.Out; } if ( typeof (IRuntimeStruct).IsAssignableFrom( paramtype.Type.GetElementType() ) ) { parameterAttributes |= ParameterAttributes.In; } ParameterBuilder parameterBuilder = inv.DefineParameter( index+1, parameterAttributes, null ); if ( paramtype.MarshalAttribute.HasValue ) { ConstructorInfo constructorInfo = typeof (MarshalAsAttribute).GetConstructor( new[] { typeof (UnmanagedType) } ); var customAttributeBuilder = new CustomAttributeBuilder( constructorInfo, new object[] { paramtype.MarshalAttribute } ); parameterBuilder.SetCustomAttribute( customAttributeBuilder ); } } inv.SetImplementationFlags( MethodImplAttributes.Runtime ); Type t = tb.CreateType(); _delegateStore.Add( cacheKey, t ); return t; } public MarshalInfo GetMarshalInfo( string typePart, Variant value ) { bool isRef = typePart.EndsWith( "*" ); if ( isRef ) { typePart = typePart.TrimEnd( '*' ); } Type managedType = typePart.Equals( "struct", StringComparison.InvariantCultureIgnoreCase ) ? value.GetValue().GetType() : GetManagedType( typePart ); UnmanagedType? marshalAttribute = GetMarshalAttribute( typePart ); object changeType = null; if ( value != null ) { changeType = ConvertAutoitTypeToMarshalType( value, managedType ); } var marshalInfo = new MarshalInfo( changeType, managedType, marshalAttribute, isRef ); return marshalInfo; } private Type GetManagedType( string typeName ) { string upperTypeName = typeName.ToUpper(); if ( _typeMapping.ContainsKey( upperTypeName ) ) { return _typeMapping[upperTypeName]; } throw new UnknowTypeNameException( typeName ); } private object ConvertAutoitTypeToMarshalType( Variant variant, Type targetType ) { object changeType; if ( variant.GetRealType() == targetType ) { changeType = variant.GetValue(); } else if ( targetType == typeof (IntPtr) ) { changeType = new IntPtr( variant.GetInt() ); } else if ( targetType == typeof (UIntPtr) ) { changeType = new UIntPtr( (uint) variant.GetInt() ); } else if ( variant.IsInt32 && targetType == typeof (uint) ) { changeType = unchecked( (uint) variant.GetInt() ); } else if ( targetType == typeof (StringBuilder) ) { string s = variant.GetString(); changeType = new StringBuilder( s, 0, s.Length, UInt16.MaxValue ); } else { changeType = Convert.ChangeType( variant.GetValue(), targetType ); } return changeType; } public UnmanagedType? GetMarshalAttribute( string typeName ) { string upperTypeName = typeName.ToUpper(); if ( _marshalAttributeMapping.ContainsKey( upperTypeName ) ) { return _marshalAttributeMapping[upperTypeName]; } return null; } public Type CreateRuntimeStruct( string @struct ) { string cacheKey = String.Format( "Struct_{0}", @struct ); if ( _structStore.ContainsKey( cacheKey ) ) { return _structStore[cacheKey]; } IEnumerable<StructTypeInfo> typeInfos = GetTypeInfo( @struct ); Type res = CreateStruct( typeInfos ); _structStore.Add( cacheKey, res ); return res; } private Type CreateStruct( IEnumerable<StructTypeInfo> typeInfos ) { ConstructorInfo constructorInfo = typeof (StructLayoutAttribute).GetConstructor( new[] { typeof (LayoutKind) } ); var customAttributeBuilder = new CustomAttributeBuilder( constructorInfo, new object[] { LayoutKind.Sequential } ); TypeBuilder tb = _dynamicMod.DefineType( "_"+Guid.NewGuid().ToString( "N" ), TypeAttributes.Public, typeof (object), new[] { typeof (IRuntimeStruct) } ); tb.SetCustomAttribute( customAttributeBuilder ); ConstructorBuilder constructorBuilder = tb.DefineConstructor( MethodAttributes.Public|MethodAttributes.HideBySig|MethodAttributes.SpecialName|MethodAttributes.RTSpecialName, CallingConventions.Standard, Type.EmptyTypes ); ILGenerator ilGenerator = constructorBuilder.GetILGenerator(); ilGenerator.Emit( OpCodes.Ldarg_0 ); ConstructorInfo superConstructor = typeof (Object).GetConstructor( Type.EmptyTypes ); ilGenerator.Emit( OpCodes.Call, superConstructor ); ilGenerator.Emit( OpCodes.Nop ); ilGenerator.Emit( OpCodes.Nop ); foreach (StructTypeInfo typeInfo in typeInfos) { FieldBuilder fieldBuilder = tb.DefineField( typeInfo.VariableName, typeInfo.ManagedType, FieldAttributes.Public ); if ( typeInfo.ArraySize > 0 ) { ilGenerator.Emit( OpCodes.Ldarg_0 ); ilGenerator.Emit( OpCodes.Ldc_I4, typeInfo.ArraySize ); ilGenerator.Emit( OpCodes.Newarr, typeInfo.ManagedType.GetElementType() ); ilGenerator.Emit( OpCodes.Stfld, fieldBuilder ); } IEnumerable<CustomAttributeBuilder> attributesToApply = GetCustomAttributes( typeInfo ); foreach (CustomAttributeBuilder builder in attributesToApply) { fieldBuilder.SetCustomAttribute( builder ); } } ilGenerator.Emit( OpCodes.Ret ); Type t = tb.CreateType(); return t; } private static IEnumerable<CustomAttributeBuilder> GetCustomAttributes( StructTypeInfo typeInfo ) { var attributesToApply = new List<CustomAttributeBuilder>(); if ( typeInfo.MarshalAs.HasValue ) { ConstructorInfo customAttributeConstructorInfoMarshalAs = typeof (MarshalAsAttribute).GetConstructor( new[] { typeof (UnmanagedType) } ); var customAttributeBuilderMarshalAs = new CustomAttributeBuilder( customAttributeConstructorInfoMarshalAs, new object[] { typeInfo.MarshalAs.Value } ); attributesToApply.Add( customAttributeBuilderMarshalAs ); } if ( typeInfo.ArraySize > 0 ) { ConstructorInfo customAttributeConstructorMarshalAsArray = typeof (MarshalAsAttribute).GetConstructor( new[] { typeof (UnmanagedType) } ); FieldInfo propertyInfoSizeConst = typeof (MarshalAsAttribute).GetFields().Single( x => x.Name.Equals( "SizeConst" ) ); var customAttributeBuilderMarshalAsArray = new CustomAttributeBuilder( customAttributeConstructorMarshalAsArray, new object[] { UnmanagedType.ByValArray }, new[] { propertyInfoSizeConst }, new object[] { typeInfo.ArraySize } ); attributesToApply.Add( customAttributeBuilderMarshalAsArray ); } return attributesToApply; } private IEnumerable<StructTypeInfo> GetTypeInfo( string @struct ) { return GetTypeInfo( @struct.Split( ';' ) ); } private IEnumerable<StructTypeInfo> GetTypeInfo( string[] fragments ) { bool isSingleStruct = fragments.First().Equals( "STRUCT", StringComparison.InvariantCultureIgnoreCase ) && fragments.Last().Equals( "ENDSTRUCT", StringComparison.InvariantCultureIgnoreCase ) && fragments.Count( x => x.Equals( "STRUCT", StringComparison.InvariantCultureIgnoreCase ) ) == 1 && fragments.Count( x => x.Equals( "ENDSTRUCT", StringComparison.InvariantCultureIgnoreCase ) ) == 1; if ( isSingleStruct ) { fragments = fragments.Skip( 1 ).Take( fragments.Length-2 ).ToArray(); } var toReturn = new List<StructTypeInfo>(); for ( int index = 0; index < fragments.Length; index++ ) { string fragment = fragments[index]; string[] nametypeFragments = fragment.Split( ' ' ); if ( nametypeFragments.Length == 1 ) { string typeFragmanet = nametypeFragments[0]; string[] typeArraySizeFragments = typeFragmanet.Split( new[] { "[", "]" }, StringSplitOptions.RemoveEmptyEntries ); string typePart = typeArraySizeFragments[0]; UnmanagedType? marshalAttribute = GetMarshalAttribute( typePart ); int arraySize = 0; if ( typeArraySizeFragments.Length == 2 ) { arraySize = Int32.Parse( typeArraySizeFragments[1] ); } Type managedType; if ( typePart.Equals( "STRUCT", StringComparison.InvariantCultureIgnoreCase ) ) { int count = 0; var structPart = new List<string>(); do { bool isEndStruct = fragments[index].Equals( "ENDSTRUCT", StringComparison.InvariantCultureIgnoreCase ); if ( isEndStruct ) { count--; } else { bool isStruct = fragments[index].Equals( "STRUCT", StringComparison.InvariantCultureIgnoreCase ); if ( isStruct ) { count++; } else { structPart.Add( fragments[index] ); } } index++; } while ( count != 0 ); IEnumerable<StructTypeInfo> structTypeInfos = GetTypeInfo( structPart.ToArray() ); Type innerStructType = CreateStruct( structTypeInfos ); managedType = innerStructType; } else { managedType = GetManagedType( typePart ); if ( arraySize > 0 ) { managedType = managedType.MakeArrayType(); } } toReturn.Add( new StructTypeInfo( "_"+Guid.NewGuid().ToString( "N" ), managedType, marshalAttribute, arraySize ) ); continue; } if ( nametypeFragments.Length == 2 ) { string typeFragment = nametypeFragments[0]; string nameArraySizeFragment = nametypeFragments[1]; string[] nameArraySizeFragments = nameArraySizeFragment.Split( new[] { "[", "]" }, StringSplitOptions.RemoveEmptyEntries ); Type managedType = GetManagedType( typeFragment ); UnmanagedType? marshalAttribute = GetMarshalAttribute( typeFragment ); int arraySize = 0; if ( nameArraySizeFragments.Length == 2 ) { arraySize = Int32.Parse( nameArraySizeFragments[1] ); } if ( arraySize > 0 ) { managedType = managedType.MakeArrayType(); }
[ " string name = nameArraySizeFragments[0];" ]
1,831
lcc
csharp
null
76752da4aab9b0f2980a363c45b8b6a846bcbfadac525fd1
// // TypeDefinition.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // 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. // using System; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider { uint attributes; TypeReference base_type; internal Range fields_range; internal Range methods_range; short packing_size = Mixin.NotResolvedMarker; int class_size = Mixin.NotResolvedMarker; Collection<TypeReference> interfaces; Collection<TypeDefinition> nested_types; Collection<MethodDefinition> methods; Collection<FieldDefinition> fields; Collection<EventDefinition> events; Collection<PropertyDefinition> properties; Collection<CustomAttribute> custom_attributes; Collection<SecurityDeclaration> security_declarations; public TypeAttributes Attributes { get { return (TypeAttributes) attributes; } set { attributes = (uint) value; } } public TypeReference BaseType { get { return base_type; } set { base_type = value; } } void ResolveLayout () { if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker) return; if (!HasImage) { packing_size = Mixin.NoDataMarker; class_size = Mixin.NoDataMarker; return; } var row = Module.Read (this, (type, reader) => reader.ReadTypeLayout (type)); packing_size = row.Col1; class_size = row.Col2; } public bool HasLayoutInfo { get { if (packing_size >= 0 || class_size >= 0) return true; ResolveLayout (); return packing_size >= 0 || class_size >= 0; } } public short PackingSize { get { if (packing_size >= 0) return packing_size; ResolveLayout (); return packing_size >= 0 ? packing_size : (short) -1; } set { packing_size = value; } } public int ClassSize { get { if (class_size >= 0) return class_size; ResolveLayout (); return class_size >= 0 ? class_size : -1; } set { class_size = value; } } public bool HasInterfaces { get { if (interfaces != null) return interfaces.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasInterfaces (type)); return false; } } public Collection<TypeReference> Interfaces { get { if (interfaces != null) return interfaces; if (HasImage) return Module.Read (ref interfaces, this, (type, reader) => reader.ReadInterfaces (type)); return interfaces = new Collection<TypeReference> (); } } public bool HasNestedTypes { get { if (nested_types != null) return nested_types.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasNestedTypes (type)); return false; } } public Collection<TypeDefinition> NestedTypes { get { if (nested_types != null) return nested_types; if (HasImage) return Module.Read (ref nested_types, this, (type, reader) => reader.ReadNestedTypes (type)); return nested_types = new MemberDefinitionCollection<TypeDefinition> (this); } } public bool HasMethods { get { if (methods != null) return methods.Count > 0; if (HasImage) return methods_range.Length > 0; return false; } } public Collection<MethodDefinition> Methods { get { if (methods != null) return methods; if (HasImage) return Module.Read (ref methods, this, (type, reader) => reader.ReadMethods (type)); return methods = new MemberDefinitionCollection<MethodDefinition> (this); } } public bool HasFields { get { if (fields != null) return fields.Count > 0; if (HasImage) return fields_range.Length > 0; return false; } } public Collection<FieldDefinition> Fields { get { if (fields != null) return fields; if (HasImage) return Module.Read (ref fields, this, (type, reader) => reader.ReadFields (type)); return fields = new MemberDefinitionCollection<FieldDefinition> (this); } } public bool HasEvents { get { if (events != null) return events.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasEvents (type)); return false; } } public Collection<EventDefinition> Events { get { if (events != null) return events; if (HasImage) return Module.Read (ref events, this, (type, reader) => reader.ReadEvents (type)); return events = new MemberDefinitionCollection<EventDefinition> (this); } } public bool HasProperties { get { if (properties != null) return properties.Count > 0; if (HasImage) return Module.Read (this, (type, reader) => reader.HasProperties (type)); return false; } } public Collection<PropertyDefinition> Properties { get { if (properties != null) return properties; if (HasImage) return Module.Read (ref properties, this, (type, reader) => reader.ReadProperties (type)); return properties = new MemberDefinitionCollection<PropertyDefinition> (this); } } public bool HasSecurityDeclarations { get { if (security_declarations != null) return security_declarations.Count > 0; return this.GetHasSecurityDeclarations (Module); } } public Collection<SecurityDeclaration> SecurityDeclarations { get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public override bool HasGenericParameters { get { if (generic_parameters != null) return generic_parameters.Count > 0; return this.GetHasGenericParameters (Module); } } public override Collection<GenericParameter> GenericParameters { get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); } } #region TypeAttributes public bool IsNotPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); } } public bool IsNestedPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); } } public bool IsNestedPrivate { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); } } public bool IsNestedFamily { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); } } public bool IsNestedAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); } } public bool IsNestedFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); } } public bool IsNestedFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); } } public bool IsAutoLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); } } public bool IsSequentialLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); } } public bool IsExplicitLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); } } public bool IsClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); } } public bool IsInterface { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); } } public bool IsSealed { get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); } } public bool IsImport { get { return attributes.GetAttributes ((uint) TypeAttributes.Import); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); } } public bool IsSerializable { get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); } } public bool IsAnsiClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); } } public bool IsUnicodeClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); } } public bool IsAutoClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); } } public bool IsBeforeFieldInit { get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); } } #endregion public bool IsEnum { get { return base_type != null && base_type.IsTypeOf ("System", "Enum"); } } public override bool IsValueType { get {
[ "\t\t\t\tif (base_type == null)" ]
1,469
lcc
csharp
null
47a5c3493dba4beb59cd884a00ee301ebbbc06f48b66fba5
/* Simple Rule Engine Copyright (C) 2005 by Sierra Digital Solutions Corp This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections.Generic; using System.Text; using System.Xml; using RuleEngine.Evidence; namespace RuleEngine { public class ROM : ICloneable { #region instance variables /// <summary> /// collection of all evidence objects /// </summary> private Dictionary<string, IEvidence> evidenceCollection = new Dictionary<string, IEvidence>(); /// <summary> /// specifies the models to be used /// </summary> private Dictionary<string, XmlDocument> models = new Dictionary<string, XmlDocument>(); /// <summary> /// specifies for a given evidence all evidence thats dependent on it /// </summary> private Dictionary<string, List<string>> dependentEvidence = new Dictionary<string, List<string>>(); /// <summary> /// /// </summary> private Dictionary<string, Delegate> callback = new Dictionary<string, Delegate>(); #endregion #region constructor public ROM() { } #endregion #region core /// <summary> /// Add a model to the ROM. The name given to the model must match those specified in the ruleset. /// </summary> /// <param name="modelId"></param> /// <param name="model"></param> public void AddModel(string modelId, XmlDocument model) { //add model to collection models.Add(modelId, model); } /// <summary> /// Add a fact, action, or rule to the ROM. /// </summary> /// <param name="Action"></param> public void AddEvidence(IEvidence evidence) { //add evidence to collection evidenceCollection.Add(evidence.ID, evidence); } /// <summary> /// specifies for a given evidence all evidence thats dependent on it /// </summary> /// <param name="evidence"></param> /// <param name="dependentEvidence"></param> public void AddDependentFact(string evidence, string dependentEvidence) { if (!this.dependentEvidence.ContainsKey(evidence)) this.dependentEvidence.Add(evidence, new List<string>()); this.dependentEvidence[evidence].Add(dependentEvidence); } /// <summary> /// /// </summary> internal Dictionary<string, IEvidence> Evidence { get { return evidenceCollection; } } /// <summary> /// /// </summary> /// <param name="id"></param> /// <returns></returns> public IEvidence this[string id] { get { try { return evidenceCollection[id]; } catch { return null; } } set { evidenceCollection[id] = value; } } /// <summary> /// /// </summary> public void Evaluate() { Decisions.Decision decision = (new Decisions.Decision()); decision.EvidenceLookup += evidence_EvidenceLookup; decision.ModelLookup += evidence_ModelLookup; decision.Evaluate(evidenceCollection, dependentEvidence); } /// <summary> /// /// </summary> /// <returns></returns> public object Clone() { ROM rom = new ROM(); rom.callback = new Dictionary<string, Delegate>(this.callback); rom.dependentEvidence = new Dictionary<string, List<string>>(); foreach (string key in this.dependentEvidence.Keys) { rom.dependentEvidence.Add(key, new List<string>(this.dependentEvidence[key])); } rom.evidenceCollection = new Dictionary<string, IEvidence>(); foreach (string key in this.evidenceCollection.Keys) { IEvidence evidence = (IEvidence)this.evidenceCollection[key].Clone(); rom.evidenceCollection.Add(key, evidence); } rom.models = new Dictionary<string, XmlDocument>(this.models); return rom; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="callback"></param> public void RegisterCallback(string name, Delegate callback) { this.callback.Add(name, callback); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <returns></returns> private IEvidence evidence_EvidenceLookup(object sender, EvidenceLookupArgs args) { try { return evidenceCollection[args.Key]; } catch (Exception e) { throw new Exception("Could not find evidence: " + args.Key, e); } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <returns></returns> private XmlNode evidence_ModelLookup(object sender, ModelLookupArgs args) { try { return models[args.Key]; } catch {
[ " throw new Exception(\"Could not find model: \" + args.Key);" ]
578
lcc
csharp
null
42d7200767daef190a5abb124bd4a3751d552931e19200aa
# SPDX-License-Identifier: MIT """ SSL with SNI_-support for Python 2. Follow these instructions if you would like to verify SSL certificates in Python 2. Note, the default libraries do *not* do certificate checking; you need to do additional work to validate certificates yourself. This needs the following packages installed: * pyOpenSSL (tested with 16.0.0) * cryptography (minimum 1.3.4, from pyopenssl) * idna (minimum 2.0, from cryptography) However, pyopenssl depends on cryptography, which depends on idna, so while we use all three directly here we end up having relatively few packages required. You can install them with the following command: pip install pyopenssl cryptography idna To activate certificate checking, call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code before you begin making HTTP requests. This can be done in a ``sitecustomize`` module, or at any other time before your application begins using ``urllib3``, like this:: try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass Now you can use :mod:`urllib3` as you normally would, and it will support SNI when the required modules are installed. Activating this module also has the positive side effect of disabling SSL/TLS compression in Python 2 (see `CRIME attack`_). If you want to configure the default list of supported cipher suites, you can set the ``urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST`` variable. .. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication .. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit) """ from __future__ import absolute_import import OpenSSL.SSL from cryptography import x509 from cryptography.hazmat.backends.openssl import backend as openssl_backend from cryptography.hazmat.backends.openssl.x509 import _Certificate from socket import timeout, error as SocketError from io import BytesIO try: # Platform-specific: Python 2 from socket import _fileobject except ImportError: # Platform-specific: Python 3 _fileobject = None from ..packages.backports.makefile import backport_makefile import logging import ssl try: import six except ImportError: from ..packages import six import sys from .. import util __all__ = ['inject_into_urllib3', 'extract_from_urllib3'] # SNI always works. HAS_SNI = True # Map from urllib3 to PyOpenSSL compatible parameter-values. _openssl_versions = { ssl.PROTOCOL_SSLv23: OpenSSL.SSL.SSLv23_METHOD, ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD, } if hasattr(ssl, 'PROTOCOL_TLSv1_1') and hasattr(OpenSSL.SSL, 'TLSv1_1_METHOD'): _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD if hasattr(ssl, 'PROTOCOL_TLSv1_2') and hasattr(OpenSSL.SSL, 'TLSv1_2_METHOD'): _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD try: _openssl_versions.update({ssl.PROTOCOL_SSLv3: OpenSSL.SSL.SSLv3_METHOD}) except AttributeError: pass _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict( (v, k) for k, v in _stdlib_to_openssl_verify.items() ) # OpenSSL will only write 16K at a time SSL_WRITE_BLOCKSIZE = 16384 orig_util_HAS_SNI = util.HAS_SNI orig_util_SSLContext = util.ssl_.SSLContext log = logging.getLogger(__name__) def inject_into_urllib3(): 'Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.' _validate_dependencies_met() util.ssl_.SSLContext = PyOpenSSLContext util.HAS_SNI = HAS_SNI util.ssl_.HAS_SNI = HAS_SNI util.IS_PYOPENSSL = True util.ssl_.IS_PYOPENSSL = True def extract_from_urllib3(): 'Undo monkey-patching by :func:`inject_into_urllib3`.' util.ssl_.SSLContext = orig_util_SSLContext util.HAS_SNI = orig_util_HAS_SNI util.ssl_.HAS_SNI = orig_util_HAS_SNI util.IS_PYOPENSSL = False util.ssl_.IS_PYOPENSSL = False def _validate_dependencies_met(): """ Verifies that PyOpenSSL's package-level dependencies have been met. Throws `ImportError` if they are not met. """ # Method added in `cryptography==1.1`; not available in older versions from cryptography.x509.extensions import Extensions if getattr(Extensions, "get_extension_for_class", None) is None: raise ImportError("'cryptography' module missing required functionality. " "Try upgrading to v1.3.4 or newer.") # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509 # attribute is only present on those versions. from OpenSSL.crypto import X509 x509 = X509() if getattr(x509, "_x509", None) is None: raise ImportError("'pyOpenSSL' module missing required functionality. " "Try upgrading to v0.14 or newer.") def _dnsname_to_stdlib(name): """ Converts a dNSName SubjectAlternativeName field to the form used by the standard library on the given Python version. Cryptography produces a dNSName as a unicode string that was idna-decoded from ASCII bytes. We need to idna-encode that string to get it back, and then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8). """ def idna_encode(name): """ Borrowed wholesale from the Python Cryptography Project. It turns out that we can't just safely call `idna.encode`: it can explode for wildcard names. This avoids that problem. """ import idna for prefix in [u'*.', u'.']: if name.startswith(prefix): name = name[len(prefix):] return prefix.encode('ascii') + idna.encode(name) return idna.encode(name) name = idna_encode(name) if sys.version_info >= (3, 0): name = name.decode('utf-8') return name def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. # This is technically using private APIs, but should work across all # relevant versions until PyOpenSSL gets something proper for this. cert = _Certificate(openssl_backend, peer_cert._x509) # We want to find the SAN extension. Ask Cryptography to locate it (it's # faster than looping in Python) try: ext = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName ).value except x509.ExtensionNotFound: # No such extension, return the empty list. return [] except (x509.DuplicateExtension, x509.UnsupportedExtension, x509.UnsupportedGeneralNameType, UnicodeError) as e: # A problem has been found with the quality of the certificate. Assume # no SAN field is present. log.warning( "A problem was encountered with the certificate that prevented " "urllib3 from finding the SubjectAlternativeName field. This can " "affect certificate validation. The error was %s", e, ) return [] # We want to return dNSName and iPAddress fields. We need to cast the IPs # back to strings because the match_hostname function wants them as # strings. # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8 # decoded. This is pretty frustrating, but that's what the standard library # does with certificates, and so we need to attempt to do the same. names = [ ('DNS', _dnsname_to_stdlib(name)) for name in ext.get_values_for_type(x509.DNSName) ] names.extend( ('IP Address', str(name)) for name in ext.get_values_for_type(x509.IPAddress) ) return names class WrappedSocket(object): '''API-compatibility wrapper for Python OpenSSL's Connection-class. Note: _makefile_refs, _drop() and _reuse() are needed for the garbage collector of pypy. ''' def __init__(self, connection, socket, suppress_ragged_eofs=True): self.connection = connection self.socket = socket self.suppress_ragged_eofs = suppress_ragged_eofs self._makefile_refs = 0 self._closed = False def fileno(self): return self.socket.fileno() # Copy-pasted from Python 3.5 source code def _decref_socketios(self): if self._makefile_refs > 0: self._makefile_refs -= 1 if self._closed: self.close() def recv(self, *args, **kwargs): try: data = self.connection.recv(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else: raise except OpenSSL.SSL.WantReadError: rd = util.wait_for_read(self.socket, self.socket.gettimeout()) if not rd: raise timeout('The read operation timed out') else: return self.recv(*args, **kwargs) else: return data def recv_into(self, *args, **kwargs): try: return self.connection.recv_into(*args, **kwargs) except OpenSSL.SSL.SysCallError as e: if self.suppress_ragged_eofs and e.args == (-1, 'Unexpected EOF'): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else: raise except OpenSSL.SSL.WantReadError: rd = util.wait_for_read(self.socket, self.socket.gettimeout()) if not rd: raise timeout('The read operation timed out') else: return self.recv_into(*args, **kwargs) def settimeout(self, timeout): return self.socket.settimeout(timeout) def _send_until_done(self, data): while True: try: return self.connection.send(data) except OpenSSL.SSL.WantWriteError: wr = util.wait_for_write(self.socket, self.socket.gettimeout()) if not wr: raise timeout() continue except OpenSSL.SSL.SysCallError as e: raise SocketError(str(e)) def sendall(self, data): total_sent = 0 while total_sent < len(data): sent = self._send_until_done(data[total_sent:total_sent + SSL_WRITE_BLOCKSIZE]) total_sent += sent def shutdown(self): # FIXME rethrow compatible exceptions should we ever use this self.connection.shutdown() def close(self): if self._makefile_refs < 1: try: self._closed = True return self.connection.close() except OpenSSL.SSL.Error: return else: self._makefile_refs -= 1 def getpeercert(self, binary_form=False): x509 = self.connection.get_peer_certificate() if not x509: return x509 if binary_form: return OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_ASN1, x509) return { 'subject': ( (('commonName', x509.get_subject().CN),), ), 'subjectAltName': get_subj_alt_name(x509) } def _reuse(self): self._makefile_refs += 1 def _drop(self): if self._makefile_refs < 1: self.close() else: self._makefile_refs -= 1 if _fileobject: # Platform-specific: Python 2 def makefile(self, mode, bufsize=-1): self._makefile_refs += 1 return _fileobject(self, mode, bufsize, close=True) else: # Platform-specific: Python 3 makefile = backport_makefile WrappedSocket.makefile = makefile class PyOpenSSLContext(object): """ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. """ def __init__(self, protocol):
[ " self.protocol = _openssl_versions[protocol]" ]
1,264
lcc
python
null
f2d519e85b596a21571ccc0da4dcf8098c04163fb6b5b321
// This file has been generated by the GUI designer. Do not modify. namespace MonoDevelop.Gettext { internal partial class POEditorWidget { private global::Gtk.UIManager UIManager; private global::Gtk.VBox vbox2; private global::Gtk.Notebook notebookPages; private global::Gtk.VBox vbox7; private global::Gtk.HBox hbox2; private global::Gtk.Label label2; private global::MonoDevelop.Components.SearchEntry searchEntryFilter; private global::Gtk.ToggleButton togglebuttonOk; private global::Gtk.HBox togglebuttonOkHbox; private global::MonoDevelop.Components.ImageView togglebuttonOkIcon; private global::Gtk.Label togglebuttonOkLabel; private global::Gtk.ToggleButton togglebuttonMissing; private global::Gtk.HBox togglebuttonMissingHbox; private global::MonoDevelop.Components.ImageView togglebuttonMissingIcon; private global::Gtk.Label togglebuttonMissingLabel; private global::Gtk.ToggleButton togglebuttonFuzzy; private global::Gtk.HBox togglebuttonFuzzyHbox; private global::MonoDevelop.Components.ImageView togglebuttonFuzzyIcon; private global::Gtk.Label togglebuttonFuzzyLabel; private global::Gtk.VPaned vpaned2; private global::Gtk.ScrolledWindow scrolledwindow1; private global::Gtk.TreeView treeviewEntries; private global::Gtk.Table table1; private global::Gtk.VBox vbox3; private global::Gtk.Label label6; private global::Gtk.ScrolledWindow scrolledwindow3; private global::Gtk.TextView textviewComments; private global::Gtk.VBox vbox4; private global::Gtk.Label label7; private global::Gtk.Notebook notebookTranslated; private global::Gtk.Label label1; private global::Gtk.VBox vbox5; private global::Gtk.HBox hbox3; private global::Gtk.Label label8; private global::Gtk.CheckButton checkbuttonWhiteSpaces; private global::Gtk.ScrolledWindow scrolledwindowOriginal; private global::Gtk.VBox vbox8; private global::Gtk.Label label9; private global::Gtk.ScrolledWindow scrolledwindowPlural; private global::Gtk.VBox vbox6; private global::Gtk.Label label4; private global::Gtk.ScrolledWindow scrolledwindow2; private global::Gtk.TreeView treeviewFoundIn; private global::Gtk.Label label5; private global::Gtk.HBox hbox1; private global::Gtk.Toolbar toolbarPages; private global::Gtk.ProgressBar progressbar1; protected virtual void Build () { MonoDevelop.Components.Gui.Initialize (this); // Widget MonoDevelop.Gettext.POEditorWidget var w1 = MonoDevelop.Components.BinContainer.Attach (this); this.UIManager = new global::Gtk.UIManager (); global::Gtk.ActionGroup w2 = new global::Gtk.ActionGroup ("Default"); this.UIManager.InsertActionGroup (w2, 0); this.Name = "MonoDevelop.Gettext.POEditorWidget"; // Container child MonoDevelop.Gettext.POEditorWidget.Gtk.Container+ContainerChild this.vbox2 = new global::Gtk.VBox (); this.vbox2.Name = "vbox2"; this.vbox2.Spacing = 6; // Container child vbox2.Gtk.Box+BoxChild this.notebookPages = new global::Gtk.Notebook (); this.notebookPages.CanFocus = true; this.notebookPages.Name = "notebookPages"; this.notebookPages.CurrentPage = 0; this.notebookPages.ShowBorder = false; this.notebookPages.ShowTabs = false; // Container child notebookPages.Gtk.Notebook+NotebookChild this.vbox7 = new global::Gtk.VBox (); this.vbox7.Name = "vbox7"; this.vbox7.Spacing = 6; // Container child vbox7.Gtk.Box+BoxChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; // Container child hbox2.Gtk.Box+BoxChild this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("_Filter:"); this.label2.UseUnderline = true; this.hbox2.Add (this.label2); global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.label2])); w3.Position = 0; w3.Expand = false; w3.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.searchEntryFilter = new global::MonoDevelop.Components.SearchEntry (); this.searchEntryFilter.Name = "searchEntryFilter"; this.searchEntryFilter.ForceFilterButtonVisible = false; this.searchEntryFilter.HasFrame = false; this.searchEntryFilter.RoundedShape = false; this.searchEntryFilter.IsCheckMenu = false; this.searchEntryFilter.ActiveFilterID = 0; this.searchEntryFilter.Ready = false; this.searchEntryFilter.HasFocus = false; this.hbox2.Add (this.searchEntryFilter); global::Gtk.Box.BoxChild w4 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.searchEntryFilter])); w4.Position = 1; // Container child hbox2.Gtk.Box+BoxChild this.togglebuttonOk = new global::Gtk.ToggleButton (); this.togglebuttonOk.CanFocus = true; this.togglebuttonOk.Name = "togglebuttonOk"; // Container child togglebuttonOk.Gtk.Container+ContainerChild this.togglebuttonOkHbox = new global::Gtk.HBox (); this.togglebuttonOkHbox.Name = "togglebuttonOkHbox"; this.togglebuttonOkHbox.Spacing = 2; // Container child togglebuttonOkHbox.Gtk.Box+BoxChild this.togglebuttonOkIcon = new global::MonoDevelop.Components.ImageView (); this.togglebuttonOkIcon.Name = "togglebuttonOkIcon"; this.togglebuttonOkIcon.IconId = "md-done"; this.togglebuttonOkIcon.IconSize = ((global::Gtk.IconSize)(1)); this.togglebuttonOkHbox.Add (this.togglebuttonOkIcon); global::Gtk.Box.BoxChild w5 = ((global::Gtk.Box.BoxChild)(this.togglebuttonOkHbox [this.togglebuttonOkIcon])); w5.Position = 0; w5.Expand = false; w5.Fill = false; // Container child togglebuttonOkHbox.Gtk.Box+BoxChild this.togglebuttonOkLabel = new global::Gtk.Label (); this.togglebuttonOkLabel.Name = "togglebuttonOkLabel"; this.togglebuttonOkLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("Valid"); this.togglebuttonOkLabel.UseUnderline = true; this.togglebuttonOkHbox.Add (this.togglebuttonOkLabel); global::Gtk.Box.BoxChild w6 = ((global::Gtk.Box.BoxChild)(this.togglebuttonOkHbox [this.togglebuttonOkLabel])); w6.Position = 1; w6.Expand = false; w6.Fill = false; this.togglebuttonOk.Add (this.togglebuttonOkHbox); this.hbox2.Add (this.togglebuttonOk); global::Gtk.Box.BoxChild w8 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.togglebuttonOk])); w8.Position = 2; w8.Expand = false; w8.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.togglebuttonMissing = new global::Gtk.ToggleButton (); this.togglebuttonMissing.CanFocus = true; this.togglebuttonMissing.Name = "togglebuttonMissing"; // Container child togglebuttonMissing.Gtk.Container+ContainerChild this.togglebuttonMissingHbox = new global::Gtk.HBox (); this.togglebuttonMissingHbox.Name = "togglebuttonMissingHbox"; this.togglebuttonMissingHbox.Spacing = 2; // Container child togglebuttonMissingHbox.Gtk.Box+BoxChild this.togglebuttonMissingIcon = new global::MonoDevelop.Components.ImageView (); this.togglebuttonMissingIcon.Name = "togglebuttonMissingIcon"; this.togglebuttonMissingIcon.IconId = "md-warning"; this.togglebuttonMissingIcon.IconSize = ((global::Gtk.IconSize)(1)); this.togglebuttonMissingHbox.Add (this.togglebuttonMissingIcon); global::Gtk.Box.BoxChild w9 = ((global::Gtk.Box.BoxChild)(this.togglebuttonMissingHbox [this.togglebuttonMissingIcon])); w9.Position = 0; w9.Expand = false; w9.Fill = false; // Container child togglebuttonMissingHbox.Gtk.Box+BoxChild this.togglebuttonMissingLabel = new global::Gtk.Label (); this.togglebuttonMissingLabel.Name = "togglebuttonMissingLabel"; this.togglebuttonMissingLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("Missing"); this.togglebuttonMissingLabel.UseUnderline = true; this.togglebuttonMissingHbox.Add (this.togglebuttonMissingLabel); global::Gtk.Box.BoxChild w10 = ((global::Gtk.Box.BoxChild)(this.togglebuttonMissingHbox [this.togglebuttonMissingLabel])); w10.Position = 1; w10.Expand = false; w10.Fill = false; this.togglebuttonMissing.Add (this.togglebuttonMissingHbox); this.hbox2.Add (this.togglebuttonMissing); global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.togglebuttonMissing])); w12.Position = 3; w12.Expand = false; w12.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.togglebuttonFuzzy = new global::Gtk.ToggleButton (); this.togglebuttonFuzzy.CanFocus = true; this.togglebuttonFuzzy.Name = "togglebuttonFuzzy"; // Container child togglebuttonFuzzy.Gtk.Container+ContainerChild this.togglebuttonFuzzyHbox = new global::Gtk.HBox (); this.togglebuttonFuzzyHbox.Name = "togglebuttonFuzzyHbox"; this.togglebuttonFuzzyHbox.Spacing = 2; // Container child togglebuttonFuzzyHbox.Gtk.Box+BoxChild this.togglebuttonFuzzyIcon = new global::MonoDevelop.Components.ImageView (); this.togglebuttonFuzzyIcon.Name = "togglebuttonFuzzyIcon"; this.togglebuttonFuzzyIcon.IconId = "md-error"; this.togglebuttonFuzzyIcon.IconSize = ((global::Gtk.IconSize)(1)); this.togglebuttonFuzzyHbox.Add (this.togglebuttonFuzzyIcon); global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.togglebuttonFuzzyHbox [this.togglebuttonFuzzyIcon])); w13.Position = 0; w13.Expand = false; w13.Fill = false; // Container child togglebuttonFuzzyHbox.Gtk.Box+BoxChild this.togglebuttonFuzzyLabel = new global::Gtk.Label (); this.togglebuttonFuzzyLabel.Name = "togglebuttonFuzzyLabel"; this.togglebuttonFuzzyLabel.LabelProp = global::Mono.Unix.Catalog.GetString ("Fuzzy"); this.togglebuttonFuzzyLabel.UseUnderline = true; this.togglebuttonFuzzyHbox.Add (this.togglebuttonFuzzyLabel); global::Gtk.Box.BoxChild w14 = ((global::Gtk.Box.BoxChild)(this.togglebuttonFuzzyHbox [this.togglebuttonFuzzyLabel])); w14.Position = 1; w14.Expand = false; w14.Fill = false; this.togglebuttonFuzzy.Add (this.togglebuttonFuzzyHbox); this.hbox2.Add (this.togglebuttonFuzzy); global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.togglebuttonFuzzy])); w16.Position = 4; w16.Expand = false; w16.Fill = false; this.vbox7.Add (this.hbox2); global::Gtk.Box.BoxChild w17 = ((global::Gtk.Box.BoxChild)(this.vbox7 [this.hbox2])); w17.Position = 0; w17.Expand = false; w17.Fill = false; // Container child vbox7.Gtk.Box+BoxChild this.vpaned2 = new global::Gtk.VPaned (); this.vpaned2.CanFocus = true; this.vpaned2.Name = "vpaned2"; this.vpaned2.Position = 186; // Container child vpaned2.Gtk.Paned+PanedChild this.scrolledwindow1 = new global::Gtk.ScrolledWindow (); this.scrolledwindow1.CanFocus = true; this.scrolledwindow1.Name = "scrolledwindow1"; this.scrolledwindow1.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child scrolledwindow1.Gtk.Container+ContainerChild this.treeviewEntries = new global::Gtk.TreeView (); this.treeviewEntries.CanFocus = true; this.treeviewEntries.Name = "treeviewEntries"; this.scrolledwindow1.Add (this.treeviewEntries); this.vpaned2.Add (this.scrolledwindow1); global::Gtk.Paned.PanedChild w19 = ((global::Gtk.Paned.PanedChild)(this.vpaned2 [this.scrolledwindow1])); w19.Resize = false; // Container child vpaned2.Gtk.Paned+PanedChild this.table1 = new global::Gtk.Table (((uint)(2)), ((uint)(2)), true); this.table1.Name = "table1"; this.table1.RowSpacing = ((uint)(6)); this.table1.ColumnSpacing = ((uint)(6)); // Container child table1.Gtk.Table+TableChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.label6 = new global::Gtk.Label (); this.label6.Name = "label6"; this.label6.Xalign = 0F; this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("_Comments:"); this.label6.UseUnderline = true; this.vbox3.Add (this.label6); global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.label6])); w20.Position = 0; w20.Expand = false; w20.Fill = false; // Container child vbox3.Gtk.Box+BoxChild this.scrolledwindow3 = new global::Gtk.ScrolledWindow (); this.scrolledwindow3.CanFocus = true; this.scrolledwindow3.Name = "scrolledwindow3"; this.scrolledwindow3.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child scrolledwindow3.Gtk.Container+ContainerChild this.textviewComments = new global::Gtk.TextView (); this.textviewComments.CanFocus = true; this.textviewComments.Name = "textviewComments"; this.textviewComments.AcceptsTab = false; this.scrolledwindow3.Add (this.textviewComments); this.vbox3.Add (this.scrolledwindow3); global::Gtk.Box.BoxChild w22 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.scrolledwindow3])); w22.Position = 1; this.table1.Add (this.vbox3); global::Gtk.Table.TableChild w23 = ((global::Gtk.Table.TableChild)(this.table1 [this.vbox3])); w23.TopAttach = ((uint)(1)); w23.BottomAttach = ((uint)(2)); w23.LeftAttach = ((uint)(1)); w23.RightAttach = ((uint)(2)); w23.XOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.vbox4 = new global::Gtk.VBox (); this.vbox4.Name = "vbox4"; this.vbox4.Spacing = 6; // Container child vbox4.Gtk.Box+BoxChild this.label7 = new global::Gtk.Label (); this.label7.Name = "label7"; this.label7.Xalign = 0F; this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("_Translated (msgstr):"); this.label7.UseUnderline = true; this.vbox4.Add (this.label7); global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.label7])); w24.Position = 0; w24.Expand = false; w24.Fill = false; // Container child vbox4.Gtk.Box+BoxChild this.notebookTranslated = new global::Gtk.Notebook (); this.notebookTranslated.CanFocus = true; this.notebookTranslated.Name = "notebookTranslated"; this.notebookTranslated.CurrentPage = 0; // Notebook tab global::Gtk.Label w25 = new global::Gtk.Label (); w25.Visible = true; this.notebookTranslated.Add (w25); this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("page1"); this.notebookTranslated.SetTabLabel (w25, this.label1); this.label1.ShowAll (); this.vbox4.Add (this.notebookTranslated); global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.vbox4 [this.notebookTranslated])); w26.Position = 1; this.table1.Add (this.vbox4); global::Gtk.Table.TableChild w27 = ((global::Gtk.Table.TableChild)(this.table1 [this.vbox4])); w27.TopAttach = ((uint)(1)); w27.BottomAttach = ((uint)(2)); w27.XOptions = ((global::Gtk.AttachOptions)(4)); w27.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.vbox5 = new global::Gtk.VBox (); this.vbox5.Name = "vbox5"; this.vbox5.Spacing = 6; // Container child vbox5.Gtk.Box+BoxChild this.hbox3 = new global::Gtk.HBox (); this.hbox3.Name = "hbox3"; this.hbox3.Spacing = 6; // Container child hbox3.Gtk.Box+BoxChild
[ "\t\t\tthis.label8 = new global::Gtk.Label ();" ]
1,086
lcc
csharp
null
79bfd01dfd65567d16786ba83d96abf2c1f32aed45f161f0
""" This module handles the tabbed layout in PyChess """ import imp, os import traceback import cStringIO import gtk, gobject from pychess.Utils.IconLoader import load_icon from pychess.System.Log import log from pychess.System import glock, conf, prefix from ChessClock import ChessClock from BoardControl import BoardControl from pydock.PyDockTop import PyDockTop from pydock.__init__ import CENTER, EAST, SOUTH from pychess.System.prefix import addUserConfigPrefix from pychess.System.uistuff import makeYellow from pychess.Utils.GameModel import GameModel ################################################################################ # Initialize modul constants, and a few worker functions # ################################################################################ def createAlignment (top, right, bottom, left): align = gtk.Alignment(.5, .5, 1, 1) align.set_property("top-padding", top) align.set_property("right-padding", right) align.set_property("bottom-padding", bottom) align.set_property("left-padding", left) return align def cleanNotebook (): notebook = gtk.Notebook() notebook.set_show_tabs(False) notebook.set_show_border(False) return notebook def createImage (pixbuf): image = gtk.Image() image.set_from_pixbuf(pixbuf) return image light_on = load_icon(16, "stock_3d-light-on", "weather-clear") light_off = load_icon(16, "stock_3d-light-off", "weather-clear-night") gtk_close = load_icon(16, "gtk-close") media_previous = load_icon(16, "gtk-media-previous-ltr") media_rewind = load_icon(16, "gtk-media-rewind-ltr") media_forward = load_icon(16, "gtk-media-forward-ltr") media_next = load_icon(16, "gtk-media-next-ltr") GAME_MENU_ITEMS = ("save_game1", "save_game_as1", "properties1", "close1") ACTION_MENU_ITEMS = ("abort", "adjourn", "draw", "pause1", "resume1", "undo1", "call_flag", "resign", "ask_to_move") VIEW_MENU_ITEMS = ("rotate_board1", "show_sidepanels", "hint_mode", "spy_mode") MENU_ITEMS = GAME_MENU_ITEMS + ACTION_MENU_ITEMS + VIEW_MENU_ITEMS path = prefix.addDataPrefix("sidepanel") postfix = "Panel.py" files = [f[:-3] for f in os.listdir(path) if f.endswith(postfix)] sidePanels = [imp.load_module(f, *imp.find_module(f, [path])) for f in files] pref_sidePanels = [] for panel in sidePanels: if conf.get(panel.__name__, True): pref_sidePanels.append(panel) ################################################################################ # Initialize module variables # ################################################################################ widgets = None def setWidgets (w): global widgets widgets = w def getWidgets (): return widgets key2gmwidg = {} notebooks = {"board": cleanNotebook(), "statusbar": cleanNotebook(), "messageArea": cleanNotebook()} for panel in sidePanels: notebooks[panel.__name__] = cleanNotebook() docks = {"board": (gtk.Label("Board"), notebooks["board"])} ################################################################################ # The holder class for tab releated widgets # ################################################################################ class GameWidget (gobject.GObject): __gsignals__ = { 'close_clicked': (gobject.SIGNAL_RUN_FIRST, None, ()), 'infront': (gobject.SIGNAL_RUN_FIRST, None, ()), 'title_changed': (gobject.SIGNAL_RUN_FIRST, None, ()), 'closed': (gobject.SIGNAL_RUN_FIRST, None, ()), } def __init__ (self, gamemodel): gobject.GObject.__init__(self) self.gamemodel = gamemodel tabcontent = self.initTabcontents() boardvbox, board, messageSock = self.initBoardAndClock(gamemodel) statusbar, stat_hbox = self.initStatusbar(board) self.tabcontent = tabcontent self.board = board self.statusbar = statusbar self.messageSock = messageSock self.notebookKey = gtk.Label(); self.notebookKey.set_size_request(0,0) self.boardvbox = boardvbox self.stat_hbox = stat_hbox # Some stuff in the sidepanels .load functions might change UI, so we # need glock # TODO: Really? glock.acquire() try: self.panels = [panel.Sidepanel().load(self) for panel in sidePanels] finally: glock.release() def __del__ (self): self.board.__del__() def initTabcontents(self): tabcontent = createAlignment(gtk.Notebook().props.tab_vborder,0,0,0) hbox = gtk.HBox() hbox.set_spacing(4) hbox.pack_start(createImage(light_off), expand=False) close_button = gtk.Button() close_button.set_property("can-focus", False) close_button.add(createImage(gtk_close)) close_button.set_relief(gtk.RELIEF_NONE) close_button.set_size_request(20, 18) close_button.connect("clicked", lambda w: self.emit("close_clicked")) hbox.pack_end(close_button, expand=False) label = gtk.Label("") label.set_alignment(0,.7) hbox.pack_end(label) tabcontent.add(hbox) tabcontent.show_all() # Gtk doesn't show tab labels when the rest is return tabcontent def initBoardAndClock(self, gamemodel): boardvbox = gtk.VBox() boardvbox.set_spacing(2) messageSock = createAlignment(0,0,0,0) makeYellow(messageSock) if gamemodel.timemodel: ccalign = createAlignment(0, 0, 0, 0) cclock = ChessClock() cclock.setModel(gamemodel.timemodel) ccalign.add(cclock) ccalign.set_size_request(-1, 32) boardvbox.pack_start(ccalign, expand=False) actionMenuDic = {} for item in ACTION_MENU_ITEMS: actionMenuDic[item] = widgets[item] board = BoardControl(gamemodel, actionMenuDic) boardvbox.pack_start(board) return boardvbox, board, messageSock def initStatusbar(self, board): def tip (widget, x, y, keyboard_mode, tooltip, text): l = gtk.Label(text) tooltip.set_custom(l) l.show() return True stat_hbox = gtk.HBox() page_vbox = gtk.VBox() page_vbox.set_spacing(1) sep = gtk.HSeparator() sep.set_size_request(-1, 2) page_hbox = gtk.HBox() startbut = gtk.Button() startbut.add(createImage(media_previous)) startbut.set_relief(gtk.RELIEF_NONE) startbut.props.has_tooltip = True startbut.connect("query-tooltip", tip, _("Jump to initial position")) backbut = gtk.Button() backbut.add(createImage(media_rewind)) backbut.set_relief(gtk.RELIEF_NONE) backbut.props.has_tooltip = True backbut.connect("query-tooltip", tip, _("Step back one move")) forwbut = gtk.Button() forwbut.add(createImage(media_forward)) forwbut.set_relief(gtk.RELIEF_NONE) forwbut.props.has_tooltip = True forwbut.connect("query-tooltip", tip, _("Step forward one move")) endbut = gtk.Button() endbut.add(createImage(media_next)) endbut.set_relief(gtk.RELIEF_NONE) endbut.props.has_tooltip = True endbut.connect("query-tooltip", tip, _("Jump to latest position")) startbut.connect("clicked", lambda w: board.view.showFirst()) backbut.connect("clicked", lambda w: board.view.showPrevious()) forwbut.connect("clicked", lambda w: board.view.showNext()) endbut.connect("clicked", lambda w: board.view.showLast()) page_hbox.pack_start(startbut) page_hbox.pack_start(backbut) page_hbox.pack_start(forwbut) page_hbox.pack_start(endbut) page_vbox.pack_start(sep) page_vbox.pack_start(page_hbox) statusbar = gtk.Statusbar() stat_hbox.pack_start(page_vbox, expand=False) stat_hbox.pack_start(statusbar) return statusbar, stat_hbox def setLocked (self, locked): """ Makes the board insensitive and turns of the tab ready indicator """ self.board.setLocked(locked) if not self.tabcontent.get_children(): return self.tabcontent.child.remove(self.tabcontent.child.get_children()[0]) if not locked: self.tabcontent.child.pack_start(createImage(light_on), expand=False) else: self.tabcontent.child.pack_start(createImage(light_off), expand=False) self.tabcontent.show_all() def setTabText (self, text): self.tabcontent.child.get_children()[1].set_text(text) self.emit('title_changed') def getTabText (self): return self.tabcontent.child.get_children()[1].get_text() def status (self, message): glock.acquire() try: self.statusbar.pop(0) if message: self.statusbar.push(0, message) finally: glock.release() def bringToFront (self): getheadbook().set_current_page(self.getPageNumber()) def isInFront(self): if not getheadbook(): return False return getheadbook().get_current_page() == self.getPageNumber() def getPageNumber (self): return getheadbook().page_num(self.notebookKey) def showMessage (self, messageDialog, vertical=False): if self.messageSock.child: self.messageSock.remove(self.messageSock.child) message = messageDialog.child.get_children()[0] hbuttonbox = messageDialog.child.get_children()[-1] if vertical: buttonbox = gtk.VButtonBox() buttonbox.props.layout_style = gtk.BUTTONBOX_SPREAD for button in hbuttonbox.get_children(): hbuttonbox.remove(button) buttonbox.add(button) else: messageDialog.child.remove(hbuttonbox) buttonbox = hbuttonbox buttonbox.props.layout_style = gtk.BUTTONBOX_SPREAD messageDialog.child.remove(message) texts = message.get_children()[1] message.set_child_packing(texts, False, False, 0, gtk.PACK_START) text1, text2 = texts.get_children() text1.props.yalign = 1 text2.props.yalign = 0 texts.set_child_packing(text1, True, True, 0, gtk.PACK_START) texts.set_child_packing(text2, True, True, 0, gtk.PACK_START) texts.set_spacing(3) message.pack_end(buttonbox, True, True) if self.messageSock.child: self.messageSock.remove(self.messageSock.child) self.messageSock.add(message) self.messageSock.show_all() if self == cur_gmwidg(): notebooks["messageArea"].show() def hideMessage (self): self.messageSock.hide() ################################################################################ # Main handling of gamewidgets # ################################################################################ def splitit(widget): if not hasattr(widget, 'get_children'): return for child in widget.get_children(): splitit(child) widget.remove(child) def delGameWidget (gmwidg): """ Remove the widget from the GUI after the game has been terminated """ gmwidg.emit("closed") del key2gmwidg[gmwidg.notebookKey] pageNum = gmwidg.getPageNumber() headbook = getheadbook() headbook.remove_page(pageNum) for notebook in notebooks.values(): notebook.remove_page(pageNum) if headbook.get_n_pages() == 1 and conf.get("hideTabs", False): show_tabs(False) if headbook.get_n_pages() == 0: mainvbox = widgets["mainvbox"] centerVBox = mainvbox.get_children()[2] for child in centerVBox.get_children(): centerVBox.remove(child) mainvbox.remove(centerVBox) mainvbox.remove(mainvbox.get_children()[1]) mainvbox.pack_end(background) background.show() gmwidg.__del__() def _ensureReadForGameWidgets (): mainvbox = widgets["mainvbox"] if len(mainvbox.get_children()) == 3: return global background background = widgets["mainvbox"].get_children()[1] mainvbox.remove(background) # Initing headbook align = createAlignment (4, 4, 0, 4) align.set_property("yscale", 0) headbook = gtk.Notebook() headbook.set_scrollable(True) headbook.props.tab_vborder = 0 align.add(headbook) mainvbox.pack_start(align, expand=False) show_tabs(not conf.get("hideTabs", False)) # Initing center centerVBox = gtk.VBox() # The message area centerVBox.pack_start(notebooks["messageArea"], expand=False) def callback (notebook, gpointer, page_num): notebook.props.visible = notebook.get_nth_page(page_num).child.props.visible notebooks["messageArea"].connect("switch-page", callback) # The dock global dock, dockAlign dock = PyDockTop("main") dockAlign = createAlignment(4,4,0,4) dockAlign.add(dock) centerVBox.pack_start(dockAlign) dockAlign.show() dock.show() dockLocation = addUserConfigPrefix("pydock.xml") for panel in sidePanels: hbox = gtk.HBox() pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(panel.__icon__, 16, 16) icon = gtk.image_new_from_pixbuf(pixbuf) label = gtk.Label(panel.__title__) label.set_size_request(0, 0) label.set_alignment(0, 1) hbox.pack_start(icon, expand=False, fill=False) hbox.pack_start(label, expand=True, fill=True) hbox.set_spacing(2) hbox.show_all() def cb (widget, x, y, keyboard_mode, tooltip, title, desc, filename): table = gtk.Table(2,2) table.set_row_spacings(2) table.set_col_spacings(6) table.set_border_width(4) pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(filename, 56, 56) image = gtk.image_new_from_pixbuf(pixbuf) image.set_alignment(0, 0) table.attach(image, 0,1,0,2) titleLabel = gtk.Label() titleLabel.set_markup("<b>%s</b>" % title) titleLabel.set_alignment(0, 0) table.attach(titleLabel, 1,2,0,1) descLabel = gtk.Label(desc) descLabel.props.wrap = True table.attach(descLabel, 1,2,1,2) tooltip.set_custom(table) table.show_all() return True hbox.props.has_tooltip = True hbox.connect("query-tooltip", cb, panel.__title__, panel.__desc__, panel.__icon__) docks[panel.__name__] = (hbox, notebooks[panel.__name__]) if os.path.isfile(dockLocation): try: dock.loadFromXML(dockLocation, docks) except Exception, e: stringio = cStringIO.StringIO() traceback.print_exc(file=stringio) error = stringio.getvalue() log.error("Dock loading error: %s\n%s" % (e, error)) md = gtk.MessageDialog(widgets["window1"], type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_CLOSE) md.set_markup(_("<b><big>PyChess was unable to load your panel settings</big></b>")) md.format_secondary_text(_("Your panel settings have been reset. If this problem repeats, you should report it to the developers")) md.run() md.hide() os.remove(dockLocation) for title, panel in docks.values(): title.unparent() panel.unparent() if not os.path.isfile(dockLocation): leaf = dock.dock(docks["board"][1], CENTER, gtk.Label(docks["board"][0]), "board") docks["board"][1].show_all() leaf.setDockable(False) # NE leaf = leaf.dock(docks["historyPanel"][1], EAST, docks["historyPanel"][0], "historyPanel") conf.set("historyPanel", True) leaf = leaf.dock(docks["scorePanel"][1], CENTER, docks["scorePanel"][0], "scorePanel") conf.set("scorePanel", True) # SE leaf = leaf.dock(docks["bookPanel"][1], SOUTH, docks["bookPanel"][0], "bookPanel") conf.set("bookPanel", True) leaf = leaf.dock(docks["commentPanel"][1], CENTER, docks["commentPanel"][0], "commentPanel") conf.set("commentPanel", True) leaf = leaf.dock(docks["chatPanel"][1], CENTER, docks["chatPanel"][0], "chatPanel") conf.set("chatPanel", True) def unrealize (dock): # unhide the panel before saving so its configuration is saved correctly notebooks["board"].get_parent().get_parent().zoomDown() dock.saveToXML(dockLocation) dock.__del__() dock.connect("unrealize", unrealize) # The status bar notebooks["statusbar"].set_border_width(4) centerVBox.pack_start(notebooks["statusbar"], expand=False) mainvbox.pack_start(centerVBox) centerVBox.show_all() mainvbox.show() # Connecting headbook to other notebooks def callback (notebook, gpointer, page_num): for notebook in notebooks.values(): notebook.set_current_page(page_num) headbook.connect("switch-page", callback) if hasattr(headbook, "set_tab_reorderable"): def page_reordered (widget, child, new_num, headbook): old_num = notebooks["board"].page_num(key2gmwidg[child].boardvbox) if old_num == -1: log.error('Games and labels are out of sync!') else:
[ " for notebook in notebooks.values():" ]
1,188
lcc
python
null
8c19d95147fe4a3d515b456de624adfc662e5bf40c1c3bad
# -*- coding: utf-8 -*- # # This file is part of NINJA-IDE (http://ninja-ide.org). # # NINJA-IDE 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 # any later version. # # NINJA-IDE 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 NINJA-IDE; If not, see <http://www.gnu.org/licenses/>. from PyQt4.QtGui import QKeySequence from PyQt4.QtCore import QDir from PyQt4.QtCore import QSettings from PyQt4.QtCore import Qt import os import sys ############################################################################### # PATHS ############################################################################### HOME_PATH = QDir.toNativeSeparators(QDir.homePath()) NINJA_EXECUTABLE = os.path.realpath(sys.argv[0]) PRJ_PATH = os.path.abspath(os.path.dirname(__file__)).decode('utf-8') #Only for py2exe frozen = getattr(sys, 'frozen', '') if frozen in ('dll', 'console_exe', 'windows_exe'): # py2exe: PRJ_PATH = os.path.abspath(os.path.dirname(sys.executable)) HOME_NINJA_PATH = os.path.join(HOME_PATH, ".ninja_ide") SETTINGS_PATH = os.path.join(HOME_NINJA_PATH, 'settings.ini') ADDINS = os.path.join(HOME_NINJA_PATH, "addins") SYNTAX_FILES = os.path.join(PRJ_PATH, "addins", "syntax") PLUGINS = os.path.join(HOME_NINJA_PATH, "addins", "plugins") PLUGINS_DESCRIPTOR = os.path.join(HOME_NINJA_PATH, "addins", "plugins", "descriptor.json") LANGS = os.path.join(PRJ_PATH, "addins", "lang") LANGS_DOWNLOAD = os.path.join(HOME_NINJA_PATH, "addins", "languages") EDITOR_SKINS = os.path.join(HOME_NINJA_PATH, "addins", "schemes") START_PAGE_URL = os.path.join(HOME_NINJA_PATH, "html", "startPage.html") NINJA_THEME = os.path.join(PRJ_PATH, "addins", "theme", "ninja_dark.qss") NINJA__THEME_CLASSIC = os.path.join( PRJ_PATH, "addins", "theme", "ninja_theme.qss") NINJA_THEME_DOWNLOAD = os.path.join(HOME_NINJA_PATH, "addins", "theme") LOG_FILE_PATH = os.path.join(HOME_NINJA_PATH, 'ninja_ide.log') GET_SYSTEM_PATH = os.path.join(PRJ_PATH, 'tools', 'get_system_path.py') QML_FILES = os.path.join(PRJ_PATH, "addins", "qml") ############################################################################### # URLS (Preserve the ninja-ide community to get support) ############################################################################### BUGS_PAGE = "http://ide.motivation.ga/issues" PLUGINS_DOC = "http://ninja-ide.readthedocs.org/en/latest/" UPDATES_URL = 'http://ninja-ide.org/updates' SCHEMES_URL = 'http://ninja-ide.org/schemes/api/' LANGUAGES_URL = 'http://ninja-ide.org/plugins/languages' PLUGINS_WEB = 'http://ninja-ide.org/plugins/api/official' PLUGINS_COMMUNITY = 'http://ninja-ide.org/plugins/api/community' ############################################################################### # IMAGES ############################################################################### IMAGES = { "splash": os.path.join(PRJ_PATH, "img", "splash.png"), "icon": os.path.join(PRJ_PATH, "img", "icon.png"), "iconUpdate": os.path.join(PRJ_PATH, "img", "icon.png"), "new": os.path.join(PRJ_PATH, "img", "document-new.png"), "newProj": os.path.join(PRJ_PATH, "img", "project-new.png"), "open": os.path.join(PRJ_PATH, "img", "document-open.png"), "openProj": os.path.join(PRJ_PATH, "img", "project-open.png"), "openFolder": os.path.join(PRJ_PATH, "img", "folder-open.png"), "save": os.path.join(PRJ_PATH, "img", "document-save.png"), "saveAs": os.path.join(PRJ_PATH, "img", "document-save-as.png"), "saveAll": os.path.join(PRJ_PATH, "img", "document-save-all.png"), "activate-profile": os.path.join(PRJ_PATH, "img", "activate_profile.png"), "deactivate-profile": os.path.join(PRJ_PATH, "img", "deactivate_profile.png"), "copy": os.path.join(PRJ_PATH, "img", "edit-copy.png"), "cut": os.path.join(PRJ_PATH, "img", "edit-cut.png"), "paste": os.path.join(PRJ_PATH, "img", "edit-paste.png"), "redo": os.path.join(PRJ_PATH, "img", "edit-redo.png"), "undo": os.path.join(PRJ_PATH, "img", "edit-undo.png"), "exit": os.path.join(PRJ_PATH, "img", "exit.png"), "find": os.path.join(PRJ_PATH, "img", "find.png"), "findReplace": os.path.join(PRJ_PATH, "img", "find-replace.png"), "locator": os.path.join(PRJ_PATH, "img", "locator.png"), "play": os.path.join(PRJ_PATH, "img", "play.png"), "stop": os.path.join(PRJ_PATH, "img", "stop.png"), "file-run": os.path.join(PRJ_PATH, "img", "file-run.png"), "preview-web": os.path.join(PRJ_PATH, "img", "preview_web.png"), "debug": os.path.join(PRJ_PATH, "img", "debug.png"), "designer": os.path.join(PRJ_PATH, "img", "qtdesigner.png"), "bug": os.path.join(PRJ_PATH, "img", "bug.png"), "function": os.path.join(PRJ_PATH, "img", "function.png"), "module": os.path.join(PRJ_PATH, "img", "module.png"), "class": os.path.join(PRJ_PATH, "img", "class.png"), "attribute": os.path.join(PRJ_PATH, "img", "attribute.png"), "web": os.path.join(PRJ_PATH, "img", "web.png"), "fullscreen": os.path.join(PRJ_PATH, "img", "fullscreen.png"), "follow": os.path.join(PRJ_PATH, "img", "follow.png"), "splitH": os.path.join(PRJ_PATH, "img", "split-horizontal.png"), "splitV": os.path.join(PRJ_PATH, "img", "split-vertical.png"), "zoom-in": os.path.join(PRJ_PATH, "img", "zoom_in.png"), "zoom-out": os.path.join(PRJ_PATH, "img", "zoom_out.png"), "splitCPosition": os.path.join(PRJ_PATH, "img", "panels-change-position.png"), "splitMPosition": os.path.join(PRJ_PATH, "img", "panels-change-vertical-position.png"), "splitCRotate": os.path.join(PRJ_PATH, "img", "panels-change-orientation.png"), "indent-less": os.path.join(PRJ_PATH, "img", "indent-less.png"), "indent-more": os.path.join(PRJ_PATH, "img", "indent-more.png"), "go-to-definition": os.path.join(PRJ_PATH, "img", "go_to_definition.png"), "insert-import": os.path.join(PRJ_PATH, "img", "insert_import.png"), "console": os.path.join(PRJ_PATH, "img", "console.png"), "pref": os.path.join(PRJ_PATH, "img", "preferences-system.png"), "tree-app": os.path.join(PRJ_PATH, "img", "tree-app.png"), "tree-code": os.path.join(PRJ_PATH, "img", "tree-code.png"), "tree-folder": os.path.join(PRJ_PATH, "img", "tree-folder.png"), "tree-html": os.path.join(PRJ_PATH, "img", "tree-html.png"), "tree-generic": os.path.join(PRJ_PATH, "img", "tree-generic.png"), "tree-css": os.path.join(PRJ_PATH, "img", "tree-CSS.png"), "tree-python": os.path.join(PRJ_PATH, "img", "tree-python.png"), "tree-image": os.path.join(PRJ_PATH, "img", "tree-image.png"), "comment-code": os.path.join(PRJ_PATH, "img", "comment-code.png"), "uncomment-code": os.path.join(PRJ_PATH, "img", "uncomment-code.png"), "reload-file": os.path.join(PRJ_PATH, "img", "reload-file.png"), "print": os.path.join(PRJ_PATH, "img", "document-print.png"), "book-left": os.path.join(PRJ_PATH, "img", "book-left.png"), "book-right": os.path.join(PRJ_PATH, "img", "book-right.png"), "break-left": os.path.join(PRJ_PATH, "img", "break-left.png"), "break-right": os.path.join(PRJ_PATH, "img", "break-right.png"), "nav-code-left": os.path.join(PRJ_PATH, "img", "nav-code-left.png"), "nav-code-right": os.path.join(PRJ_PATH, "img", "nav-code-right.png"), "locate-file": os.path.join(PRJ_PATH, "img", "locate-file.png"), "locate-class": os.path.join(PRJ_PATH, "img", "locate-class.png"), "locate-function": os.path.join(PRJ_PATH, "img", "locate-function.png"), "locate-attributes": os.path.join(PRJ_PATH, "img", "locate-attributes.png"), "locate-nonpython": os.path.join(PRJ_PATH, "img", "locate-nonpython.png"), "locate-on-this-file": os.path.join(PRJ_PATH, "img", "locate-on-this-file.png"), "locate-tab": os.path.join(PRJ_PATH, "img", "locate-tab.png"), "locate-line": os.path.join(PRJ_PATH, "img", "locate-line.png"), "add": os.path.join(PRJ_PATH, "img", "add.png"), "delete": os.path.join(PRJ_PATH, "img", "delete.png"), "loading": os.path.join(PRJ_PATH, "img", "loading.gif"), "separator": os.path.join(PRJ_PATH, "img", "separator.png")} ############################################################################### # COLOR SCHEMES ############################################################################### COLOR_SCHEME = { "keyword": "#6EC7D7", "operator": "#FFFFFF", "brace": "#FFFFFF", "definition": "#F6EC2A", "string": "#B369BF", "string2": "#86d986", "comment": "#80FF80", "properObject": "#6EC7D7", "numbers": "#F8A008", "spaces": "#7b7b7b", "extras": "#ee8859", "editor-background": "#1E1E1E", "editor-selection-color": "#FFFFFF", "editor-selection-background": "#437DCD", "editor-text": "#B3BFA7", "current-line": "#858585", "selected-word": "red", "pending": "red", "selected-word-background": "#009B00", "fold-area": "#FFFFFF", "fold-arrow": "#454545", "linkNavigate": "orange", "brace-background": "#5BC85B", "brace-foreground": "red", "error-underline": "red", "pep8-underline": "yellow", "sidebar-background": "#c4c4c4", "sidebar-foreground": "black", "locator-name": "white", "locator-name-selected": "black", "locator-path": "gray", "locator-path-selected": "white", "migration-underline": "blue", "current-line-opacity": 20, "error-background-opacity": 60, } CUSTOM_SCHEME = {} ############################################################################### # SHORTCUTS ############################################################################### #default shortcuts SHORTCUTS = { "Duplicate": QKeySequence(Qt.CTRL + Qt.Key_R), # Replicate "Remove-line": QKeySequence(Qt.CTRL + Qt.Key_E), # Eliminate "Move-up": QKeySequence(Qt.ALT + Qt.Key_Up), "Move-down": QKeySequence(Qt.ALT + Qt.Key_Down), "Close-tab": QKeySequence(Qt.CTRL + Qt.Key_W), "New-file": QKeySequence(Qt.CTRL + Qt.Key_N), "New-project": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_N), "Open-file": QKeySequence(Qt.CTRL + Qt.Key_O), "Open-project": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_O), "Save-file": QKeySequence(Qt.CTRL + Qt.Key_S), "Save-project": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_S), "Print-file": QKeySequence(Qt.CTRL + Qt.Key_P), "Redo": QKeySequence(Qt.CTRL + Qt.Key_Y), "Comment": QKeySequence(Qt.CTRL + Qt.Key_D), "Uncomment": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_D), "Horizontal-line": QKeySequence(), "Title-comment": QKeySequence(), "Indent-less": QKeySequence(Qt.SHIFT + Qt.Key_Tab), "Hide-misc": QKeySequence(Qt.Key_F4), "Hide-editor": QKeySequence(Qt.Key_F3), "Hide-explorer": QKeySequence(Qt.Key_F2), "Run-file": QKeySequence(Qt.CTRL + Qt.Key_F6), "Run-project": QKeySequence(Qt.Key_F6), "Debug": QKeySequence(Qt.Key_F7), "Switch-Focus": QKeySequence(Qt.CTRL + Qt.Key_QuoteLeft), "Stop-execution": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F6), "Hide-all": QKeySequence(Qt.Key_F11), "Full-screen": QKeySequence(Qt.CTRL + Qt.Key_F11), "Find": QKeySequence(Qt.CTRL + Qt.Key_F), "Find-replace": QKeySequence(Qt.CTRL + Qt.Key_H), "Find-with-word": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_F), "Find-next": QKeySequence(Qt.CTRL + Qt.Key_F3), "Find-previous": QKeySequence(Qt.SHIFT + Qt.Key_F3), "Help": QKeySequence(Qt.Key_F1), "Split-horizontal": QKeySequence(Qt.Key_F9), "Split-vertical": QKeySequence(Qt.Key_F10), "Follow-mode": QKeySequence(Qt.CTRL + Qt.Key_F10), "Reload-file": QKeySequence(Qt.Key_F5), "Find-in-files": QKeySequence(Qt.CTRL + Qt.Key_L), "Import": QKeySequence(Qt.CTRL + Qt.Key_I), "Go-to-definition": QKeySequence(Qt.CTRL + Qt.Key_Return), "Complete-Declarations": QKeySequence(Qt.ALT + Qt.Key_Return), "Code-locator": QKeySequence(Qt.CTRL + Qt.Key_K), "File-Opener": QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_O), "Navigate-back": QKeySequence(Qt.ALT + Qt.Key_Left), "Navigate-forward": QKeySequence(Qt.ALT + Qt.Key_Right), "Open-recent-closed": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_T), "Change-Tab": QKeySequence(Qt.CTRL + Qt.Key_PageDown), "Change-Tab-Reverse": QKeySequence(Qt.CTRL + Qt.Key_PageUp), "Move-Tab-to-right": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_0),
[ " \"Move-Tab-to-left\": QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_9)," ]
902
lcc
python
null
a4712b2e717d6693fc9b69d66fce23e4ec1069203a8569a4
/* * Copyright 2002-2010 the original author or 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. */ package org.springframework.orm.jpa.persistenceunit; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.Properties; import javax.persistence.spi.ClassTransformer; import javax.persistence.spi.PersistenceUnitTransactionType; import javax.sql.DataSource; import org.springframework.util.ClassUtils; /** * Spring's base implementation of the JPA * {@link javax.persistence.spi.PersistenceUnitInfo} interface, * used to bootstrap an EntityManagerFactory in a container. * * <p>This implementation is largely a JavaBean, offering mutators * for all standard PersistenceUnitInfo properties. * * @author Rod Johnson * @author Juergen Hoeller * @author Costin Leau * @since 2.0 */ public class MutablePersistenceUnitInfo implements SmartPersistenceUnitInfo { private String persistenceUnitName; private String persistenceProviderClassName; private PersistenceUnitTransactionType transactionType; private DataSource nonJtaDataSource; private DataSource jtaDataSource; private List<String> mappingFileNames = new LinkedList<String>(); private List<URL> jarFileUrls = new LinkedList<URL>(); private URL persistenceUnitRootUrl; private List<String> managedClassNames = new LinkedList<String>(); private boolean excludeUnlistedClasses = false; private Properties properties = new Properties(); private String persistenceXMLSchemaVersion = "1.0"; private String persistenceProviderPackageName; public void setPersistenceUnitName(String persistenceUnitName) { this.persistenceUnitName = persistenceUnitName; } public String getPersistenceUnitName() { return this.persistenceUnitName; } public void setPersistenceProviderClassName(String persistenceProviderClassName) { this.persistenceProviderClassName = persistenceProviderClassName; } public String getPersistenceProviderClassName() { return this.persistenceProviderClassName; } public void setTransactionType(PersistenceUnitTransactionType transactionType) { this.transactionType = transactionType; } public PersistenceUnitTransactionType getTransactionType() { if (this.transactionType != null) { return this.transactionType; } else { return (this.jtaDataSource != null ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL); } } public void setJtaDataSource(DataSource jtaDataSource) { this.jtaDataSource = jtaDataSource; } public DataSource getJtaDataSource() { return this.jtaDataSource; } public void setNonJtaDataSource(DataSource nonJtaDataSource) { this.nonJtaDataSource = nonJtaDataSource; } public DataSource getNonJtaDataSource() { return this.nonJtaDataSource; } public void addMappingFileName(String mappingFileName) { this.mappingFileNames.add(mappingFileName); } public List<String> getMappingFileNames() { return this.mappingFileNames; } public void addJarFileUrl(URL jarFileUrl) { this.jarFileUrls.add(jarFileUrl); } public List<URL> getJarFileUrls() { return this.jarFileUrls; } public void setPersistenceUnitRootUrl(URL persistenceUnitRootUrl) { this.persistenceUnitRootUrl = persistenceUnitRootUrl; } public URL getPersistenceUnitRootUrl() { return this.persistenceUnitRootUrl; } public void addManagedClassName(String managedClassName) { this.managedClassNames.add(managedClassName); } public List<String> getManagedClassNames() { return this.managedClassNames; } public void setExcludeUnlistedClasses(boolean excludeUnlistedClasses) { this.excludeUnlistedClasses = excludeUnlistedClasses; } public boolean excludeUnlistedClasses() { return this.excludeUnlistedClasses; } public void addProperty(String name, String value) { if (this.properties == null) { this.properties = new Properties(); } this.properties.setProperty(name, value); } public void setProperties(Properties properties) { this.properties = properties; } public Properties getProperties() { return this.properties; } public void setPersistenceXMLSchemaVersion(String persistenceXMLSchemaVersion) { this.persistenceXMLSchemaVersion = persistenceXMLSchemaVersion; } public String getPersistenceXMLSchemaVersion() { return this.persistenceXMLSchemaVersion; } public void setPersistenceProviderPackageName(String persistenceProviderPackageName) { this.persistenceProviderPackageName = persistenceProviderPackageName; } public String getPersistenceProviderPackageName() { return this.persistenceProviderPackageName; } /** * This implementation returns the default ClassLoader. * @see org.springframework.util.ClassUtils#getDefaultClassLoader() */ public ClassLoader getClassLoader() { return ClassUtils.getDefaultClassLoader(); } /** * This implementation throws an UnsupportedOperationException. */ public void addTransformer(ClassTransformer classTransformer) { throw new UnsupportedOperationException("addTransformer not supported"); } /** * This implementation throws an UnsupportedOperationException. */ public ClassLoader getNewTempClassLoader() { throw new UnsupportedOperationException("getNewTempClassLoader not supported"); } @Override public String toString() {
[ "\t\tStringBuilder builder = new StringBuilder();" ]
538
lcc
java
null
fa471400c4273aa3192c4acebefee0003fad434d98173787
/******************************************************************************* * Copyright (c) 2001, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.wst.xsd.ui.internal.adt.design.editparts; import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.AccessibleEditPart; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPartFactory; import org.eclipse.gef.GraphicalViewer; import org.eclipse.gef.editparts.AbstractGraphicalEditPart; import org.eclipse.gef.editparts.ScalableRootEditPart; import org.eclipse.gef.editparts.ZoomListener; import org.eclipse.gef.editparts.ZoomManager; import org.eclipse.jface.action.IAction; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.FileStoreEditorInput; import org.eclipse.wst.xsd.ui.internal.adt.design.editparts.model.IActionProvider; import org.eclipse.wst.xsd.ui.internal.adt.design.editparts.model.IFeedbackHandler; import org.eclipse.wst.xsd.ui.internal.adt.design.editpolicies.KeyBoardAccessibilityEditPolicy; import org.eclipse.wst.xsd.ui.internal.adt.design.figures.IFigureFactory; import org.eclipse.wst.xsd.ui.internal.adt.editor.CommonMultiPageEditor; import org.eclipse.wst.xsd.ui.internal.adt.facade.IADTObject; import org.eclipse.wst.xsd.ui.internal.adt.facade.IADTObjectListener; public abstract class BaseEditPart extends AbstractGraphicalEditPart implements IActionProvider, IADTObjectListener, IFeedbackHandler { protected static final String[] EMPTY_ACTION_ARRAY = {}; protected boolean isSelected = false; protected boolean hasFocus = false; protected static boolean isHighContrast = Display.getDefault().getHighContrast(); protected AccessibleEditPart accessiblePart; public IFigureFactory getFigureFactory() { EditPartFactory factory = getViewer().getEditPartFactory(); Assert.isTrue(factory instanceof IFigureFactory, "EditPartFactory must be an instanceof of IFigureFactory"); //$NON-NLS-1$ return (IFigureFactory)factory; } public String[] getActions(Object object) { Object model = getModel(); if (model instanceof IActionProvider) { return ((IActionProvider)model).getActions(object); } return EMPTY_ACTION_ARRAY; } protected void addActionsToList(List list, IAction[] actions) { for (int i = 0; i < actions.length; i++) { list.add(actions[i]); } } public void activate() { super.activate(); Object model = getModel(); if (model instanceof IADTObject) { IADTObject object = (IADTObject)model; object.registerListener(this); } if (getZoomManager() != null) getZoomManager().addZoomListener(zoomListener); } public void deactivate() { try { Object model = getModel(); if (model instanceof IADTObject) { IADTObject object = (IADTObject)model; object.unregisterListener(this); } if (getZoomManager() != null) getZoomManager().removeZoomListener(zoomListener); } finally { super.deactivate(); } } public void propertyChanged(Object object, String property) { refresh(); } public void refresh() { boolean doUpdateDesign = doUpdateDesign(); if (doUpdateDesign) { super.refresh(); } } public void addFeedback() { isSelected = true; refreshVisuals(); } public void removeFeedback() { isSelected = false; refreshVisuals(); } public ZoomManager getZoomManager() { return ((ScalableRootEditPart)getRoot()).getZoomManager(); } public Rectangle getZoomedBounds(Rectangle r) { double factor = getZoomManager().getZoom(); int x = (int)Math.round(r.x * factor); int y = (int)Math.round(r.y * factor); int width = (int)Math.round(r.width * factor); int height = (int)Math.round(r.height * factor); return new Rectangle(x, y, width, height); } private ZoomListener zoomListener = new ZoomListener() { public void zoomChanged(double zoom) { handleZoomChanged(); } }; protected void handleZoomChanged() { refreshVisuals(); } public IEditorPart getEditorPart() { IEditorPart editorPart = null; IWorkbench workbench = PlatformUI.getWorkbench(); if (workbench != null) { IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow(); if (workbenchWindow != null) { if (workbenchWindow.getActivePage() != null) { editorPart = workbenchWindow.getActivePage().getActiveEditor(); } } } // Assert.isNotNull(editorPart); return editorPart; } protected void createEditPolicies() { installEditPolicy(KeyBoardAccessibilityEditPolicy.KEY, new KeyBoardAccessibilityEditPolicy() { public EditPart getRelativeEditPart(EditPart editPart, int direction) { return doGetRelativeEditPart(editPart, direction); } }); } public EditPart doGetRelativeEditPart(EditPart editPart, int direction) { return null; } protected boolean isFileReadOnly() {
[ " IWorkbench workbench = PlatformUI.getWorkbench();" ]
469
lcc
java
null
376650a8fc449c6f93baab1f5327f682bda670ea2bbdcc0b
using System; using System.Windows.Forms; using System.Diagnostics; using OpenDentBusiness; using OpenDental.UI; using System.Collections.Generic; using System.IO; using CodeBase; namespace OpenDental{ /// <summary> /// Summary description for FormBasicTemplate. /// </summary> public class FormEmailTemplateEdit : System.Windows.Forms.Form{ private OpenDental.UI.Button butCancel; private OpenDental.UI.Button butOK; /// <summary>Required designer variable.</summary> private System.ComponentModel.Container components = null; private System.Windows.Forms.Label label2; private OpenDental.ODtextBox textBodyText; ///<summary></summary> public bool IsNew; private Label label1; private Label label3; private UI.Button butBodyFields; private ODtextBox textSubject; private ODtextBox textDescription; ///<summary></summary> public EmailTemplate ETcur; private UI.Button butAttach; private UI.ODGrid gridAttachments; private UI.Button butSubjectFields; private List<EmailAttach> _listEmailAttachDisplayed; private ContextMenu contextMenuAttachments; private MenuItem menuItemOpen; private MenuItem menuItemRename; private MenuItem menuItemRemove; private List<EmailAttach> _listEmailAttachOld=new List<EmailAttach>(); ///<summary></summary> public FormEmailTemplateEdit() { // // Required for Windows Form Designer support // InitializeComponent(); Lan.F(this); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormEmailTemplateEdit)); this.butCancel = new OpenDental.UI.Button(); this.butOK = new OpenDental.UI.Button(); this.label2 = new System.Windows.Forms.Label(); this.textBodyText = new OpenDental.ODtextBox(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.butBodyFields = new OpenDental.UI.Button(); this.textSubject = new OpenDental.ODtextBox(); this.textDescription = new OpenDental.ODtextBox(); this.butSubjectFields = new OpenDental.UI.Button(); this.butAttach = new OpenDental.UI.Button(); this.gridAttachments = new OpenDental.UI.ODGrid(); this.contextMenuAttachments = new System.Windows.Forms.ContextMenu(); this.menuItemOpen = new System.Windows.Forms.MenuItem(); this.menuItemRename = new System.Windows.Forms.MenuItem(); this.menuItemRemove = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // butCancel // this.butCancel.AdjustImageLocation = new System.Drawing.Point(0, 0); this.butCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.butCancel.Autosize = true; this.butCancel.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle; this.butCancel.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver; this.butCancel.CornerRadius = 4F; this.butCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.butCancel.Location = new System.Drawing.Point(883, 656); this.butCancel.Name = "butCancel"; this.butCancel.Size = new System.Drawing.Size(75, 25); this.butCancel.TabIndex = 6; this.butCancel.Text = "&Cancel"; this.butCancel.Click += new System.EventHandler(this.butCancel_Click); // // butOK // this.butOK.AdjustImageLocation = new System.Drawing.Point(0, 0); this.butOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.butOK.Autosize = true; this.butOK.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle; this.butOK.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver; this.butOK.CornerRadius = 4F; this.butOK.Location = new System.Drawing.Point(802, 656); this.butOK.Name = "butOK"; this.butOK.Size = new System.Drawing.Size(75, 25); this.butOK.TabIndex = 5; this.butOK.Text = "&OK"; this.butOK.Click += new System.EventHandler(this.butOK_Click); // // label2 // this.label2.Location = new System.Drawing.Point(8, 65); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(88, 20); this.label2.TabIndex = 0; this.label2.Text = "Subject"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // textBodyText // this.textBodyText.AcceptsTab = true; this.textBodyText.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBodyText.DetectUrls = false; this.textBodyText.Location = new System.Drawing.Point(97, 86); this.textBodyText.Name = "textBodyText"; this.textBodyText.QuickPasteType = OpenDentBusiness.QuickPasteType.Email; this.textBodyText.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical; this.textBodyText.Size = new System.Drawing.Size(861, 564); this.textBodyText.TabIndex = 3; this.textBodyText.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(8, 86); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 20); this.label1.TabIndex = 0; this.label1.Text = "Body"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label3 // this.label3.Location = new System.Drawing.Point(8, 44); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(88, 20); this.label3.TabIndex = 0; this.label3.Text = "Description"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // butBodyFields // this.butBodyFields.AdjustImageLocation = new System.Drawing.Point(0, 0); this.butBodyFields.Autosize = true; this.butBodyFields.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle; this.butBodyFields.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver; this.butBodyFields.CornerRadius = 4F; this.butBodyFields.Location = new System.Drawing.Point(182, 23); this.butBodyFields.Name = "butBodyFields"; this.butBodyFields.Size = new System.Drawing.Size(82, 20); this.butBodyFields.TabIndex = 4; this.butBodyFields.Text = "Body Fields"; this.butBodyFields.Click += new System.EventHandler(this.butBodyFields_Click); // // textSubject // this.textSubject.AcceptsTab = true; this.textSubject.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textSubject.DetectUrls = false; this.textSubject.Location = new System.Drawing.Point(97, 65); this.textSubject.Multiline = false; this.textSubject.Name = "textSubject"; this.textSubject.QuickPasteType = OpenDentBusiness.QuickPasteType.None; this.textSubject.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical; this.textSubject.Size = new System.Drawing.Size(635, 20); this.textSubject.TabIndex = 2; this.textSubject.Text = ""; // // textDescription // this.textDescription.AcceptsTab = true; this.textDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textDescription.DetectUrls = false; this.textDescription.Location = new System.Drawing.Point(97, 44); this.textDescription.Multiline = false; this.textDescription.Name = "textDescription"; this.textDescription.QuickPasteType = OpenDentBusiness.QuickPasteType.None; this.textDescription.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Vertical; this.textDescription.Size = new System.Drawing.Size(635, 20); this.textDescription.TabIndex = 1; this.textDescription.Text = ""; // // butSubjectFields // this.butSubjectFields.AdjustImageLocation = new System.Drawing.Point(0, 0); this.butSubjectFields.Autosize = true; this.butSubjectFields.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle; this.butSubjectFields.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver; this.butSubjectFields.CornerRadius = 4F; this.butSubjectFields.Location = new System.Drawing.Point(97, 23); this.butSubjectFields.Name = "butSubjectFields"; this.butSubjectFields.Size = new System.Drawing.Size(82, 20); this.butSubjectFields.TabIndex = 7; this.butSubjectFields.Text = "Subject Fields"; this.butSubjectFields.Click += new System.EventHandler(this.butSubjectFields_Click); // // butAttach // this.butAttach.AdjustImageLocation = new System.Drawing.Point(0, 0); this.butAttach.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.butAttach.Autosize = true; this.butAttach.BtnShape = OpenDental.UI.enumType.BtnShape.Rectangle; this.butAttach.BtnStyle = OpenDental.UI.enumType.XPStyle.Silver; this.butAttach.CornerRadius = 4F;
[ "\t\t\tthis.butAttach.Location = new System.Drawing.Point(738, 2);" ]
692
lcc
csharp
null
c4cefa2a1ddbaac52ded7360c79296813666aad6d9e178b1
package org.alfresco.web.awe.tag; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; /** * Tag utilities for Alfresco Web Editor * * @author muzquiano */ public class AlfrescoTagUtil { public static final String KEY_MARKER_ID_PREFIX = "awe_marker_id_prefix"; public static final String KEY_EDITABLE_CONTENT = "awe_editable_content"; /** * Returns the list of marked content that has been discovered. * <p> * This list is built up as each markContent tag is encountered. * </p> * * @return List of MarkedContent objects */ @SuppressWarnings("unchecked") public static List<MarkedContent> getMarkedContent(ServletRequest request) { List<MarkedContent> markedContent = (List<MarkedContent>) request.getAttribute(KEY_EDITABLE_CONTENT); if (markedContent == null) { markedContent = new ArrayList<MarkedContent>(); request.setAttribute(KEY_EDITABLE_CONTENT, markedContent); } return markedContent; } public static void writeMarkContentHtml(Writer out, String urlPrefix, String redirectUrl, MarkedContent content) throws IOException, UnsupportedEncodingException { String contentId = content.getContentId(); String contentTitle = content.getContentTitle(); String formId = content.getFormId(); String editMarkerId = content.getMarkerId(); // Hide initially, in case we need to log in or user does not want to // log in out.write("<span class=\"alfresco-content-marker\" style=\"display: none\" id=\""); out.write(editMarkerId); out.write("\">"); // render edit link for content out.write("<a class=\"alfresco-content-edit\" href=\""); out.write(urlPrefix); out.write("/page/metadata?nodeRef="); out.write(contentId); out.write("&js=off"); if (contentTitle != null) { out.write("&title="); out.write(URLEncoder.encode(contentTitle, "UTF-8")); } if (redirectUrl != null) { out.write("&redirect="); out.write(redirectUrl); } if (formId != null) { out.write("&formId="); out.write(formId); } out.write("\"><img src=\""); out.write(urlPrefix); out.write("/res/awe/images/edit.png\" alt=\""); out.write(encode(contentTitle == null ? "" : contentTitle)); out.write("\" title=\""); out.write(encode(contentTitle == null ? "" : contentTitle)); out.write("\"border=\"0\" /></a>"); // render create link for content out.write("<a class=\"alfresco-content-new\" href=\""); out.write(urlPrefix); out.write("/page/metadata?nodeRef="); out.write(contentId); out.write("&js=off"); if (contentTitle != null) { out.write("&title="); out.write(URLEncoder.encode(contentTitle, "UTF-8")); } if (redirectUrl != null) { out.write("&redirect="); out.write(redirectUrl); } if (formId != null) { out.write("&formId="); out.write(formId); } out.write("\"><img src=\""); out.write(urlPrefix); out.write("/res/awe/images/new.png\" alt=\""); out.write(encode(contentTitle == null ? "" : contentTitle)); out.write("\" title=\""); out.write(encode(contentTitle == null ? "" : contentTitle)); out.write("\"border=\"0\" /></a>"); // render delete link for content out.write("<a class=\"alfresco-content-delete\" href=\""); out.write(urlPrefix); // TODO out.write("/page/metadata?nodeRef="); out.write(contentId); out.write("&js=off"); if (contentTitle != null) { out.write("&title="); out.write(URLEncoder.encode(contentTitle, "UTF-8")); } if (redirectUrl != null) { out.write("&redirect="); out.write(redirectUrl); } if (formId != null) { out.write("&formId="); out.write(formId); } out.write("\"><img src=\""); out.write(urlPrefix); out.write("/res/awe/images/delete.png\" alt=\""); out.write(encode(contentTitle == null ? "" : contentTitle)); out.write("\" title=\""); out.write(encode(contentTitle == null ? "" : contentTitle)); out.write("\"border=\"0\" /></a>"); out.write("</span>\n"); } /** * Calculates the redirect url for form submission, this will * be the current request URL. * * @return The redirect URL */ public static String calculateRedirectUrl(HttpServletRequest request) { // NOTE: This may become configurable in the future, for now // this just returns the current page's URI String redirectUrl = null; try { StringBuffer url = request.getRequestURL(); String queryString = request.getQueryString(); if (queryString != null) { url.append("?").append(queryString); } redirectUrl = URLEncoder.encode(url.toString(), "UTF-8"); } catch (UnsupportedEncodingException uee) { // just return null } return redirectUrl; } /** * Encodes the given string, so that it can be used within an HTML page. * * @param string the String to convert */ public static String encode(String string) { if (string == null) { return ""; } StringBuilder sb = null; // create on demand String enc; char c; for (int i = 0; i < string.length(); i++) { enc = null; c = string.charAt(i); switch (c) { case '"': enc = "&quot;"; break; //" case '&': enc = "&amp;"; break; //& case '<': enc = "&lt;"; break; //< case '>': enc = "&gt;"; break; //> case '\u20AC': enc = "&euro;"; break; case '\u00AB': enc = "&laquo;"; break; case '\u00BB': enc = "&raquo;"; break; case '\u00A0': enc = "&nbsp;"; break; default: if (((int)c) >= 0x80) { //encode all non basic latin characters enc = "&#" + ((int)c) + ";"; } break; } if (enc != null) { if (sb == null) { String soFar = string.substring(0, i); sb = new StringBuilder(i + 16); sb.append(soFar); } sb.append(enc); } else { if (sb != null) { sb.append(c); } } }
[ " if (sb == null)" ]
627
lcc
java
null
1425b06afee32d16a5355b9b1c74c573855e0bfe86164222
// // HMACSHA512Test.cs - NUnit Test Cases for HMACSHA512 // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2006, 2007 Novell, Inc (http://www.novell.com) // using NUnit.Framework; using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace MonoTests.System.Security.Cryptography { public class HS512 : HMACSHA512 { public int BlockSize { get { return base.BlockSizeValue; } set { base.BlockSizeValue = value; } } } public class SelectableHmacSha512: HMAC { // Legacy parameter explanation: // http://blogs.msdn.com/shawnfa/archive/2007/01/31/please-do-not-use-the-net-2-0-hmacsha512-and-hmacsha384-classes.aspx public SelectableHmacSha512 (byte[] key, bool legacy) { HashName = "SHA512"; HashSizeValue = 512; BlockSizeValue = legacy ? 64 : 128; Key = key; } } // References: // a. Identifiers and Test Vectors for HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, and HMAC-SHA-512 // http://www.ietf.org/rfc/rfc4231.txt [TestFixture] public class HMACSHA512Test : KeyedHashAlgorithmTest { protected HMACSHA512 algo; [SetUp] public override void SetUp () { algo = new HMACSHA512 (); algo.Key = new byte [8]; hash = algo; } // the hash algorithm only exists as a managed implementation public override bool ManagedHashImplementation { get { return true; } } [Test] public void Constructors () { algo = new HMACSHA512 (); Assert.IsNotNull (algo, "HMACSHA512 ()"); byte[] key = new byte [8]; algo = new HMACSHA512 (key); Assert.IsNotNull (algo, "HMACSHA512 (key)"); } [Test] [ExpectedException (typeof (NullReferenceException))] public void Constructor_Null () { new HMACSHA512 (null); } [Test] public void Invariants () { algo = new HMACSHA512 (); Assert.IsTrue (algo.CanReuseTransform, "HMACSHA512.CanReuseTransform"); Assert.IsTrue (algo.CanTransformMultipleBlocks, "HMACSHA512.CanTransformMultipleBlocks"); Assert.AreEqual ("SHA512", algo.HashName, "HMACSHA512.HashName"); Assert.AreEqual (512, algo.HashSize, "HMACSHA512.HashSize"); Assert.AreEqual (1, algo.InputBlockSize, "HMACSHA512.InputBlockSize"); Assert.AreEqual (1, algo.OutputBlockSize, "HMACSHA512.OutputBlockSize"); Assert.AreEqual (128, algo.Key.Length, "HMACSHA512.Key.Length"); Assert.AreEqual ("System.Security.Cryptography.HMACSHA512", algo.ToString (), "HMACSHA512.ToString()"); } // some test case truncate the result private void Compare (byte[] expected, byte[] actual, string msg) { if (expected.Length == actual.Length) { Assert.AreEqual (expected, actual, msg); } else { byte[] data = new byte [expected.Length]; Array.Copy (actual, data, data.Length); Assert.AreEqual (expected, data, msg); } } public void Check (string testName, HMAC algo, byte[] data, byte[] result) { CheckA (testName, algo, data, result); CheckB (testName, algo, data, result); CheckC (testName, algo, data, result); CheckD (testName, algo, data, result); CheckE (testName, algo, data, result); } public void CheckA (string testName, HMAC algo, byte[] data, byte[] result) { byte[] hmac = algo.ComputeHash (data); Compare (result, hmac, testName + "a1"); Compare (result, algo.Hash, testName + "a2"); } public void CheckB (string testName, HMAC algo, byte[] data, byte[] result) { byte[] hmac = algo.ComputeHash (data, 0, data.Length); Compare (result, hmac, testName + "b1"); Compare (result, algo.Hash, testName + "b2"); } public void CheckC (string testName, HMAC algo, byte[] data, byte[] result) { using (MemoryStream ms = new MemoryStream (data)) { byte[] hmac = algo.ComputeHash (ms); Compare (result, hmac, testName + "c1"); Compare (result, algo.Hash, testName + "c2"); } } public void CheckD (string testName, HMAC algo, byte[] data, byte[] result) { algo.TransformFinalBlock (data, 0, data.Length); Compare (result, algo.Hash, testName + "d"); algo.Initialize (); } public void CheckE (string testName, HMAC algo, byte[] data, byte[] result) { byte[] copy = new byte[data.Length]; for (int i = 0; i < data.Length - 1; i++) algo.TransformBlock (data, i, 1, copy, i); algo.TransformFinalBlock (data, data.Length - 1, 1); Compare (result, algo.Hash, testName + "e"); algo.Initialize (); } [Test] public void RFC4231_TC1_Normal () { byte[] key = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; byte[] data = Encoding.Default.GetBytes ("Hi There"); byte[] digest = { 0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a, 0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0, 0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7, 0x02, 0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e, 0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54 }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC1", hmac, data, digest); } [Test] // Test with a key shorter than the length of the HMAC output. public void RFC4231_TC2_Normal () { byte[] key = Encoding.Default.GetBytes ("Jefe"); byte[] data = Encoding.Default.GetBytes ("what do ya want for nothing?"); byte[] digest = { 0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b, 0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27, 0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99, 0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3, 0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37 }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC2", hmac, data, digest); } [Test] // Test with a combined length of key and data that is larger than 64 bytes (= block-size of SHA-224 and SHA-256). public void RFC4231_TC3_Normal () { byte[] key = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; byte[] data = { 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd }; byte[] digest = { 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c, 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8, 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22, 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37, 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC3", hmac, data, digest); } [Test] // Test with a combined length of key and data that is larger than 64 bytes (= block-size of SHA-224 and SHA-256). public void RFC4231_TC4_Normal () { byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19 }; byte[] data = { 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd }; byte[] digest = { 0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6, 0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f, 0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e, 0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41, 0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC4", hmac, data, digest); } [Test] // Test with a truncation of output to 128 bits. public void RFC4231_TC5_Normal () { byte[] key = { 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }; byte[] data = Encoding.Default.GetBytes ("Test With Truncation"); byte[] digest = { 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53, 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6 }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC5", hmac, data, digest); } [Test] // Test with a key larger than 128 bytes (= block-size of SHA-384 and SHA-512). public void RFC4231_TC6_Normal () { byte[] key = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; byte[] data = Encoding.Default.GetBytes ("Test Using Larger Than Block-Size Key - Hash Key First"); byte[] digest = { 0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd, 0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b, 0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25, 0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73, 0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98 }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC6", hmac, data, digest); } [Test] // Test with a key and data that is larger than 128 bytes (= block-size of SHA-384 and SHA-512). public void RFC4231_TC7_Normal () { byte[] key = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; byte[] data = Encoding.Default.GetBytes ("This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm."); byte[] digest = { 0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e, 0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5, 0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82, 0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb, 0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58 }; HMAC hmac = new SelectableHmacSha512 (key, false); Check ("HMACSHA512-N-RFC4231-TC7", hmac, data, digest); } [Test] public void RFC4231_TC1_Legacy () { byte[] key = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; byte[] data = Encoding.Default.GetBytes ("Hi There"); byte[] digest = { 0x96, 0x56, 0x97, 0x5E, 0xE5, 0xDE, 0x55, 0xE7, 0x5F, 0x29, 0x76, 0xEC, 0xCE, 0x9A, 0x04, 0x50, 0x10, 0x60, 0xB9, 0xDC, 0x22, 0xA6, 0xED, 0xA2, 0xEA, 0xEF, 0x63, 0x89, 0x66, 0x28, 0x01, 0x82, 0x47, 0x7F, 0xE0, 0x9F, 0x08, 0x0B, 0x2B, 0xF5, 0x64, 0x64, 0x9C, 0xAD, 0x42, 0xAF, 0x86, 0x07, 0xA2, 0xBD, 0x8D, 0x02, 0x97, 0x9D, 0xF3, 0xA9, 0x80, 0xF1, 0x5E, 0x23, 0x26, 0xA0, 0xA2, 0x2A }; HMAC hmac = new SelectableHmacSha512 (key, true);
[ "\t\t\tCheck (\"HMACSHA512-L-RFC4231-TC1\", hmac, data, digest);" ]
1,867
lcc
csharp
null
5d5f9a55f0ca5e209dc65f2dc23ceaa77d3050df01057941
/* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages * * Copyright (C) 2014 Proyectos y Sistemas de Mantenimiento S.L. (eProsima) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library 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 library. If not, see <http://www.gnu.org/licenses/>. * * * @file EnumSwitchUnion.java * This file contains the class representing a user defined union. * * This file was generated by using the tool Kiaragen. * */ package org.fiware.kiara.serialization.types; import java.io.IOException; import org.fiware.kiara.serialization.impl.Serializable; import org.fiware.kiara.serialization.impl.SerializerImpl; import org.fiware.kiara.serialization.impl.CDRSerializer; import org.fiware.kiara.transport.impl.TransportMessage; import java.util.List; import java.util.ArrayList; import java.util.Objects; import org.fiware.kiara.serialization.impl.BasicSerializers; import org.fiware.kiara.serialization.impl.BinaryInputStream; import org.fiware.kiara.serialization.impl.BinaryOutputStream; import org.fiware.kiara.serialization.impl.Serializable; import org.fiware.kiara.serialization.impl.SerializerImpl; import org.fiware.kiara.serialization.impl.CDRSerializer; import org.fiware.kiara.serialization.impl.ListAsArraySerializer; import org.fiware.kiara.serialization.impl.ListAsSequenceSerializer; import org.fiware.kiara.serialization.impl.Serializer; import org.fiware.kiara.serialization.impl.MapAsMapSerializer; import org.fiware.kiara.serialization.impl.SetAsSetSerializer; import org.fiware.kiara.serialization.impl.ObjectSerializer; import org.fiware.kiara.serialization.impl.EnumSerializer; public class EnumSwitchUnion implements Serializable { private EnumSwitcher m_d; private int intVal; private java.lang.String stringVal; private float floatVal; public EnumSwitchUnion() { this.intVal = 0; this.stringVal = ""; this.floatVal = (float) 0.0; } public void _d(EnumSwitcher discriminator) { this.m_d = discriminator; } /* * @param other An object instance of Object */ @Override public boolean equals(Object other) { boolean comparison = true; if (other instanceof EnumSwitchUnion) { switch(this.m_d) { case option_1: case option_2: comparison = comparison && (this.intVal == ((EnumSwitchUnion) other).intVal); break; case option_3: comparison = comparison && (this.stringVal.compareTo(((EnumSwitchUnion) other).stringVal) == 0); break; default: comparison = comparison && (this.floatVal == ((EnumSwitchUnion) other).floatVal); break; } } return comparison; } /* * This method serializes a EnumSwitchUnion. * * @see org.fiware.kiara.serialization.impl.Serializable#serialize(org.fiware.kiara.serialization.impl.SerializerImpl, org.fiware.kiara.serialization.impl.BinaryOutputStream, java.lang.String) */ @Override public void serialize(SerializerImpl impl, BinaryOutputStream message, String name) throws IOException { impl.serializeEnum(message, name, this.m_d); switch(this.m_d) { case option_1: case option_2: impl.serializeI32(message, name, this.intVal); break; case option_3: impl.serializeString(message, name, this.stringVal); break; default: impl.serializeFloat32(message, name, this.floatVal); break; } } /* * This method deserializes a EnumSwitchUnion. * * @see org.fiware.kiara.serialization.impl.Serializable#deserialize(org.fiware.kiara.serialization.impl.SerializerImpl, org.fiware.kiara.serialization.impl.BinaryInputStream, java.lang.String) */ @Override public void deserialize(SerializerImpl impl, BinaryInputStream message, String name) throws IOException { this.m_d = impl.deserializeEnum(message, name, EnumSwitcher.class); switch(this.m_d) { case option_1: case option_2: this.intVal = impl.deserializeI32(message, name); break; case option_3: this.stringVal = impl.deserializeString(message, name); break; default: this.floatVal = impl.deserializeFloat32(message, name); break; } } /* * Method to get the attribute intVal. */ public int getIntVal() { boolean canDoIt = false; switch(this.m_d) { case option_1: case option_2: canDoIt=true; break; default: break; } if (!canDoIt) { throw new UnsupportedOperationException("Invalid union value"); } return this.intVal; } /* * Method to set the attribute intVal. */ public void setIntVal(int intVal) { boolean canDoIt = false; switch(this.m_d) { case option_1: case option_2: canDoIt=true; break; default: break; } if (!canDoIt) { throw new UnsupportedOperationException("Invalid union value"); } this.intVal = intVal; } /* * Method to get the attribute stringVal. */ public java.lang.String getStringVal() { boolean canDoIt = false; switch(this.m_d) { case option_3: canDoIt=true; break; default: break; } if (!canDoIt) { throw new UnsupportedOperationException("Invalid union value"); } return this.stringVal; } /* * Method to set the attribute stringVal. */ public void setStringVal(java.lang.String stringVal) { boolean canDoIt = false; switch(this.m_d) { case option_3: canDoIt=true; break; default: break; } if (!canDoIt) { throw new UnsupportedOperationException("Invalid union value"); } this.stringVal = stringVal; } /* * Method to get the attribute floatVal. */ public float getFloatVal() { boolean canDoIt = false; switch(this.m_d) { case option_1: case option_2: break; case option_3: break; default: canDoIt=true; break; } if (!canDoIt) { throw new UnsupportedOperationException("Invalid union value"); } return this.floatVal; } /* * Method to set the attribute floatVal. */ public void setFloatVal(float floatVal) { boolean canDoIt = false; switch(this.m_d) { case option_1: case option_2: break; case option_3: break; default: canDoIt=true; break; } if (!canDoIt) { throw new UnsupportedOperationException("Invalid union value"); } this.floatVal = floatVal; } /* *This method calculates the maximum size in CDR for this class. * * @param current_alignment Integer containing the current position in the buffer. */ public static int getMaxCdrSerializedSize(int current_alignment) { int current_align = current_alignment; int sum = 0; int current_sum = 0; current_align += 4 + CDRSerializer.alignment(current_align, 4); // Enum type
[ "\t current_sum += 4 + CDRSerializer.alignment(current_sum, 4);" ]
737
lcc
java
null
0acfff98f8a07512b57bf9de46cc67617183784cdd9c686d
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Alex Rojkov */ using System; using System.Reflection; using System.Collections; using System.Text; using System.IO; using Microsoft.Win32; using System.Diagnostics; using System.Windows.Forms; using System.ServiceProcess; using System.Threading; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Principal; namespace Caucho { public class Resin : ServiceBase { private static String HKEY_JRE = @"Software\JavaSoft\Java Runtime Environment"; private static String HKEY_JDK = @"Software\JavaSoft\Java Development Kit"; private static String CAUCHO_APP_DATA = @"Caucho Technology\Resin"; private String _javaExe; private String _javaHome; private String _resinHome; private String _rootDirectory; private Process _process; private ResinArgs ResinArgs; private static Mutex mutex = new Mutex(false, @"Global\com.caucho.Resin"); private Resin(ResinArgs args) { ResinArgs = args; _resinHome = ResinArgs.ResinHome; _rootDirectory = ResinArgs.ResinRoot; _javaHome = ResinArgs.JavaHome; } public bool StartResin() { try { if (ResinArgs.IsService) ExecuteJava("start"); else ExecuteJava(ResinArgs.Command); return true; } catch (ResinServiceException e) { throw e; } catch (Exception e) { StringBuilder message = new StringBuilder("Unable to start application. Make sure java is in your path. Use option -verbose for more detail.\n"); message.Append(e.ToString()); Info(message.ToString()); return false; } } public void StopResin() { if (ResinArgs.IsService) { Info("Stopping Resin"); ExecuteJava("stop"); } } private int Execute() { _resinHome = Util.GetResinHome(_resinHome, System.Reflection.Assembly.GetExecutingAssembly().Location); if (_resinHome == null) { Error("Can't find RESIN_HOME", null); return 1; } if (_rootDirectory == null) _rootDirectory = _resinHome; _javaHome = GetJavaHome(_resinHome, _javaHome); if (_javaExe == null && _javaHome != null) _javaExe = GetJavaExe(_javaHome); if (_javaExe == null) _javaExe = "java.exe"; System.Environment.SetEnvironmentVariable("JAVA_HOME", _javaHome); Environment.SetEnvironmentVariable("PATH", String.Format("{0};{1};\\openssl\\bin;.", _javaHome + "\\bin", Environment.GetEnvironmentVariable("PATH"))); if (ResinArgs.IsService) { ServiceBase.Run(new ServiceBase[] { this }); return 0; } else { if (StartResin()) { Join(); if (_process != null) { int exitCode = _process.ExitCode; _process.Dispose(); return exitCode; } } return 0; } } private static String GetResinAppDataDir() { return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + '\\' + CAUCHO_APP_DATA; } private void ExecuteJava(String command) { mutex.WaitOne(); try { ExecuteJavaImpl(command); } finally { mutex.ReleaseMutex(); } } private void ExecuteJavaImpl(String command) { if (ResinArgs.IsVerbose) { StringBuilder info = new StringBuilder(); info.Append("java : ").Append(_javaExe).Append('\n'); info.Append("JAVA_HOME : ").Append(_javaHome).Append('\n'); info.Append("RESIN_HOME : ").Append(_resinHome).Append('\n'); info.Append("SERVER_ROOT : ").Append(_rootDirectory).Append('\n'); info.Append("PATH : ").Append(Environment.GetEnvironmentVariable("PATH")); Info(info.ToString()); } ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = _javaExe; StringBuilder arguments = new StringBuilder(); arguments.Append("-Xrs -jar "); arguments.Append("\"" + _resinHome + "\\lib\\resin.jar\""); arguments.Append(" -resin-home \"").Append(_resinHome).Append("\" "); arguments.Append(" -root-directory \"").Append(_rootDirectory).Append("\" "); if ("".Equals(ResinArgs.Server)) arguments.Append(" -server \"\""); else if (ResinArgs.Server != null) arguments.Append(" -server ").Append(ResinArgs.Server); if (ResinArgs.ElasticServer) arguments.Append(" --elastic-server "); /* else if (ResinArgs.DynamicServer != null) arguments.Append(" -dynamic-server ").Append(ResinArgs.DynamicServer); */ if (command != null) arguments.Append(' ').Append(command); else if (ResinArgs.RawArgs.Count == 1) arguments.Append(' ').Append("gui"); bool isStart = "start".Equals(command) || "gui".Equals(command) || "console".Equals(command); if (isStart && ResinArgs.Cluster != null) arguments.Append(" -cluster ").Append(ResinArgs.Cluster); if (isStart && ResinArgs.ElasticServer && ! String.IsNullOrEmpty(ResinArgs.ElasticServerAddress)) { arguments.Append(" --elastic-server-address ").Append(ResinArgs.ElasticServerAddress).Append(' '); } if (isStart && ResinArgs.ElasticServer && ! String.IsNullOrEmpty(ResinArgs.ElasticServerPort)) { arguments.Append(" --elastic-server-port ").Append(ResinArgs.ElasticServerPort).Append(' '); } arguments.Append(' ').Append(ResinArgs.ResinArguments); startInfo.Arguments = arguments.ToString(); if (ResinArgs.IsVerbose) Info("Using Command Line: " + _javaExe + ' ' + startInfo.Arguments); startInfo.UseShellExecute = false; if (ResinArgs.IsService) { startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; Process process = null; try { process = Process.Start(startInfo); } catch (Exception e) { Error(e.Message, e); return; } StringBuilder error = new StringBuilder(); StringBuilder output = new StringBuilder(); process.ErrorDataReceived += delegate(Object sendingProcess, DataReceivedEventArgs err) { error.Append(err.Data).Append('\n'); }; process.OutputDataReceived += delegate(object sender, DataReceivedEventArgs err) { output.Append(err.Data).Append('\n'); }; process.BeginErrorReadLine(); process.BeginOutputReadLine(); while (!process.HasExited) process.WaitForExit(500); process.CancelErrorRead(); process.CancelOutputRead(); if (process.HasExited && process.ExitCode != 0) { StringBuilder messageBuilder = new StringBuilder("Error Executing Resin Using: "); messageBuilder.Append(startInfo.FileName).Append(' ').Append(startInfo.Arguments); if (output.Length > 0) messageBuilder.Append('\n').Append(output); if (error.Length > 0) messageBuilder.Append('\n').Append(error); String message = messageBuilder.ToString(); Info(message, true); throw new ResinServiceException(message); } } else { _process = Process.Start(startInfo); } } protected override void OnStart(string[] args) { base.OnStart(args); Info("Service: " + ResinArgs.ServiceName); StartResin(); } protected override void OnStop() { base.OnStop(); StopResin(); } private void Join() { if (_process != null && !_process.HasExited) _process.WaitForExit(); } public void Error(String message, Exception e) { Error(message, e, null); } public void Error(String message, Exception e, TextWriter writer) { StringBuilder data = new StringBuilder(message); if (e != null) data.Append('\n').Append(e.ToString()); if (writer != null) writer.WriteLine(data.ToString()); else if (ResinArgs.IsService && EventLog != null) { EventLog.WriteEntry("Resin: " + ResinArgs.ServiceName, data.ToString(), EventLogEntryType.Error); } else Console.WriteLine(data.ToString()); } private void Info(String message) { Info(message, null, true); } private void Info(String message, bool newLine) { Info(message, null, newLine); } private void Info(String message, TextWriter writer, bool newLine) { if (writer != null && newLine) writer.WriteLine(message); else if (writer != null && !newLine) writer.Write(message); else if (ResinArgs.IsService && EventLog != null) { EventLog.WriteEntry("Resin: " + ResinArgs.ServiceName, message, EventLogEntryType.Information); } else if (newLine) Console.WriteLine(message); else Console.Write(message); } public static int Main(String[] args) { ResinArgs resinArgs = new ResinArgs(Environment.GetCommandLineArgs()); Resin resin = new Resin(resinArgs); return resin.Execute(); } private static String GetJavaExe(String javaHome) { if (File.Exists(javaHome + @"\bin\java.exe")) return javaHome + @"\bin\java.exe"; else if (File.Exists(javaHome + @"\jrockit.exe")) return javaHome + @"\jrockit.exe"; else return null; } private static String FindJdkInRegistry(String key) { RegistryKey regKey = Registry.LocalMachine.OpenSubKey(key); if (regKey == null) return null; RegistryKey java = regKey.OpenSubKey("CurrentVersion"); if (java == null)
[ " java = regKey.OpenSubKey(\"1.6\");" ]
950
lcc
csharp
null
76a0bf2e534153ecd85f4baa149e185926fdf7267d6e1660
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012, Dane Summers <dsummers@pinedesk.biz> # Copyright: (c) 2013, Mike Grozak <mike.grozak@gmail.com> # Copyright: (c) 2013, Patrick Callahan <pmc@patrickcallahan.com> # Copyright: (c) 2015, Evan Kaufman <evan@digitalflophouse.com> # Copyright: (c) 2015, Luca Berruti <nadirio@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: cron short_description: Manage cron.d and crontab entries description: - Use this module to manage crontab and environment variables entries. This module allows you to create environment variables and named crontab entries, update, or delete them. - 'When crontab jobs are managed: the module includes one line with the description of the crontab entry C("#Ansible: <name>") corresponding to the "name" passed to the module, which is used by future ansible/module calls to find/check the state. The "name" parameter should be unique, and changing the "name" value will result in a new cron task being created (or a different one being removed).' - When environment variables are managed, no comment line is added, but, when the module needs to find/check the state, it uses the "name" parameter to find the environment variable definition line. - When using symbols such as %, they must be properly escaped. version_added: "0.9" options: name: description: - Description of a crontab entry or, if env is set, the name of environment variable. - Required if C(state=absent). - Note that if name is not set and C(state=present), then a new crontab entry will always be created, regardless of existing ones. - This parameter will always be required in future releases. type: str user: description: - The specific user whose crontab should be modified. - When unset, this parameter defaults to using C(root). type: str job: description: - The command to execute or, if env is set, the value of environment variable. - The command should not contain line breaks. - Required if C(state=present). type: str aliases: [ value ] state: description: - Whether to ensure the job or environment variable is present or absent. type: str choices: [ absent, present ] default: present cron_file: description: - If specified, uses this file instead of an individual user's crontab. - If this is a relative path, it is interpreted with respect to I(/etc/cron.d). - If it is absolute, it will typically be I(/etc/crontab). - Many linux distros expect (and some require) the filename portion to consist solely of upper- and lower-case letters, digits, underscores, and hyphens. - To use the C(cron_file) parameter you must specify the C(user) as well. type: str backup: description: - If set, create a backup of the crontab before it is modified. The location of the backup is returned in the C(backup_file) variable by this module. type: bool default: no minute: description: - Minute when the job should run ( 0-59, *, */2, etc ) type: str default: "*" hour: description: - Hour when the job should run ( 0-23, *, */2, etc ) type: str default: "*" day: description: - Day of the month the job should run ( 1-31, *, */2, etc ) type: str default: "*" aliases: [ dom ] month: description: - Month of the year the job should run ( 1-12, *, */2, etc ) type: str default: "*" weekday: description: - Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc ) type: str default: "*" aliases: [ dow ] reboot: description: - If the job should be run at reboot. This option is deprecated. Users should use special_time. version_added: "1.0" type: bool default: no special_time: description: - Special time specification nickname. type: str choices: [ annually, daily, hourly, monthly, reboot, weekly, yearly ] version_added: "1.3" disabled: description: - If the job should be disabled (commented out) in the crontab. - Only has effect if C(state=present). type: bool default: no version_added: "2.0" env: description: - If set, manages a crontab's environment variable. - New variables are added on top of crontab. - C(name) and C(value) parameters are the name and the value of environment variable. type: bool default: no version_added: "2.1" insertafter: description: - Used with C(state=present) and C(env). - If specified, the environment variable will be inserted after the declaration of specified environment variable. type: str version_added: "2.1" insertbefore: description: - Used with C(state=present) and C(env). - If specified, the environment variable will be inserted before the declaration of specified environment variable. type: str version_added: "2.1" requirements: - cron (or cronie on CentOS) author: - Dane Summers (@dsummersl) - Mike Grozak (@rhaido) - Patrick Callahan (@dirtyharrycallahan) - Evan Kaufman (@EvanK) - Luca Berruti (@lberruti) ''' EXAMPLES = r''' - name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null" cron: name: "check dirs" minute: "0" hour: "5,2" job: "ls -alh > /dev/null" - name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab' cron: name: "an old job" state: absent - name: Creates an entry like "@reboot /some/job.sh" cron: name: "a job for reboot" special_time: reboot job: "/some/job.sh" - name: Creates an entry like "PATH=/opt/bin" on top of crontab cron: name: PATH env: yes job: /opt/bin - name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration cron: name: APP_HOME env: yes job: /srv/app insertafter: PATH - name: Creates a cron file under /etc/cron.d cron: name: yum autoupdate weekday: "2" minute: "0" hour: "12" user: root job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate" cron_file: ansible_yum-autoupdate - name: Removes a cron file from under /etc/cron.d cron: name: "yum autoupdate" cron_file: ansible_yum-autoupdate state: absent - name: Removes "APP_HOME" environment variable from crontab cron: name: APP_HOME env: yes state: absent ''' import os import platform import pwd import re import sys import tempfile from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.six.moves import shlex_quote class CronTabError(Exception): pass class CronTab(object): """ CronTab object to write time based crontab file user - the user of the crontab (defaults to root) cron_file - a cron file under /etc/cron.d, or an absolute path """ def __init__(self, module, user=None, cron_file=None): self.module = module self.user = user self.root = (os.getuid() == 0) self.lines = None self.ansible = "#Ansible: " self.existing = '' self.cron_cmd = self.module.get_bin_path('crontab', required=True) if cron_file: if os.path.isabs(cron_file): self.cron_file = cron_file else: self.cron_file = os.path.join('/etc/cron.d', cron_file) else: self.cron_file = None self.read() def read(self): # Read in the crontab from the system self.lines = [] if self.cron_file: # read the cronfile try: f = open(self.cron_file, 'r') self.existing = f.read() self.lines = self.existing.splitlines() f.close() except IOError: # cron file does not exist return except Exception: raise CronTabError("Unexpected error:", sys.exc_info()[0]) else: # using safely quoted shell for now, but this really should be two non-shell calls instead. FIXME (rc, out, err) = self.module.run_command(self._read_user_execute(), use_unsafe_shell=True) if rc != 0 and rc != 1: # 1 can mean that there are no jobs. raise CronTabError("Unable to read crontab") self.existing = out lines = out.splitlines() count = 0 for l in lines: if count > 2 or (not re.match(r'# DO NOT EDIT THIS FILE - edit the master and reinstall.', l) and not re.match(r'# \(/tmp/.*installed on.*\)', l) and not re.match(r'# \(.*version.*\)', l)): self.lines.append(l) else: pattern = re.escape(l) + '[\r\n]?' self.existing = re.sub(pattern, '', self.existing, 1) count += 1 def is_empty(self): if len(self.lines) == 0: return True else: return False def write(self, backup_file=None): """ Write the crontab to the system. Saves all information. """ if backup_file: fileh = open(backup_file, 'w') elif self.cron_file: fileh = open(self.cron_file, 'w') else: filed, path = tempfile.mkstemp(prefix='crontab') os.chmod(path, int('0644', 8)) fileh = os.fdopen(filed, 'w') fileh.write(self.render()) fileh.close() # return if making a backup if backup_file: return # Add the entire crontab back to the user crontab if not self.cron_file: # quoting shell args for now but really this should be two non-shell calls. FIXME (rc, out, err) = self.module.run_command(self._write_execute(path), use_unsafe_shell=True) os.unlink(path) if rc != 0: self.module.fail_json(msg=err) # set SELinux permissions if self.module.selinux_enabled() and self.cron_file: self.module.set_default_selinux_context(self.cron_file, False) def do_comment(self, name): return "%s%s" % (self.ansible, name) def add_job(self, name, job): # Add the comment self.lines.append(self.do_comment(name)) # Add the job self.lines.append("%s" % (job)) def update_job(self, name, job): return self._update_job(name, job, self.do_add_job) def do_add_job(self, lines, comment, job): lines.append(comment) lines.append("%s" % (job)) def remove_job(self, name): return self._update_job(name, "", self.do_remove_job) def do_remove_job(self, lines, comment, job): return None def add_env(self, decl, insertafter=None, insertbefore=None): if not (insertafter or insertbefore): self.lines.insert(0, decl) return if insertafter: other_name = insertafter elif insertbefore: other_name = insertbefore other_decl = self.find_env(other_name) if len(other_decl) > 0: if insertafter: index = other_decl[0] + 1 elif insertbefore: index = other_decl[0] self.lines.insert(index, decl) return self.module.fail_json(msg="Variable named '%s' not found." % other_name) def update_env(self, name, decl): return self._update_env(name, decl, self.do_add_env) def do_add_env(self, lines, decl): lines.append(decl) def remove_env(self, name): return self._update_env(name, '', self.do_remove_env) def do_remove_env(self, lines, decl): return None def remove_job_file(self): try: os.unlink(self.cron_file) return True except OSError: # cron file does not exist return False except Exception: raise CronTabError("Unexpected error:", sys.exc_info()[0]) def find_job(self, name, job=None): # attempt to find job by 'Ansible:' header comment comment = None for l in self.lines: if comment is not None: if comment == name: return [comment, l] else: comment = None elif re.match(r'%s' % self.ansible, l):
[ " comment = re.sub(r'%s' % self.ansible, '', l)" ]
1,528
lcc
python
null
70b3e65a3e9eee500a87c090d97914f3b7614cd7d7d51635
# Nikita Akimov # interplanety@interplanety.org # # GitHub # https://github.com/Korchy/BIS # Mesh Modifiers # ------------------------------------------------- # old - remove after recreating meshes through import # ------------------------------------------------- import os import bpy from .bl_types_conversion import BLset, BLObject, BLCacheFile, BLVector, BLImage, BLbpy_prop_collection, BLbpy_prop_array, BLCurveMapping, BLTexture class MeshModifierCommon: @classmethod def to_json(cls, modifier): # base specification modifier_json = { 'type': modifier.type, 'name': modifier.name, 'show_expanded': modifier.show_expanded, 'show_render': modifier.show_render, 'show_viewport': modifier.show_viewport, 'show_in_editmode': modifier.show_in_editmode, 'show_on_cage': modifier.show_on_cage, 'use_apply_on_spline': modifier.use_apply_on_spline } # for current specifications cls._to_json_spec(modifier_json, modifier) return modifier_json @classmethod def _to_json_spec(cls, modifier_json, modifier): # extend to current modifier data pass @classmethod def from_json(cls, mesh, modifier_json): # for current specifications modifier = mesh.modifiers.new(modifier_json['name'], modifier_json['type']) modifier.show_expanded = modifier_json['show_expanded'] modifier.show_render = modifier_json['show_render'] modifier.show_viewport = modifier_json['show_viewport'] modifier.show_in_editmode = modifier_json['show_in_editmode'] modifier.show_on_cage = modifier_json['show_on_cage'] modifier.use_apply_on_spline = modifier_json['use_apply_on_spline'] cls._from_json_spec(modifier=modifier, modifier_json=modifier_json) return mesh @classmethod def _from_json_spec(cls, modifier, modifier_json): # extend to current modifier data pass class MeshModifierSUBSURF(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['levels'] = modifier.levels modifier_json['render_levels'] = modifier.render_levels modifier_json['show_only_control_edges'] = modifier.show_only_control_edges modifier_json['subdivision_type'] = modifier.subdivision_type if hasattr(modifier, 'use_opensubdiv'): modifier_json['use_opensubdiv'] = modifier.use_opensubdiv if hasattr(modifier, 'use_subsurf_uv'): modifier_json['use_subsurf_uv'] = modifier.use_subsurf_uv @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.levels = modifier_json['levels'] modifier.render_levels = modifier_json['render_levels'] modifier.show_only_control_edges = modifier_json['show_only_control_edges'] modifier.subdivision_type = modifier_json['subdivision_type'] if 'use_opensubdiv' in modifier_json and hasattr(modifier, 'use_opensubdiv'): modifier.use_opensubdiv = modifier_json['use_opensubdiv'] if 'use_subsurf_uv' in modifier_json and hasattr(modifier, 'use_subsurf_uv'): modifier.use_subsurf_uv = modifier_json['use_subsurf_uv'] class MeshModifierDATA_TRANSFER(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['object'] = BLObject.to_json(instance=modifier.object) modifier_json['use_poly_data'] = modifier.use_poly_data modifier_json['use_vert_data'] = modifier.use_vert_data modifier_json['use_edge_data'] = modifier.use_edge_data modifier_json['use_loop_data'] = modifier.use_loop_data modifier_json['data_types_edges'] = BLset.to_json(modifier.data_types_edges) modifier_json['data_types_loops'] = BLset.to_json(modifier.data_types_loops) modifier_json['data_types_polys'] = BLset.to_json(modifier.data_types_polys) modifier_json['data_types_verts'] = BLset.to_json(modifier.data_types_verts) modifier_json['edge_mapping'] = modifier.edge_mapping modifier_json['invert_vertex_group'] = modifier.invert_vertex_group modifier_json['islands_precision'] = modifier.islands_precision modifier_json['layers_uv_select_dst'] = modifier.layers_uv_select_dst modifier_json['layers_uv_select_src'] = modifier.layers_uv_select_src modifier_json['layers_vcol_select_dst'] = modifier.layers_vcol_select_dst modifier_json['layers_vcol_select_src'] = modifier.layers_vcol_select_src modifier_json['layers_vgroup_select_dst'] = modifier.layers_vgroup_select_dst modifier_json['layers_vgroup_select_src'] = modifier.layers_vgroup_select_src modifier_json['loop_mapping'] = modifier.loop_mapping modifier_json['max_distance'] = modifier.max_distance modifier_json['mix_factor'] = modifier.mix_factor modifier_json['mix_mode'] = modifier.mix_mode modifier_json['poly_mapping'] = modifier.poly_mapping modifier_json['ray_radius'] = modifier.ray_radius modifier_json['use_max_distance'] = modifier.use_max_distance modifier_json['use_object_transform'] = modifier.use_object_transform modifier_json['vert_mapping'] = modifier.vert_mapping modifier_json['vertex_group'] = modifier.vertex_group @classmethod def _from_json_spec(cls, modifier, modifier_json): BLObject.from_json(instance=modifier, json=modifier_json['object']) modifier.use_poly_data = modifier_json['use_poly_data'] modifier.use_vert_data = modifier_json['use_vert_data'] modifier.use_edge_data = modifier_json['use_edge_data'] modifier.use_loop_data = modifier_json['use_loop_data'] modifier.use_max_distance = modifier_json['use_max_distance'] modifier.use_object_transform = modifier_json['use_object_transform'] modifier.data_types_edges = BLset.from_json(json=modifier_json['data_types_edges']) modifier.data_types_loops = BLset.from_json(json=modifier_json['data_types_loops']) modifier.data_types_polys = BLset.from_json(json=modifier_json['data_types_polys']) modifier.data_types_verts = BLset.from_json(json=modifier_json['data_types_verts']) modifier.edge_mapping = modifier_json['edge_mapping'] modifier.invert_vertex_group = modifier_json['invert_vertex_group'] modifier.islands_precision = modifier_json['islands_precision'] modifier.layers_uv_select_dst = modifier_json['layers_uv_select_dst'] modifier.layers_uv_select_src = modifier_json['layers_uv_select_src'] modifier.layers_vcol_select_dst = modifier_json['layers_vcol_select_dst'] modifier.layers_vcol_select_src = modifier_json['layers_vcol_select_src'] modifier.layers_vgroup_select_dst = modifier_json['layers_vgroup_select_dst'] modifier.layers_vgroup_select_src = modifier_json['layers_vgroup_select_src'] modifier.loop_mapping = modifier_json['loop_mapping'] modifier.max_distance = modifier_json['max_distance'] modifier.mix_factor = modifier_json['mix_factor'] modifier.mix_mode = modifier_json['mix_mode'] modifier.poly_mapping = modifier_json['poly_mapping'] modifier.ray_radius = modifier_json['ray_radius'] modifier.vert_mapping = modifier_json['vert_mapping'] modifier.vertex_group = modifier_json['vertex_group'] class MeshModifierMESH_CACHE(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['cache_format'] = modifier.cache_format modifier_json['deform_mode'] = modifier.deform_mode modifier_json['eval_factor'] = modifier.eval_factor modifier_json['eval_frame'] = modifier.eval_frame modifier_json['eval_time'] = modifier.eval_time modifier_json['factor'] = modifier.factor modifier_json['filepath'] = modifier.filepath modifier_json['flip_axis'] = BLset.to_json(modifier.flip_axis) modifier_json['forward_axis'] = modifier.forward_axis modifier_json['frame_scale'] = modifier.frame_scale modifier_json['frame_start'] = modifier.frame_start modifier_json['interpolation'] = modifier.interpolation modifier_json['play_mode'] = modifier.play_mode modifier_json['time_mode'] = modifier.time_mode modifier_json['up_axis'] = modifier.up_axis @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.cache_format = modifier_json['cache_format'] modifier.deform_mode = modifier_json['deform_mode'] modifier.eval_factor = modifier_json['eval_factor'] modifier.eval_frame = modifier_json['eval_frame'] modifier.eval_time = modifier_json['eval_time'] modifier.factor = modifier_json['factor'] modifier.filepath = modifier_json['filepath'] modifier.flip_axis = BLset.from_json(json=modifier_json['flip_axis']) modifier.forward_axis = modifier_json['forward_axis'] modifier.frame_scale = modifier_json['frame_scale'] modifier.frame_start = modifier_json['frame_start'] modifier.interpolation = modifier_json['interpolation'] modifier.play_mode = modifier_json['play_mode'] modifier.time_mode = modifier_json['time_mode'] modifier.up_axis = modifier_json['up_axis'] class MeshModifierMESH_SEQUENCE_CACHE(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['cache_file'] = BLCacheFile.to_json(instance=modifier.cache_file) modifier_json['object_path'] = modifier.object_path modifier_json['read_data'] = BLset.to_json(modifier.read_data) @classmethod def _from_json_spec(cls, modifier, modifier_json): BLCacheFile.from_json(instance=modifier, json=modifier_json['cache_file'], instance_field='cache_file') modifier.object_path = modifier_json['object_path'] modifier.read_data = BLset.from_json(json=modifier_json['read_data']) class MeshModifierNORMAL_EDIT(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['target'] = BLObject.to_json(instance=modifier.target) modifier_json['invert_vertex_group'] = modifier.invert_vertex_group modifier_json['mix_factor'] = modifier.mix_factor modifier_json['mix_limit'] = modifier.mix_limit modifier_json['mix_mode'] = modifier.mix_mode modifier_json['mode'] = modifier.mode modifier_json['offset'] = BLVector.to_json(instance=modifier.offset) modifier_json['use_direction_parallel'] = modifier.use_direction_parallel modifier_json['vertex_group'] = modifier.vertex_group @classmethod def _from_json_spec(cls, modifier, modifier_json): BLObject.from_json(instance=modifier, json=modifier_json['target'], instance_field='target') modifier.invert_vertex_group = modifier_json['invert_vertex_group'] modifier.mix_factor = modifier_json['mix_factor'] modifier.mix_limit = modifier_json['mix_limit'] modifier.mix_mode = modifier_json['mix_mode'] modifier.mode = modifier_json['mode'] BLVector.from_json(instance=modifier.offset, json=modifier_json['offset']) modifier.use_direction_parallel = modifier_json['use_direction_parallel'] modifier.vertex_group = modifier_json['vertex_group'] class MeshModifierUV_PROJECT(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['aspect_x'] = modifier.aspect_x modifier_json['aspect_y'] = modifier.aspect_y modifier_json['image'] = BLImage.to_json(instance=modifier.image) modifier_json['projector_count'] = modifier.projector_count modifier_json['projectors'] = BLbpy_prop_collection.to_json(modifier.projectors) modifier_json['scale_x'] = modifier.scale_x modifier_json['scale_y'] = modifier.scale_y modifier_json['use_image_override'] = modifier.use_image_override modifier_json['uv_layer'] = modifier.uv_layer @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.aspect_x = modifier_json['aspect_x'] modifier.aspect_y = modifier_json['aspect_y'] BLImage.from_json(instance=modifier, json=modifier_json['image'], instance_field='image') modifier.projector_count = modifier_json['projector_count'] BLbpy_prop_collection.from_json(modifier, modifier.projectors, modifier_json['projectors']) modifier.scale_x = modifier_json['scale_x'] modifier.scale_y = modifier_json['scale_y'] modifier.use_image_override = modifier_json['use_image_override'] modifier.uv_layer = modifier_json['uv_layer'] class MeshModifierUV_WARP(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['axis_u'] = modifier.axis_u modifier_json['axis_v'] = modifier.axis_v modifier_json['bone_from'] = modifier.bone_from modifier_json['bone_to'] = modifier.bone_to modifier_json['center'] = BLbpy_prop_array.to_json(prop_array=modifier.center) modifier_json['object_from'] = BLObject.to_json(instance=modifier.object_from) modifier_json['object_to'] = BLObject.to_json(instance=modifier.object_to) modifier_json['uv_layer'] = modifier.uv_layer modifier_json['vertex_group'] = modifier.vertex_group @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.axis_u = modifier_json['axis_u'] modifier.axis_v = modifier_json['axis_v'] modifier.bone_from = modifier_json['bone_from'] modifier.bone_to = modifier_json['bone_to'] BLbpy_prop_array.from_json(prop_array=modifier.center, json=modifier_json['center']) BLObject.from_json(instance=modifier, json=modifier_json['object_from'], instance_field='object_from') BLObject.from_json(instance=modifier, json=modifier_json['object_to'], instance_field='object_to') modifier.uv_layer = modifier_json['uv_layer'] modifier.vertex_group = modifier_json['vertex_group'] class MeshModifierVERTEX_WEIGHT_EDIT(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['add_threshold'] = modifier.add_threshold modifier_json['default_weight'] = modifier.default_weight modifier_json['falloff_type'] = modifier.falloff_type modifier_json['map_curve'] = BLCurveMapping.to_json(instance=modifier.map_curve) modifier_json['mask_constant'] = modifier.mask_constant modifier_json['mask_tex_map_object'] = BLObject.to_json(instance=modifier.mask_tex_map_object) modifier_json['mask_tex_mapping'] = modifier.mask_tex_mapping modifier_json['mask_tex_use_channel'] = modifier.mask_tex_use_channel modifier_json['mask_tex_uv_layer'] = modifier.mask_tex_uv_layer modifier_json['mask_texture'] = BLTexture.to_json(instance=modifier.mask_texture) modifier_json['mask_vertex_group'] = modifier.mask_vertex_group modifier_json['remove_threshold'] = modifier.remove_threshold modifier_json['use_add'] = modifier.use_add modifier_json['use_remove'] = modifier.use_remove modifier_json['vertex_group'] = modifier.vertex_group @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.add_threshold = modifier_json['add_threshold'] modifier.default_weight = modifier_json['default_weight'] modifier.falloff_type = modifier_json['falloff_type'] BLCurveMapping.from_json(instance=modifier.map_curve, json=modifier_json['map_curve']) modifier.mask_constant = modifier_json['mask_constant'] BLObject.from_json(instance=modifier, json=modifier_json['mask_tex_map_object'], instance_field='mask_tex_map_object') modifier.mask_tex_mapping = modifier_json['mask_tex_mapping'] modifier.mask_tex_use_channel = modifier_json['mask_tex_use_channel'] modifier.mask_tex_uv_layer = modifier_json['mask_tex_uv_layer'] BLTexture.from_json(instance=modifier, json=modifier_json['mask_texture'], instance_field='mask_texture') modifier.mask_vertex_group = modifier_json['mask_vertex_group'] modifier.remove_threshold = modifier_json['remove_threshold'] modifier.use_add = modifier_json['use_add'] modifier.use_remove = modifier_json['use_remove'] modifier.vertex_group = modifier_json['vertex_group'] class MeshModifierVERTEX_WEIGHT_MIX(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['default_weight_a'] = modifier.default_weight_a modifier_json['default_weight_b'] = modifier.default_weight_b modifier_json['mask_constant'] = modifier.mask_constant modifier_json['mask_tex_map_object'] = BLObject.to_json(instance=modifier.mask_tex_map_object) modifier_json['mask_tex_mapping'] = modifier.mask_tex_mapping modifier_json['mask_tex_use_channel'] = modifier.mask_tex_use_channel modifier_json['mask_tex_uv_layer'] = modifier.mask_tex_uv_layer modifier_json['mask_texture'] = BLTexture.to_json(instance=modifier.mask_texture) modifier_json['mask_vertex_group'] = modifier.mask_vertex_group modifier_json['mix_mode'] = modifier.mix_mode modifier_json['mix_set'] = modifier.mix_set modifier_json['vertex_group_a'] = modifier.vertex_group_a @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.default_weight_a = modifier_json['default_weight_a'] modifier.default_weight_b = modifier_json['default_weight_b'] modifier.mask_constant = modifier_json['mask_constant'] BLObject.from_json(instance=modifier, json=modifier_json['mask_tex_map_object'], instance_field='mask_tex_map_object') modifier.mask_tex_mapping = modifier_json['mask_tex_mapping'] modifier.mask_tex_use_channel = modifier_json['mask_tex_use_channel'] modifier.mask_tex_uv_layer = modifier_json['mask_tex_uv_layer'] BLTexture.from_json(instance=modifier, json=modifier_json['mask_texture'], instance_field='mask_texture') modifier.mask_vertex_group = modifier_json['mask_vertex_group'] modifier.mix_mode = modifier_json['mix_mode'] modifier.mix_set = modifier_json['mix_set'] modifier.vertex_group_a = modifier_json['vertex_group_a'] class MeshModifierVERTEX_WEIGHT_PROXIMITY(MeshModifierCommon): @classmethod def _to_json_spec(cls, modifier_json, modifier): modifier_json['falloff_type'] = modifier.falloff_type modifier_json['mask_constant'] = modifier.mask_constant modifier_json['mask_tex_map_object'] = BLObject.to_json(instance=modifier.mask_tex_map_object) modifier_json['mask_tex_mapping'] = modifier.mask_tex_mapping modifier_json['mask_tex_use_channel'] = modifier.mask_tex_use_channel modifier_json['mask_tex_uv_layer'] = modifier.mask_tex_uv_layer modifier_json['mask_texture'] = BLTexture.to_json(instance=modifier.mask_texture) modifier_json['mask_vertex_group'] = modifier.mask_vertex_group modifier_json['max_dist'] = modifier.max_dist modifier_json['min_dist'] = modifier.min_dist modifier_json['proximity_geometry'] = BLset.to_json(modifier.proximity_geometry) modifier_json['proximity_mode'] = modifier.proximity_mode modifier_json['target'] = BLObject.to_json(instance=modifier.target) modifier_json['vertex_group'] = modifier.vertex_group @classmethod def _from_json_spec(cls, modifier, modifier_json): modifier.falloff_type = modifier_json['falloff_type'] modifier.mask_constant = modifier_json['mask_constant'] BLObject.from_json(instance=modifier, json=modifier_json['mask_tex_map_object'], instance_field='mask_tex_map_object') modifier.mask_tex_mapping = modifier_json['mask_tex_mapping'] modifier.mask_tex_use_channel = modifier_json['mask_tex_use_channel'] modifier.mask_tex_uv_layer = modifier_json['mask_tex_uv_layer'] BLTexture.from_json(instance=modifier, json=modifier_json['mask_texture'], instance_field='mask_texture') modifier.mask_vertex_group = modifier_json['mask_vertex_group'] modifier.max_dist = modifier_json['max_dist'] modifier.min_dist = modifier_json['min_dist'] modifier.proximity_geometry = BLset.from_json(json=modifier_json['proximity_geometry']) modifier.proximity_mode = modifier_json['proximity_mode'] BLObject.from_json(instance=modifier, json=modifier_json['target'], instance_field='target')
[ " modifier.vertex_group = modifier_json['vertex_group']" ]
994
lcc
python
null
e8d2fbeddaaa67221144399f1e48bc62deb18f5fd8c3c92a
package com.hartwig.hmftools.neo.bind; import static java.lang.Math.max; import static java.lang.Math.min; import static com.hartwig.hmftools.common.utils.FileWriterUtils.closeBufferedWriter; import static com.hartwig.hmftools.common.utils.FileWriterUtils.createBufferedWriter; import static com.hartwig.hmftools.common.utils.FileWriterUtils.createFieldsIndexMap; import static com.hartwig.hmftools.neo.NeoCommon.NE_LOGGER; import static com.hartwig.hmftools.neo.bind.BindCommon.DELIM; import static com.hartwig.hmftools.neo.bind.BindCommon.FLD_ALLELE; import static com.hartwig.hmftools.neo.bind.BindCommon.FLD_PEPTIDE_LEN; import static com.hartwig.hmftools.neo.bind.BindConstants.DEFAULT_PEPTIDE_LENGTHS; import static com.hartwig.hmftools.neo.bind.BindConstants.MIN_LIKELIHOOD_ALLELE_BIND_COUNT; import static com.hartwig.hmftools.neo.bind.BindConstants.MIN_PEPTIDE_LENGTH; import static com.hartwig.hmftools.neo.bind.BindConstants.REF_PEPTIDE_LENGTH; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.List; import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.hartwig.hmftools.common.utils.Doubles; public class BindingLikelihood { // statically-defined rank buckets in exponentially increasing size private final List<Double> mScoreRankBuckets; // map of allele to a matrix of peptide-length and rank buckets, containing the likelihood values private final Map<String,double[][]> mAlleleLikelihoodMap; private BufferedWriter mWriter; private boolean mHasData; private static final double INVALID_LIKELIHOOD = -1; private static final double MIN_BUCKET_RANK = 0.00005; private static final int PEPTIDE_LENGTHS = 5; private static final double MIN_EMPTY_PEP_LEN_LIKELIHOOD = 0.25; private static final double MIN_EMPTY_PEP_LEN_FACTOR = 1000; private static final double MIN_EMPTY_PEP_LEN_BUCKET_THRESHOLD = 0.01; public BindingLikelihood() { mWriter = null; mAlleleLikelihoodMap = Maps.newHashMap(); mHasData = false; mScoreRankBuckets = Lists.newArrayListWithExpectedSize(16); double rankPercBucket = MIN_BUCKET_RANK; while(rankPercBucket < 1) { mScoreRankBuckets.add(rankPercBucket); rankPercBucket *= 2; } } public boolean hasData() { return mHasData; } public double getBindingLikelihood(final String allele, final String peptide, final double rank) { if(!mHasData) return INVALID_LIKELIHOOD; int peptideLength = peptide.length(); int pepLenIndex = peptideLengthIndex(peptideLength); if(pepLenIndex == INVALID_PEP_LEN) return INVALID_LIKELIHOOD; double[][] likelihoods = mAlleleLikelihoodMap.get(allele); if(likelihoods == null) { likelihoods = mAlleleLikelihoodMap.get(extractTwoDigitType(allele)); if(likelihoods == null) likelihoods = mAlleleLikelihoodMap.get(extractGene(allele)); if(likelihoods == null) return INVALID_LIKELIHOOD; } for(int i = 0; i < mScoreRankBuckets.size(); ++i) { if(rank < mScoreRankBuckets.get(i)) { double likelihood = likelihoods[pepLenIndex][i]; if(i == 0) return likelihood; double lowerLikelihood = likelihoods[pepLenIndex][i - 1]; double lowerRank = mScoreRankBuckets.get(i - 1); double upperRank = mScoreRankBuckets.get(i); double upperPerc = (rank - lowerRank) / (upperRank - lowerRank); return upperPerc * likelihood + (1 - upperPerc) * lowerLikelihood; } } return 0; } public boolean loadLikelihoods(final String filename) { if(filename == null) return false; try { final List<String> lines = Files.readAllLines(new File(filename).toPath()); final Map<String,Integer> fieldsIndexMap = createFieldsIndexMap(lines.get(0), DELIM); lines.remove(0); int alleleIndex = fieldsIndexMap.get(FLD_ALLELE); int pepLenIndex = fieldsIndexMap.get(FLD_PEPTIDE_LEN); String currentAllele = ""; double[][] likelihoods = null; for(String line : lines) { String[] items = line.split(DELIM, -1); String allele = items[alleleIndex]; int peptideLength = Integer.parseInt(items[pepLenIndex]); if(!currentAllele.equals(allele)) { currentAllele = allele; likelihoods = new double[PEPTIDE_LENGTHS][mScoreRankBuckets.size()]; mAlleleLikelihoodMap.put(allele, likelihoods); } int index = pepLenIndex + 1; for(int i = 0; index < items.length; ++i, ++index) { likelihoods[peptideLengthIndex(peptideLength)][i] = Double.parseDouble(items[index]); } } NE_LOGGER.info("loaded {} alleles peptide likelihoods from {}", mAlleleLikelihoodMap.size(), filename); mHasData = true; } catch(IOException e) { NE_LOGGER.error("failed to read peptide likelihoods file: {}", e.toString()); return false; } return true; } private static int INVALID_PEP_LEN = -1; private static int peptideLengthIndex(int peptideLength) { if(peptideLength < MIN_PEPTIDE_LENGTH || peptideLength > REF_PEPTIDE_LENGTH) return INVALID_PEP_LEN; return peptideLength - MIN_PEPTIDE_LENGTH; } private static int peptideLengthFromIndex(int index) { return MIN_PEPTIDE_LENGTH + index; } public void buildAllelePeptideLikelihoods( final Map<String,Map<Integer,List<BindData>>> allelePeptideData, final String outputFilename) { if(outputFilename != null) mWriter = initWriter(outputFilename); // any allele with sufficient counts will have a likelihood distribution calculated for it // in addition, distributions will be calculated for 2-digit alleles and at the HLA gene level final Map<String,Map<Integer,List<Double>>> sharedPepLenRanks = Maps.newHashMap(); for(Map.Entry<String, Map<Integer, List<BindData>>> alleleEntry : allelePeptideData.entrySet()) { final String allele = alleleEntry.getKey(); final Map<Integer,List<BindData>> pepLenBindDataMap = alleleEntry.getValue(); int alleleBindCount = pepLenBindDataMap.values().stream().mapToInt(x -> x.size()).sum(); if(alleleBindCount < MIN_LIKELIHOOD_ALLELE_BIND_COUNT) continue; String hlaGene = extractGene(allele); String twoDigitType = extractTwoDigitType(allele); Map<Integer,List<Double>> genePepLenRanks = sharedPepLenRanks.get(hlaGene); if(genePepLenRanks == null) { genePepLenRanks = Maps.newHashMap(); sharedPepLenRanks.put(hlaGene, genePepLenRanks); } Map<Integer,List<Double>> twoDigitPepLenRanks = sharedPepLenRanks.get(twoDigitType); if(twoDigitPepLenRanks == null) { twoDigitPepLenRanks = Maps.newHashMap(); sharedPepLenRanks.put(twoDigitType, twoDigitPepLenRanks); } final Map<Integer,List<Double>> pepLenRanks = Maps.newHashMap(); for(Map.Entry<Integer,List<BindData>> pepLenEntry : pepLenBindDataMap.entrySet()) { int peptideLength = pepLenEntry.getKey(); List<Double> peptideRanks = Lists.newArrayListWithCapacity(pepLenEntry.getValue().size()); pepLenEntry.getValue().forEach(x -> peptideRanks.add(x.rankPercentile())); pepLenRanks.put(peptideLength, peptideRanks); List<Double> sharedRanks = genePepLenRanks.get(peptideLength); if(sharedRanks == null) { sharedRanks = Lists.newArrayList(); genePepLenRanks.put(peptideLength, sharedRanks); } sharedRanks.addAll(peptideRanks); sharedRanks = twoDigitPepLenRanks.get(peptideLength); if(sharedRanks == null) { sharedRanks = Lists.newArrayList(); twoDigitPepLenRanks.put(peptideLength, sharedRanks); } sharedRanks.addAll(peptideRanks); } buildAllelePeptideLikelihoods(allele, pepLenRanks); } for(Map.Entry<String,Map<Integer,List<Double>>> sharedAlleleEntry : sharedPepLenRanks.entrySet()) { buildAllelePeptideLikelihoods(sharedAlleleEntry.getKey(), sharedAlleleEntry.getValue()); } mHasData = true; closeBufferedWriter(mWriter); } private static String extractGene(final String allele) { // A, B or C return allele.substring(0, 1); } private static String extractTwoDigitType(final String allele) { // eg A02 return allele.substring(0, 3); } private void buildAllelePeptideLikelihoods(final String allele, final Map<Integer,List<Double>> pepLenRanks) { Map<Integer,double[]> pepLenRankCounts = Maps.newHashMap(); int totalBuckets = mScoreRankBuckets.size(); int totalPositivesCount = 0; for(int peptideLength : DEFAULT_PEPTIDE_LENGTHS) { double[] rankCounts = new double[totalBuckets]; pepLenRankCounts.put(peptideLength, rankCounts); List<Double> pepLengthRanks = pepLenRanks.get(peptideLength); if(pepLengthRanks == null) continue; totalPositivesCount += pepLengthRanks.size(); for(double rank : pepLengthRanks) { for(int i = 0; i < totalBuckets; ++i) { double bucketRank = mScoreRankBuckets.get(i); if(rank > bucketRank) continue; if(rank < bucketRank || Doubles.equal(bucketRank, rank)) { ++rankCounts[i]; break; } if(i < totalBuckets - 1) { double nextBucketRank = mScoreRankBuckets.get(i + 1); if(rank < nextBucketRank || Doubles.equal(nextBucketRank, rank)) { ++rankCounts[i + 1]; break; } } else { ++rankCounts[totalBuckets - 1]; } } } } // fill in values for zeros using a fraction of total positives for lengths with none, and halving for other missing buckets double minLikelihood = min(MIN_EMPTY_PEP_LEN_LIKELIHOOD, totalPositivesCount / MIN_EMPTY_PEP_LEN_FACTOR); for(int peptideLength : DEFAULT_PEPTIDE_LENGTHS) { double[] rankCounts = pepLenRankCounts.get(peptideLength);
[ " for(int i = 0; i < rankCounts.length; ++i)" ]
822
lcc
java
null
7b052378f063837f048563149af68758cefc4141ff2e4669
package mx.letmethink.graph; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.util.ArrayList; import lombok.val; import mx.letmethink.graphics.Point2D; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Unit tests {@link Vertex}. */ public class VertexTest { Vertex vertex; @BeforeEach void setUp() { vertex = Vertex.create("vertex"); } @Test @DisplayName("setKey() should set values correctly") void setKey() { vertex.setKey(7); assertEquals(7, vertex.getKey()); } @Test @DisplayName("setLabel() should set values correctly") void setLabel() { assertEquals("vertex", vertex.getLabel()); vertex.setLabel("label"); assertEquals("label", vertex.getLabel()); } @Test @DisplayName("setEdgeDirection() should set values correctly") void setEdgeDirection() { assertEquals(0, vertex.getEdgeDirection()); vertex.setEdgeDirection(1); assertEquals(1, vertex.getEdgeDirection()); } @Test @DisplayName("addNeighbor() should add valid neighbors") void addNeighbor() { vertex.addNeighbor(Edge.create(1, 2, "-->")); assertTrue(vertex.contains(2)); } @Test @DisplayName("addNeighbor() should NOT add null edges") void addNeighbor_nullEdge() { val vertex = Vertex.create("vertex"); vertex.addNeighbor(null); assertFalse(vertex.contains(2)); } @Test @DisplayName("addNeighbor() should NOT add edges without an end") void addNeighbor_edgesWithoutEnd() { val vertex = Vertex.create("vertex"); vertex.addNeighbor(Edge.create(1, null, "")); assertFalse(vertex.contains(2)); } @Test @DisplayName("addNeighbor() should return the edge to the new neighbor") void addNeighbor_newNeighbor() { val edge = vertex.addNeighbor(7, "seven"); assertEquals(7, edge.getEnd()); assertEquals("seven", edge.getLabel()); } @Test @DisplayName("addNeighbor() should return null if the specified vertex is already a neighbor") void addNeighbor_attemptToAddExistingNeighbor() { vertex.addNeighbor(7, "seven"); assertNull(vertex.addNeighbor(7, "label")); } @Test @DisplayName("getNeighbor() should return null when the requested key does not exist") void getNeighbor_nonExistent() { assertNull(vertex.getNeighbor(3)); } @Test @DisplayName("getNeighbor() should return existing neighbor") void getNeighbor_existingNeighbor() { vertex.addNeighbor(3, "three"); val edge = vertex.getNeighbor(3); assertEquals(3, edge.getEnd()); assertEquals("three", edge.getLabel()); } @Test @DisplayName("setCenter() should accept a point") void setCenter_fromPoint() { vertex.setCenter(Point2D.of(1, 2)); assertEquals(1, vertex.getCenter().getX()); assertEquals(2, vertex.getCenter().getY()); } @Test @DisplayName("setCenter() should accept coordinates") void setCenter_fromTwoValues() { vertex.setCenter(1, 2); assertEquals(1, vertex.getCenter().getX()); assertEquals(2, vertex.getCenter().getY()); } @Test @DisplayName("setRadius() should set values correctly") void setRadius() { vertex.setRadius(5); assertEquals(5, vertex.getRadius()); } @Test @DisplayName("setLabelAssignment() should set values correctly") void setLabelAlignment() { assertEquals(0, vertex.getLabelAlignment()); vertex.setLabelAlignment(1); assertEquals(1, vertex.getLabelAlignment()); } @Test @DisplayName("setLabelChanged() should set values correctly") void setLabelChanged() { vertex.setLabelChanged(false); assertFalse(vertex.hasLabelChanged()); vertex.setLabelChanged(true); assertTrue(vertex.hasLabelChanged()); } @Test @DisplayName("setSelected() should set values correctly") void setSelected() { vertex.setSelected(false); assertFalse(vertex.isSelected()); vertex.setSelected(true); assertTrue(vertex.isSelected()); } @Test @DisplayName("setForegroundColor() should not assign null colors") void setForegroundColor_nullColor() { assertNotNull(vertex.getForegroundColor()); vertex.setForegroundColor(null); assertNotNull(vertex.getForegroundColor()); } @Test @DisplayName("setForegroundColor() should assign non-null colors") void setForegroundColor_nonNullColor() { assertEquals(Color.BLACK, vertex.getForegroundColor()); vertex.setForegroundColor(Color.BLUE); assertEquals(Color.BLUE, vertex.getForegroundColor()); } @Test @DisplayName("setBorderColor() should not assign null colors") void setBorderColor_nullColor() { assertNotNull(vertex.getBorderColor()); vertex.setBorderColor(null); assertNotNull(vertex.getBorderColor()); } @Test @DisplayName("setBorderColor() should assign non-null colors") void setBorderColor_nonNullColor() { assertEquals(Color.BLACK, vertex.getBorderColor()); vertex.setBorderColor(Color.BLUE); assertEquals(Color.BLUE, vertex.getBorderColor()); } @Test @DisplayName("setBackgroundColor() should not assign null colors") void setBackgroundColor_nullColor() { assertNotNull(vertex.getBackgroundColor()); vertex.setBackgroundColor(null); assertNotNull(vertex.getBackgroundColor()); } @Test @DisplayName("setBackgroundColor() should assign non-null colors") void setBackgroundColor_nonNullColor() { assertEquals(Color.WHITE, vertex.getBackgroundColor()); vertex.setBackgroundColor(Color.BLACK); assertEquals(Color.BLACK, vertex.getBackgroundColor()); } @Test @DisplayName("removeNeighbor() should return null if neighbor does not exist") void removeNeighbor_nonExistentNeighbor() { assertNull(vertex.removeNeighbor(3)); } @Test @DisplayName("removeNeighbor() should remove existing neighbor") void removeNeighbor() { vertex.addNeighbor(2, "two"); val edge = vertex.removeNeighbor(2); assertEquals(2, edge.getEnd()); assertEquals("two", edge.getLabel()); } @Test @DisplayName("neighbors() should return iterator with all the neighbors") void neighbors() { vertex.addNeighbor(1, "one"); vertex.addNeighbor(2, "two"); vertex.addNeighbor(3, "three"); val neighbors = new ArrayList<Integer>();
[ " for (val n : vertex.neighbors()) {" ]
466
lcc
java
null
7e369e49db979a11fae014da09f9aeaf1d365950a38b7333
#!/usr/bin/python import argparse, sys, time, logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * """ Author: mtask@github.com Program: pydump.py Description: Simple packet analyzer. """ """ Pydump is made also python3 in mind, but haven't been tested how scapy's python3 version works. """ class Pydump(object): def __init__(self): self.blk = '\033[0m' # Black - Regular self.warn = '\033[93m' # yellow self.grn = '\033[92m' # Green self.fatal = '\033[91m' #red self.packetNumber = 0 def arguments(self,custom_arg=None): self.parser = argparse.ArgumentParser(description="Packet capturing tool", prog="pydump.py") self.parser.add_argument("-i", "--iface", help="Capturing interface") self.parser.add_argument("-n", "--num", help="Number of packets to capture") self.parser.add_argument("-r", "--read", help="Read .pcap file") self.parser.add_argument("-f", "--filter", help="Filter packets. Use quotes(\"\")") self.parser.add_argument("-w", "--write", help="Write capture to file") self.parser.add_argument("-I", "--inspect", action='store_true', help="Inspect packets") try: if custom_arg: self.args = self.parser.parse_args(custom_arg) else: self.args = self.parser.parse_args() if not self.args.iface and not self.args.read: self.parser.print_usage() else: return self.args except SystemExit: if custom_arg: return else: sys.exit(1) def output(self, packet): """ Standard sniffing output """ self.packetNumber += 1 time.sleep(1) return str(self.packetNumber) + ": " + packet.summary() def sniffer(self,iface, filter_=None, num=None): ###################################### #Sniffing with scapy. # #sniffer() returns captured packets, # #or False if none captured. # ###################################### self.fil = filter_ self.iface = iface self.num = num self.pckts = None self.statement = self.output ###Check if --num/--filter used and start capturing### if self.num: try: print("Capturing "+ self.num + " packets from " + self.iface) if self.fil: self.pckts = sniff(iface=self.iface,filter=self.fil, count=int(num), prn = self.statement) else: self.pckts = sniff(iface=self.iface, count=int(num), prn = self.statement) except NameError: print(self.fatal+"Check your filtering argument"+self.blk) except socket.error as se: print(self.fatal+str(se)+": "+self.iface+self.blk) elif not self.num: try: print("Capturing traffic from "+self.iface) if self.fil: self.pckts = sniff(iface=self.iface, filter=self.fil, prn = self.statement) else: self.pckts = sniff(iface=self.iface, prn = self.statement) except NameError: print(self.fatal+"Check your filtering argument"+self.blk) except socket.error as se: print(self.fatal+str(se)+": "+self.iface+self.blk) if self.pckts: return self.pckts else: return False def main(self, customArgs=None): ###Checking arguments### if customArgs: self.arg = self.arguments(custom_arg=customArgs) else: self.arg = self.arguments() if not self.arg: return self.iface_ = self.arg.iface if self.arg.filter: self.fil_ = self.arg.filter else: self.fil_ = None if self.arg.num: self.num_ = self.arg.num else: self.num_ = None ###If --read### if self.arg.read: self.pcapfile = self.arg.read try: self.rdpkt=rdpcap(self.pcapfile) self.rdpkt.nsummary() except Exception as e: sys.stderr.write(self.fatal+str(e)+self.blk) print("") return ###Start packet sniffing### self.cap = self.sniffer(self.iface_, filter_=self.fil_, num=self.num_) ###Write captured packets to file if --write### if self.cap: if self.arg.write: self.file_ = self.arg.write if ".pcap" in self.file_: wrpcap(self.file_, self.cap) else: self.file_ = self.file_+".pcap" wrpcap(self.file_, self.cap) ###If inspection mode selected### if self.arg.inspect: self.inspect = Inspect() os.system('clear') print(self.grn+"[*] Starting inspection mode.."+self.blk) time.sleep(2) self.inspect.prompt(self.cap) else: print("") print(self.warn+"[!] No packets were captured"+self.blk) class Inspect(object): def __init__(self): self.blk = '\033[0m' # Black - Regular self.warn = '\033[93m' # yellow self.grn = '\033[92m' # Green self.fatal = '\033[91m' #red def get_input(self, prompt): #################################################### # #Get user input maintaining the python compatibility # #with earlier and newer versions. # ###################################################### if sys.hexversion > 0x03000000: return input(prompt) else: return raw_input(prompt) def print_usage(self): os.system('clear') print('--------------------------') print(self.grn+'Inspection mode'+self.blk) print('--------------------------') print(self.grn+'[*] Captured traffic can be viewed with "list" command.') print('[*] Give packet number to inspect packet.') print('[*] Commands: "help", "list", "exit"') print(self.warn+'Press enter to continue'+self.blk) self.get_input('...') return True def print_packets(self,packets): #Print list of captured packets self.packet_number = 1 for self.packet in packets: print(str(self.packet_number)+": " + self.packet.summary()) self.packet_number += 1 def prompt(self, cap): self.cap = cap self.option = None self.opts = ['list', 'help', 'exit'] self.print_usage() os.system('clear') print(self.grn+'[*] Listing packages'+self.blk) time.sleep(1) self.print_packets(self.cap) while True: try: print(self.grn+"- - - - - - - - - - - - - - - - - - - - - ") print("Give packet number to inspect or try \"help\":") print("- - - - - - - - - - - - - - - - - - - - - "+self.blk) ###Get user's option### self.choice = self.get_input(">>>") try: if self.choice in self.opts: if self.choice.lower() == 'list': self.parser(self.choice, cap=self.cap) continue elif self.choice.lower() == 'exit': return else: self.parser(self.choice) continue ###Show selected packet###
[ " self.choice = int(self.choice) - 1" ]
615
lcc
python
null
0015062cf7e9262884bb54332e85c9529f05689017c95eff
namespace HospitalityManagement.Dialogs { partial class rptParamsDiag { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.docTypComboBox = new System.Windows.Forms.ComboBox(); this.OKButton = new System.Windows.Forms.Button(); this.label6 = new System.Windows.Forms.Label(); this.endDteButton = new System.Windows.Forms.Button(); this.label8 = new System.Windows.Forms.Label(); this.cancelButton = new System.Windows.Forms.Button(); this.endDteTextBox = new System.Windows.Forms.TextBox(); this.startDteButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.startDteTextBox = new System.Windows.Forms.TextBox(); this.createdByTextBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.createdByIDTextBox = new System.Windows.Forms.TextBox(); this.createdByButton = new System.Windows.Forms.Button(); this.sortByComboBox = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.rptComboBox = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.useCreationDateCheckBox = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // docTypComboBox // this.docTypComboBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.docTypComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.docTypComboBox.FormattingEnabled = true; this.docTypComboBox.Items.AddRange(new object[] { "Pro-Forma Invoice", "Sales Order", "Sales Invoice", "Internal Item Request", "Item Issue-Unbilled", "Sales Return"}); this.docTypComboBox.Location = new System.Drawing.Point(91, 83); this.docTypComboBox.Name = "docTypComboBox"; this.docTypComboBox.Size = new System.Drawing.Size(264, 21); this.docTypComboBox.TabIndex = 4; // // OKButton // this.OKButton.Location = new System.Drawing.Point(112, 185); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(75, 23); this.OKButton.TabIndex = 6; this.OKButton.Text = "OK"; this.OKButton.UseVisualStyleBackColor = true; this.OKButton.Click += new System.EventHandler(this.OKButton_Click); // // label6 // this.label6.AutoSize = true; this.label6.ForeColor = System.Drawing.Color.White; this.label6.Location = new System.Drawing.Point(5, 86); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(86, 13); this.label6.TabIndex = 74; this.label6.Text = "Document Type:"; // // endDteButton // this.endDteButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.endDteButton.ForeColor = System.Drawing.Color.Black; this.endDteButton.Location = new System.Drawing.Point(328, 56); this.endDteButton.Name = "endDteButton"; this.endDteButton.Size = new System.Drawing.Size(28, 23); this.endDteButton.TabIndex = 3; this.endDteButton.TabStop = false; this.endDteButton.Text = "..."; this.endDteButton.UseVisualStyleBackColor = true; this.endDteButton.Click += new System.EventHandler(this.endDteButton_Click); // // label8 // this.label8.AutoSize = true; this.label8.ForeColor = System.Drawing.Color.White; this.label8.Location = new System.Drawing.Point(5, 61); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(55, 13); this.label8.TabIndex = 73; this.label8.Text = "End Date:"; // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(187, 185); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 7; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // endDteTextBox // this.endDteTextBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.endDteTextBox.Location = new System.Drawing.Point(92, 57); this.endDteTextBox.Name = "endDteTextBox"; this.endDteTextBox.Size = new System.Drawing.Size(233, 21); this.endDteTextBox.TabIndex = 2; this.endDteTextBox.TextChanged += new System.EventHandler(this.startDteTextBox_TextChanged); this.endDteTextBox.Leave += new System.EventHandler(this.startDteTextBox_Leave); // // startDteButton // this.startDteButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.startDteButton.ForeColor = System.Drawing.Color.Black; this.startDteButton.Location = new System.Drawing.Point(328, 30); this.startDteButton.Name = "startDteButton"; this.startDteButton.Size = new System.Drawing.Size(28, 23); this.startDteButton.TabIndex = 1; this.startDteButton.TabStop = false; this.startDteButton.Text = "..."; this.startDteButton.UseVisualStyleBackColor = true; this.startDteButton.Click += new System.EventHandler(this.startDteButton_Click); // // label1 // this.label1.AutoSize = true; this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(5, 35); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(61, 13); this.label1.TabIndex = 70; this.label1.Text = "Start Date:"; // // startDteTextBox // this.startDteTextBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.startDteTextBox.Location = new System.Drawing.Point(92, 31); this.startDteTextBox.Name = "startDteTextBox"; this.startDteTextBox.Size = new System.Drawing.Size(233, 21); this.startDteTextBox.TabIndex = 0; this.startDteTextBox.TextChanged += new System.EventHandler(this.startDteTextBox_TextChanged); this.startDteTextBox.Leave += new System.EventHandler(this.startDteTextBox_Leave); // // createdByTextBox // this.createdByTextBox.Location = new System.Drawing.Point(92, 109); this.createdByTextBox.MaxLength = 200; this.createdByTextBox.Name = "createdByTextBox"; this.createdByTextBox.Size = new System.Drawing.Size(233, 21); this.createdByTextBox.TabIndex = 193; this.createdByTextBox.TextChanged += new System.EventHandler(this.startDteTextBox_TextChanged); this.createdByTextBox.Leave += new System.EventHandler(this.startDteTextBox_Leave); // // label4 // this.label4.AutoSize = true; this.label4.ForeColor = System.Drawing.Color.White; this.label4.Location = new System.Drawing.Point(5, 113); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(65, 13); this.label4.TabIndex = 192; this.label4.Text = "Created By:"; // // createdByIDTextBox // this.createdByIDTextBox.Location = new System.Drawing.Point(293, 109); this.createdByIDTextBox.MaxLength = 200; this.createdByIDTextBox.Name = "createdByIDTextBox"; this.createdByIDTextBox.ReadOnly = true; this.createdByIDTextBox.Size = new System.Drawing.Size(32, 21); this.createdByIDTextBox.TabIndex = 194; this.createdByIDTextBox.TabStop = false; this.createdByIDTextBox.Text = "-1"; // // createdByButton // this.createdByButton.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.createdByButton.ForeColor = System.Drawing.Color.Black; this.createdByButton.Location = new System.Drawing.Point(328, 109); this.createdByButton.Name = "createdByButton"; this.createdByButton.Size = new System.Drawing.Size(28, 23); this.createdByButton.TabIndex = 195; this.createdByButton.TabStop = false; this.createdByButton.Text = "..."; this.createdByButton.UseVisualStyleBackColor = true; this.createdByButton.Click += new System.EventHandler(this.createdByButton_Click); // // sortByComboBox // this.sortByComboBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.sortByComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.sortByComboBox.FormattingEnabled = true; this.sortByComboBox.Items.AddRange(new object[] { "QTY", "TOTAL AMOUNT"}); this.sortByComboBox.Location = new System.Drawing.Point(91, 135); this.sortByComboBox.Name = "sortByComboBox"; this.sortByComboBox.Size = new System.Drawing.Size(264, 21); this.sortByComboBox.TabIndex = 5; // // label2 // this.label2.AutoSize = true; this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(5, 138); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(46, 13); this.label2.TabIndex = 197; this.label2.Text = "Sort By:"; // // rptComboBox // this.rptComboBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(128))))); this.rptComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.rptComboBox.FormattingEnabled = true; this.rptComboBox.Items.AddRange(new object[] { "Money Received Report (Payments Received)", "Money Received Report (Documents Created)", "Items Sold/Issued Report", "Rooms Needing Cleaning"});
[ " this.rptComboBox.Location = new System.Drawing.Point(92, 5);" ]
764
lcc
csharp
null
94f4579778d0f769443d95027663337643885b8b0b67cd03
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'NoteReferenceNS' db.create_table(u'main_notereferencens', ( (u'notesection_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.NoteSection'], unique=True, primary_key=True)), ('note_reference', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Note'])), ('content', self.gf('editorsnotes.main.fields.XHTMLField')(null=True, blank=True)), )) db.send_create_signal('main', ['NoteReferenceNS']) # Adding model 'CitationNS' db.create_table(u'main_citationns', ( (u'notesection_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.NoteSection'], unique=True, primary_key=True)), ('document', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Document'])), ('content', self.gf('editorsnotes.main.fields.XHTMLField')(null=True, blank=True)), )) db.send_create_signal('main', ['CitationNS']) # Adding model 'TextNS' db.create_table(u'main_textns', ( (u'notesection_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['main.NoteSection'], unique=True, primary_key=True)), ('content', self.gf('editorsnotes.main.fields.XHTMLField')()), )) db.send_create_signal('main', ['TextNS']) # Deleting field 'NoteSection.content' db.delete_column(u'main_notesection', 'content') # Deleting field 'NoteSection.document' db.delete_column(u'main_notesection', 'document_id') # Adding field 'NoteSection._section_type' db.add_column(u'main_notesection', '_section_type', self.gf('django.db.models.fields.CharField')(default='', max_length=100), keep_default=False) # Adding field 'NoteSection.note_section_id' db.add_column(u'main_notesection', 'note_section_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding field 'NoteSection.ordering' db.add_column(u'main_notesection', 'ordering', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False) # Adding field 'Note.sections_counter' db.add_column(u'main_note', 'sections_counter', self.gf('django.db.models.fields.PositiveIntegerField')(default=0), keep_default=False) def backwards(self, orm): # Deleting model 'NoteReferenceNS' db.delete_table(u'main_notereferencens') # Deleting model 'CitationNS' db.delete_table(u'main_citationns') # Deleting model 'TextNS' db.delete_table(u'main_textns') # Adding field 'NoteSection.content' db.add_column(u'main_notesection', 'content', self.gf('editorsnotes.main.fields.XHTMLField')(null=True, blank=True), keep_default=False) # Adding field 'NoteSection.document' db.add_column(u'main_notesection', 'document', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['main.Document'], null=True, blank=True), keep_default=False) # Deleting field 'NoteSection._section_type' db.delete_column(u'main_notesection', '_section_type') # Deleting field 'NoteSection.note_section_id' db.delete_column(u'main_notesection', 'note_section_id') # Deleting field 'NoteSection.ordering' db.delete_column(u'main_notesection', 'ordering') # Deleting field 'Note.sections_counter' db.delete_column(u'main_note', 'sections_counter') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'main.alias': { 'Meta': {'unique_together': "(('topic', 'name'),)", 'object_name': 'Alias'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_alias_set'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': "'80'"}), 'topic': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'aliases'", 'to': "orm['main.Topic']"}) }, 'main.citation': { 'Meta': {'ordering': "['ordering']", 'object_name': 'Citation'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_citation_set'", 'to': u"orm['auth.User']"}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'citations'", 'to': "orm['main.Document']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'last_updater': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_to_update_citation_set'", 'to': u"orm['auth.User']"}), 'notes': ('editorsnotes.main.fields.XHTMLField', [], {'null': 'True', 'blank': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'ordering': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'main.citationns': { 'Meta': {'ordering': "['ordering', 'note_section_id']", 'object_name': 'CitationNS', '_ormbases': ['main.NoteSection']}, 'content': ('editorsnotes.main.fields.XHTMLField', [], {'null': 'True', 'blank': 'True'}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['main.Document']"}), u'notesection_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['main.NoteSection']", 'unique': 'True', 'primary_key': 'True'}) }, 'main.document': { 'Meta': {'ordering': "['ordering', 'import_id']", 'object_name': 'Document'}, 'affiliated_projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['main.Project']", 'null': 'True', 'blank': 'True'}), 'collection': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'parts'", 'null': 'True', 'to': "orm['main.Document']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_document_set'", 'to': u"orm['auth.User']"}), 'description': ('editorsnotes.main.fields.XHTMLField', [], {}), 'edtf_date': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'import_id': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'default': "'English'", 'max_length': '32'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'last_updater': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_to_update_document_set'", 'to': u"orm['auth.User']"}), 'ordering': ('django.db.models.fields.CharField', [], {'max_length': '32'}) }, 'main.documentlink': { 'Meta': {'object_name': 'DocumentLink'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_documentlink_set'", 'to': u"orm['auth.User']"}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'links'", 'to': "orm['main.Document']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, 'main.documentmetadata': { 'Meta': {'unique_together': "(('document', 'key'),)", 'object_name': 'DocumentMetadata'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_documentmetadata_set'", 'to': u"orm['auth.User']"}), 'document': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'metadata'", 'to': "orm['main.Document']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'value': ('django.db.models.fields.TextField', [], {}) }, 'main.featureditem': { 'Meta': {'object_name': 'FeaturedItem'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_featureditem_set'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['main.Project']"}) }, 'main.footnote': { 'Meta': {'object_name': 'Footnote'}, 'content': ('editorsnotes.main.fields.XHTMLField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_footnote_set'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'last_updater': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_to_update_footnote_set'", 'to': u"orm['auth.User']"}), 'transcript': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'footnotes'", 'to': "orm['main.Transcript']"}) }, 'main.note': { 'Meta': {'ordering': "['-last_updated']", 'object_name': 'Note'}, 'affiliated_projects': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['main.Project']", 'null': 'True', 'blank': 'True'}), 'assigned_users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['main.UserProfile']", 'null': 'True', 'blank': 'True'}), 'content': ('editorsnotes.main.fields.XHTMLField', [], {}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_note_set'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'last_updater': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_to_update_note_set'", 'to': u"orm['auth.User']"}), 'sections_counter': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'1'", 'max_length': '1'}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': "'80'"}) }, 'main.notereferencens': { 'Meta': {'ordering': "['ordering', 'note_section_id']", 'object_name': 'NoteReferenceNS', '_ormbases': ['main.NoteSection']}, 'content': ('editorsnotes.main.fields.XHTMLField', [], {'null': 'True', 'blank': 'True'}), 'note_reference': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['main.Note']"}), u'notesection_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['main.NoteSection']", 'unique': 'True', 'primary_key': 'True'}) }, 'main.notesection': { 'Meta': {'ordering': "['ordering', 'note_section_id']", 'object_name': 'NoteSection'}, '_section_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_notesection_set'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'last_updater': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'last_to_update_notesection_set'", 'to': u"orm['auth.User']"}), 'note': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'sections'", 'to': "orm['main.Note']"}), 'note_section_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}), 'ordering': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}) }, 'main.project': { 'Meta': {'object_name': 'Project'}, 'description': ('editorsnotes.main.fields.XHTMLField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': "'80'"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}) }, 'main.projectinvitation': { 'Meta': {'object_name': 'ProjectInvitation'}, 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_projectinvitation_set'", 'to': u"orm['auth.User']"}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['main.Project']"}), 'role': ('django.db.models.fields.CharField', [], {'default': "'researcher'", 'max_length': '10'}) }, 'main.scan': {
[ " 'Meta': {'ordering': \"['ordering']\", 'object_name': 'Scan'}," ]
1,056
lcc
python
null
01f0d043830d266acc4757da3d85f78ced040ba1063aa7fb
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.sdo.helper; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.transform.Source; import org.eclipse.persistence.exceptions.SDOException; import org.eclipse.persistence.internal.helper.ClassConstants; import org.eclipse.persistence.internal.oxm.XMLConversionManager; import org.eclipse.persistence.internal.oxm.schema.SchemaModelProject; import org.eclipse.persistence.internal.oxm.schema.model.All; import org.eclipse.persistence.internal.oxm.schema.model.Annotation; import org.eclipse.persistence.internal.oxm.schema.model.Any; import org.eclipse.persistence.internal.oxm.schema.model.Attribute; import org.eclipse.persistence.internal.oxm.schema.model.AttributeGroup; import org.eclipse.persistence.internal.oxm.schema.model.Choice; import org.eclipse.persistence.internal.oxm.schema.model.ComplexContent; import org.eclipse.persistence.internal.oxm.schema.model.ComplexType; import org.eclipse.persistence.internal.oxm.schema.model.Element; import org.eclipse.persistence.internal.oxm.schema.model.Extension; import org.eclipse.persistence.internal.oxm.schema.model.Group; import org.eclipse.persistence.internal.oxm.schema.model.Import; import org.eclipse.persistence.internal.oxm.schema.model.Include; import org.eclipse.persistence.internal.oxm.schema.model.List; import org.eclipse.persistence.internal.oxm.schema.model.NestedParticle; import org.eclipse.persistence.internal.oxm.schema.model.Occurs; import org.eclipse.persistence.internal.oxm.schema.model.Restriction; import org.eclipse.persistence.internal.oxm.schema.model.Schema; import org.eclipse.persistence.internal.oxm.schema.model.Sequence; import org.eclipse.persistence.internal.oxm.schema.model.SimpleComponent; import org.eclipse.persistence.internal.oxm.schema.model.SimpleContent; import org.eclipse.persistence.internal.oxm.schema.model.SimpleType; import org.eclipse.persistence.internal.oxm.schema.model.TypeDefParticle; import org.eclipse.persistence.internal.oxm.schema.model.Union; import org.eclipse.persistence.oxm.NamespaceResolver; import org.eclipse.persistence.oxm.XMLConstants; import org.eclipse.persistence.oxm.XMLContext; import org.eclipse.persistence.oxm.XMLDescriptor; import org.eclipse.persistence.oxm.XMLUnmarshaller; import org.eclipse.persistence.sdo.SDOConstants; import org.eclipse.persistence.sdo.SDOProperty; import org.eclipse.persistence.sdo.SDOType; import org.eclipse.persistence.sdo.helper.extension.SDOUtil; import org.eclipse.persistence.sdo.types.SDODataType; import org.eclipse.persistence.sdo.types.SDOWrapperType; import org.eclipse.persistence.sessions.Project; import commonj.sdo.Property; import commonj.sdo.Type; import commonj.sdo.helper.HelperContext; /** * <p><b>Purpose</b>: Called from XSDHelper define methods to generate SDO Types from a Schema * * @see commonj.sdo.XSDHelper */ public class SDOTypesGenerator { private Project schemaProject; private Schema rootSchema; private HashMap processedComplexTypes; private HashMap processedSimpleTypes; private HashMap processedElements; private HashMap processedAttributes; private Map itemNameToSDOName; private boolean processImports; private boolean returnAllTypes; private java.util.List<NamespaceResolver> namespaceResolvers; private boolean inRestriction; // hold the context containing all helpers so that we can preserve inter-helper relationships private HelperContext aHelperContext; private java.util.List<SDOType> anonymousTypes; private java.util.Map<QName, Type> generatedTypes; private java.util.Map<QName, SDOType> generatedTypesByXsdQName; private java.util.Map<QName, Property> generatedGlobalElements; private java.util.Map<QName, Property> generatedGlobalAttributes; private String packageName; private java.util.List<NonContainmentReference> nonContainmentReferences; private Map<Type, java.util.List<GlobalRef>> globalRefs; private boolean isImportProcessor; public SDOTypesGenerator(HelperContext aContext) { anonymousTypes = new ArrayList<SDOType>(); generatedTypesByXsdQName = new HashMap<QName, SDOType>(); processedComplexTypes = new HashMap(); processedSimpleTypes = new HashMap(); processedElements = new HashMap(); processedAttributes = new HashMap(); itemNameToSDOName = new HashMap(); namespaceResolvers = new ArrayList(); this.aHelperContext = aContext; } public java.util.List<Type> define(Source xsdSource, SchemaResolver schemaResolver) { return define(xsdSource, schemaResolver, false, true); } public java.util.List<Type> define(Source xsdSource, SchemaResolver schemaResolver, boolean includeAllTypes, boolean processImports) { Schema schema = getSchema(xsdSource, schemaResolver); return define(schema, includeAllTypes, processImports); } public java.util.List<Type> define(Schema schema, boolean includeAllTypes, boolean processImports) { // Initialize the List of Types before we process the schema java.util.List<Type> returnList = new ArrayList<Type>(); setReturnAllTypes(includeAllTypes); setProcessImports(processImports); processSchema(schema); returnList.addAll(getGeneratedTypes().values()); returnList.addAll(anonymousTypes); if (!this.isImportProcessor()) { java.util.List descriptorsToAdd = new ArrayList(returnList); Iterator<Type> iter = descriptorsToAdd.iterator(); while (iter.hasNext()) { SDOType nextSDOType = (SDOType) iter.next(); if (!nextSDOType.isFinalized()) { //Only throw this error if we're not processing an import. throw SDOException.typeReferencedButNotDefined(nextSDOType.getURI(), nextSDOType.getName()); } Iterator<Property> propertiesIter = nextSDOType.getProperties().iterator(); while (propertiesIter.hasNext()) { SDOProperty prop = (SDOProperty) propertiesIter.next(); if (prop.getType().isDataType() && prop.isContainment()) { // If isDataType is true, then isContainment has to be false. // This property was likely created as a stub, and isContainment never got reset // when the property was fully defined. // This problem was uncovered in bug 6809767 prop.setContainment(false); } } } Iterator<Property> propertiesIter = getGeneratedGlobalElements().values().iterator(); while (propertiesIter.hasNext()) { SDOProperty nextSDOProperty = (SDOProperty) propertiesIter.next(); if (!nextSDOProperty.isFinalized()) { //Only throw this error if we're not processing an import. throw SDOException.referencedPropertyNotFound(nextSDOProperty.getUri(), nextSDOProperty.getName()); } } propertiesIter = getGeneratedGlobalAttributes().values().iterator(); while (propertiesIter.hasNext()) { SDOProperty nextSDOProperty = (SDOProperty) propertiesIter.next(); if (!nextSDOProperty.isFinalized()) { //Only throw this error if we're not processing an import. throw SDOException.referencedPropertyNotFound(nextSDOProperty.getUri(), nextSDOProperty.getName()); } } iter = getGeneratedTypes().values().iterator(); //If we get here all types were finalized correctly while (iter.hasNext()) { SDOType nextSDOType = (SDOType) iter.next(); ((SDOTypeHelper) aHelperContext.getTypeHelper()).addType(nextSDOType); } Iterator anonymousIterator = getAnonymousTypes().iterator(); while (anonymousIterator.hasNext()) { SDOType nextSDOType = (SDOType) anonymousIterator.next(); ((SDOTypeHelper) aHelperContext.getTypeHelper()).getAnonymousTypes().add(nextSDOType); } // add any base types to the list for (int i=0; i<descriptorsToAdd.size(); i++) { SDOType nextSDOType = (SDOType) descriptorsToAdd.get(i); if (!nextSDOType.isDataType() && !nextSDOType.isSubType() && nextSDOType.isBaseType()) { nextSDOType.setupInheritance(null); } else if (!nextSDOType.isDataType() && nextSDOType.isSubType() && !getGeneratedTypes().values().contains(nextSDOType.getBaseTypes().get(0))) { SDOType baseType = (SDOType) nextSDOType.getBaseTypes().get(0); while (baseType != null) { descriptorsToAdd.add(baseType); if (baseType.getBaseTypes().size() == 0) { // baseType should now be root of inheritance baseType.setupInheritance(null); baseType = null; } else { baseType = (SDOType) baseType.getBaseTypes().get(0); } } } } ((SDOXMLHelper) aHelperContext.getXMLHelper()).addDescriptors(descriptorsToAdd); //go through generatedGlobalProperties and add to xsdhelper Iterator<QName> qNameIter = getGeneratedGlobalElements().keySet().iterator(); while (qNameIter.hasNext()) { QName nextQName = qNameIter.next(); SDOProperty nextSDOProperty = (SDOProperty) getGeneratedGlobalElements().get(nextQName); ((SDOXSDHelper) aHelperContext.getXSDHelper()).addGlobalProperty(nextQName, nextSDOProperty, true); } qNameIter = getGeneratedGlobalAttributes().keySet().iterator(); while (qNameIter.hasNext()) { QName nextQName = qNameIter.next(); SDOProperty nextSDOProperty = (SDOProperty) getGeneratedGlobalAttributes().get(nextQName); ((SDOXSDHelper) aHelperContext.getXSDHelper()).addGlobalProperty(nextQName, nextSDOProperty, false); } Iterator<java.util.List<GlobalRef>> globalRefsIter = getGlobalRefs().values().iterator(); while (globalRefsIter.hasNext()) { java.util.List<GlobalRef> nextList = globalRefsIter.next(); if (nextList.size() > 0) { GlobalRef ref = nextList.get(0); throw SDOException.referencedPropertyNotFound(((SDOProperty) ref.getProperty()).getUri(), ref.getProperty().getName()); } } } return returnList; } private void processSchema(Schema parsedSchema) { rootSchema = parsedSchema; initialize(); namespaceResolvers.add(rootSchema.getNamespaceResolver()); processIncludes(rootSchema.getIncludes()); processImports(rootSchema.getImports()); preprocessGlobalTypes(rootSchema); processGlobalAttributes(rootSchema); processGlobalElements(rootSchema); processGlobalSimpleTypes(rootSchema); processGlobalComplexTypes(rootSchema); postProcessing(); } private void processImports(java.util.List imports) { if ((imports == null) || (imports.size() == 0) || !isProcessImports()) { return; } Iterator iter = imports.iterator(); while (iter.hasNext()) { Import nextImport = (Import) iter.next(); try { processImportIncludeInternal(nextImport); } catch (Exception e) { throw SDOException.errorProcessingImport(nextImport.getSchemaLocation(), nextImport.getNamespace(), e); } } } private void processIncludes(java.util.List includes) { if ((includes == null) || (includes.size() == 0) || !isProcessImports()) { return; } Iterator iter = includes.iterator(); while (iter.hasNext()) { Include nextInclude = (Include) iter.next(); try { processImportIncludeInternal(nextInclude); } catch (Exception e) { throw SDOException.errorProcessingInclude(nextInclude.getSchemaLocation(), e); } } } /** * INTERNAL: * This function is referenced by processImport or processInclude possibly recursively * @param Include theImportOrInclude * @throws Exception */ private void processImportIncludeInternal(Include theImportOrInclude) throws Exception { if (theImportOrInclude.getSchema() != null) { SDOTypesGenerator generator = new SDOTypesGenerator(aHelperContext); generator.setAnonymousTypes(getAnonymousTypes()); generator.setGeneratedTypes(getGeneratedTypes()); generator.setGeneratedTypesByXsdQName(getGeneratedTypesByXsdQName()); generator.setGeneratedGlobalElements(getGeneratedGlobalElements()); generator.setGeneratedGlobalAttributes(getGeneratedGlobalAttributes()); // Both imports and includes are treated the same when checking for a mid-schema tree walk state generator.setIsImportProcessor(true); // May throw an IAE if a global type: local part cannot be null when creating a QName java.util.List<Type> importedTypes = generator.define(theImportOrInclude.getSchema(), isReturnAllTypes(), isProcessImports()); processedComplexTypes.putAll(generator.processedComplexTypes); processedSimpleTypes.putAll(generator.processedSimpleTypes); processedElements.putAll(generator.processedElements); processedAttributes.putAll(generator.processedAttributes); if (null != importedTypes) { for (int i = 0, size = importedTypes.size(); i < size; i++) { SDOType nextType = (SDOType) importedTypes.get(i); getGeneratedTypes().put(nextType.getQName(), nextType); } } //copy over any global properties Iterator<QName> globalPropsIter = generator.getGeneratedGlobalElements().keySet().iterator(); while (globalPropsIter.hasNext()) { QName nextKey = globalPropsIter.next(); getGeneratedGlobalElements().put(nextKey, generator.getGeneratedGlobalElements().get(nextKey)); } globalPropsIter = generator.getGeneratedGlobalAttributes().keySet().iterator(); while (globalPropsIter.hasNext()) { QName nextKey = globalPropsIter.next(); getGeneratedGlobalAttributes().put(nextKey, generator.getGeneratedGlobalAttributes().get(nextKey)); } //copy over any unfinished globalRefs Iterator<Type> globalRefsIter = generator.getGlobalRefs().keySet().iterator(); while (globalRefsIter.hasNext()) { Type nextKey = globalRefsIter.next(); getGlobalRefs().put(nextKey, generator.getGlobalRefs().get(nextKey)); } } } private boolean typesExists(String targetNamespace, String sdoTypeName) { boolean alreadyProcessed = false; if ((targetNamespace != null) && (targetNamespace.equals(SDOConstants.SDOJAVA_URL) || targetNamespace.equals(SDOConstants.SDO_URL) || targetNamespace.equals(SDOConstants.SDOXML_URL))) { alreadyProcessed = true; } else { QName qname = new QName(targetNamespace, sdoTypeName); Object processed = processedComplexTypes.get(qname); if (processed != null) { alreadyProcessed = true; } } if (!alreadyProcessed) { SDOType lookup = (SDOType) aHelperContext.getTypeHelper().getType(targetNamespace, sdoTypeName); if ((lookup != null) && lookup.isFinalized()) { if (isReturnAllTypes()) { QName qname = new QName(targetNamespace, sdoTypeName); getGeneratedTypes().put(qname, lookup); } return true; } else if (lookup == null) {
[ " QName qname = new QName(targetNamespace, sdoTypeName);" ]
1,110
lcc
java
null
cfb6b58b94ffae9a2bc26c67c46fbd41b8ceea666926fb64
# -*- coding: utf-8 -*- ################################################################################## # # Copyright (c) 2005-2006 Axelor SARL. (http://www.axelor.com) # and 2004-2010 Tiny SPRL (<http://tiny.be>). # # $Id: hr.py 4656 2006-11-24 09:58:42Z Cyp $ # # 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/>. # ############################################################################## import datetime import math import time from operator import attrgetter from openerp.exceptions import Warning from openerp import tools from openerp.osv import fields, osv from openerp.tools.translate import _ class hr_holidays_status(osv.osv): _name = "hr.holidays.status" _description = "Leave Type" def get_days(self, cr, uid, ids, employee_id, context=None): result = dict((id, dict(max_leaves=0, leaves_taken=0, remaining_leaves=0, virtual_remaining_leaves=0)) for id in ids) holiday_ids = self.pool['hr.holidays'].search(cr, uid, [('employee_id', '=', employee_id), ('state', 'in', ['confirm', 'validate1', 'validate']), ('holiday_status_id', 'in', ids) ], context=context) for holiday in self.pool['hr.holidays'].browse(cr, uid, holiday_ids, context=context): status_dict = result[holiday.holiday_status_id.id] if holiday.type == 'add': status_dict['virtual_remaining_leaves'] += holiday.number_of_days_temp if holiday.state == 'validate': status_dict['max_leaves'] += holiday.number_of_days_temp status_dict['remaining_leaves'] += holiday.number_of_days_temp elif holiday.type == 'remove': # number of days is negative status_dict['virtual_remaining_leaves'] -= holiday.number_of_days_temp if holiday.state == 'validate': status_dict['leaves_taken'] += holiday.number_of_days_temp status_dict['remaining_leaves'] -= holiday.number_of_days_temp return result def _user_left_days(self, cr, uid, ids, name, args, context=None): employee_id = False if context and 'employee_id' in context: employee_id = context['employee_id'] else: employee_ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context) if employee_ids: employee_id = employee_ids[0] if employee_id: res = self.get_days(cr, uid, ids, employee_id, context=context) else: res = dict((res_id, {'leaves_taken': 0, 'remaining_leaves': 0, 'max_leaves': 0}) for res_id in ids) return res _columns = { 'name': fields.char('Leave Type', size=64, required=True, translate=True), 'categ_id': fields.many2one('calendar.event.type', 'Meeting Type', help='Once a leave is validated, Odoo will create a corresponding meeting of this type in the calendar.'), 'color_name': fields.selection([('red', 'Red'),('blue','Blue'), ('lightgreen', 'Light Green'), ('lightblue','Light Blue'), ('lightyellow', 'Light Yellow'), ('magenta', 'Magenta'),('lightcyan', 'Light Cyan'),('black', 'Black'),('lightpink', 'Light Pink'),('brown', 'Brown'),('violet', 'Violet'),('lightcoral', 'Light Coral'),('lightsalmon', 'Light Salmon'),('lavender', 'Lavender'),('wheat', 'Wheat'),('ivory', 'Ivory')],'Color in Report', required=True, help='This color will be used in the leaves summary located in Reporting\Leaves by Department.'), 'limit': fields.boolean('Allow to Override Limit', help='If you select this check box, the system allows the employees to take more leaves than the available ones for this type and will not take them into account for the "Remaining Legal Leaves" defined on the employee form.'), 'active': fields.boolean('Active', help="If the active field is set to false, it will allow you to hide the leave type without removing it."), 'max_leaves': fields.function(_user_left_days, string='Maximum Allowed', help='This value is given by the sum of all holidays requests with a positive value.', multi='user_left_days'), 'leaves_taken': fields.function(_user_left_days, string='Leaves Already Taken', help='This value is given by the sum of all holidays requests with a negative value.', multi='user_left_days'), 'remaining_leaves': fields.function(_user_left_days, string='Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken', multi='user_left_days'), 'virtual_remaining_leaves': fields.function(_user_left_days, string='Virtual Remaining Leaves', help='Maximum Leaves Allowed - Leaves Already Taken - Leaves Waiting Approval', multi='user_left_days'), 'double_validation': fields.boolean('Apply Double Validation', help="When selected, the Allocation/Leave Requests for this type require a second validation to be approved."), } _defaults = { 'color_name': 'red', 'active': True, } def name_get(self, cr, uid, ids, context=None): if context is None: context = {} if not context.get('employee_id',False): # leave counts is based on employee_id, would be inaccurate if not based on correct employee return super(hr_holidays_status, self).name_get(cr, uid, ids, context=context) res = [] for record in self.browse(cr, uid, ids, context=context): name = record.name if not record.limit: name = name + (' (%g/%g)' % (record.leaves_taken or 0.0, record.max_leaves or 0.0)) res.append((record.id, name)) return res class hr_holidays(osv.osv): _name = "hr.holidays" _description = "Leave" _order = "type desc, date_from asc" _inherit = ['mail.thread', 'ir.needaction_mixin'] _track = { 'state': { 'hr_holidays.mt_holidays_approved': lambda self, cr, uid, obj, ctx=None: obj.state == 'validate', 'hr_holidays.mt_holidays_refused': lambda self, cr, uid, obj, ctx=None: obj.state == 'refuse', 'hr_holidays.mt_holidays_confirmed': lambda self, cr, uid, obj, ctx=None: obj.state == 'confirm', }, } def _employee_get(self, cr, uid, context=None): emp_id = context.get('default_employee_id', False) if emp_id: return emp_id ids = self.pool.get('hr.employee').search(cr, uid, [('user_id', '=', uid)], context=context) if ids: return ids[0] return False def _compute_number_of_days(self, cr, uid, ids, name, args, context=None): result = {} for hol in self.browse(cr, uid, ids, context=context): if hol.type=='remove': result[hol.id] = -hol.number_of_days_temp else: result[hol.id] = hol.number_of_days_temp return result def _get_can_reset(self, cr, uid, ids, name, arg, context=None): """User can reset a leave request if it is its own leave request or if he is an Hr Manager. """ user = self.pool['res.users'].browse(cr, uid, uid, context=context) group_hr_manager_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_hr_manager')[1] if group_hr_manager_id in [g.id for g in user.groups_id]: return dict.fromkeys(ids, True) result = dict.fromkeys(ids, False) for holiday in self.browse(cr, uid, ids, context=context): if holiday.employee_id and holiday.employee_id.user_id and holiday.employee_id.user_id.id == uid: result[holiday.id] = True return result def _check_date(self, cr, uid, ids, context=None): for holiday in self.browse(cr, uid, ids, context=context): domain = [ ('date_from', '<=', holiday.date_to), ('date_to', '>=', holiday.date_from), ('employee_id', '=', holiday.employee_id.id), ('id', '!=', holiday.id), ('state', 'not in', ['cancel', 'refuse']), ] nholidays = self.search_count(cr, uid, domain, context=context) if nholidays: return False return True _check_holidays = lambda self, cr, uid, ids, context=None: self.check_holidays(cr, uid, ids, context=context) _columns = { 'name': fields.char('Description', size=64), 'state': fields.selection([('draft', 'To Submit'), ('cancel', 'Cancelled'),('confirm', 'To Approve'), ('refuse', 'Refused'), ('validate1', 'Second Approval'), ('validate', 'Approved')], 'Status', readonly=True, track_visibility='onchange', copy=False, help='The status is set to \'To Submit\', when a holiday request is created.\ \nThe status is \'To Approve\', when holiday request is confirmed by user.\ \nThe status is \'Refused\', when holiday request is refused by manager.\ \nThe status is \'Approved\', when holiday request is approved by manager.'), 'user_id':fields.related('employee_id', 'user_id', type='many2one', relation='res.users', string='User', store=True), 'date_from': fields.datetime('Start Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, select=True, copy=False), 'date_to': fields.datetime('End Date', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False), 'holiday_status_id': fields.many2one("hr.holidays.status", "Leave Type", required=True,readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'employee_id': fields.many2one('hr.employee', "Employee", select=True, invisible=False, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'manager_id': fields.many2one('hr.employee', 'First Approval', invisible=False, readonly=True, copy=False, help='This area is automatically filled by the user who validate the leave'), 'notes': fields.text('Reasons',readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'number_of_days_temp': fields.float('Allocation', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, copy=False), 'number_of_days': fields.function(_compute_number_of_days, string='Number of Days', store=True), 'meeting_id': fields.many2one('calendar.event', 'Meeting'), 'type': fields.selection([('remove','Leave Request'),('add','Allocation Request')], 'Request Type', required=True, readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help="Choose 'Leave Request' if someone wants to take an off-day. \nChoose 'Allocation Request' if you want to increase the number of leaves available for someone", select=True), 'parent_id': fields.many2one('hr.holidays', 'Parent'), 'linked_request_ids': fields.one2many('hr.holidays', 'parent_id', 'Linked Requests',), 'department_id':fields.related('employee_id', 'department_id', string='Department', type='many2one', relation='hr.department', readonly=True, store=True), 'category_id': fields.many2one('hr.employee.category', "Employee Tag", help='Category of Employee', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}), 'holiday_type': fields.selection([('employee','By Employee'),('category','By Employee Tag')], 'Allocation Mode', readonly=True, states={'draft':[('readonly',False)], 'confirm':[('readonly',False)]}, help='By Employee: Allocation/Request for individual Employee, By Employee Tag: Allocation/Request for group of employees in category', required=True), 'manager_id2': fields.many2one('hr.employee', 'Second Approval', readonly=True, copy=False, help='This area is automaticly filled by the user who validate the leave with second level (If Leave type need second validation)'), 'double_validation': fields.related('holiday_status_id', 'double_validation', type='boolean', relation='hr.holidays.status', string='Apply Double Validation'), 'can_reset': fields.function( _get_can_reset, type='boolean'), } _defaults = { 'employee_id': _employee_get, 'state': 'confirm', 'type': 'remove', 'user_id': lambda obj, cr, uid, context: uid, 'holiday_type': 'employee' } _constraints = [ (_check_date, 'You can not have 2 leaves that overlaps on same day!', ['date_from','date_to']), (_check_holidays, 'The number of remaining leaves is not sufficient for this leave type', ['state','number_of_days_temp']) ] _sql_constraints = [ ('type_value', "CHECK( (holiday_type='employee' AND employee_id IS NOT NULL) or (holiday_type='category' AND category_id IS NOT NULL))", "The employee or employee category of this request is missing. Please make sure that your user login is linked to an employee."), ('date_check2', "CHECK ( (type='add') OR (date_from <= date_to))", "The start date must be anterior to the end date."), ('date_check', "CHECK ( number_of_days_temp >= 0 )", "The number of days must be greater than 0."), ] def _create_resource_leave(self, cr, uid, leaves, context=None): '''This method will create entry in resource calendar leave object at the time of holidays validated ''' obj_res_leave = self.pool.get('resource.calendar.leaves') for leave in leaves: vals = { 'name': leave.name, 'date_from': leave.date_from, 'holiday_id': leave.id, 'date_to': leave.date_to, 'resource_id': leave.employee_id.resource_id.id, 'calendar_id': leave.employee_id.resource_id.calendar_id.id } obj_res_leave.create(cr, uid, vals, context=context) return True def _remove_resource_leave(self, cr, uid, ids, context=None): '''This method will create entry in resource calendar leave object at the time of holidays cancel/removed''' obj_res_leave = self.pool.get('resource.calendar.leaves') leave_ids = obj_res_leave.search(cr, uid, [('holiday_id', 'in', ids)], context=context) return obj_res_leave.unlink(cr, uid, leave_ids, context=context) def onchange_type(self, cr, uid, ids, holiday_type, employee_id=False, context=None): result = {} if holiday_type == 'employee' and not employee_id: ids_employee = self.pool.get('hr.employee').search(cr, uid, [('user_id','=', uid)]) if ids_employee: result['value'] = { 'employee_id': ids_employee[0] } elif holiday_type != 'employee': result['value'] = { 'employee_id': False } return result def onchange_employee(self, cr, uid, ids, employee_id): result = {'value': {'department_id': False}} if employee_id: employee = self.pool.get('hr.employee').browse(cr, uid, employee_id) result['value'] = {'department_id': employee.department_id.id} return result # TODO: can be improved using resource calendar method def _get_number_of_days(self, date_from, date_to): """Returns a float equals to the timedelta between two dates given as string.""" DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" from_dt = datetime.datetime.strptime(date_from, DATETIME_FORMAT) to_dt = datetime.datetime.strptime(date_to, DATETIME_FORMAT) timedelta = to_dt - from_dt diff_day = timedelta.days + float(timedelta.seconds) / 86400 return diff_day def unlink(self, cr, uid, ids, context=None): for rec in self.browse(cr, uid, ids, context=context): if rec.state not in ['draft', 'cancel', 'confirm']: raise osv.except_osv(_('Warning!'),_('You cannot delete a leave which is in %s state.')%(rec.state)) return super(hr_holidays, self).unlink(cr, uid, ids, context) def onchange_date_from(self, cr, uid, ids, date_to, date_from): """ If there are no date set for date_to, automatically set one 8 hours later than the date_from. Also update the number_of_days. """ # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.')) result = {'value': {}} # No date_to set so far: automatically compute one 8 hours later if date_from and not date_to: date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8) result['value']['date_to'] = str(date_to_with_delta) # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1 else: result['value']['number_of_days_temp'] = 0 return result def onchange_date_to(self, cr, uid, ids, date_to, date_from): """ Update the number_of_days. """ # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.')) result = {'value': {}} # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1 else: result['value']['number_of_days_temp'] = 0 return result def add_follower(self, cr, uid, ids, employee_id, context=None): employee = self.pool['hr.employee'].browse(cr, uid, employee_id, context=context) if employee.user_id: self.message_subscribe(cr, uid, ids, [employee.user_id.partner_id.id], context=context) def create(self, cr, uid, values, context=None): """ Override to avoid automatic logging of creation """ if context is None: context = {} employee_id = values.get('employee_id', False) context = dict(context, mail_create_nolog=True, mail_create_nosubscribe=True) if values.get('state') and values['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'): raise osv.except_osv(_('Warning!'), _('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % values.get('state')) hr_holiday_id = super(hr_holidays, self).create(cr, uid, values, context=context) self.add_follower(cr, uid, [hr_holiday_id], employee_id, context=context) return hr_holiday_id def write(self, cr, uid, ids, vals, context=None): employee_id = vals.get('employee_id', False) if vals.get('state') and vals['state'] not in ['draft', 'confirm', 'cancel'] and not self.pool['res.users'].has_group(cr, uid, 'base.group_hr_user'): raise osv.except_osv(_('Warning!'), _('You cannot set a leave request as \'%s\'. Contact a human resource manager.') % vals.get('state')) hr_holiday_id = super(hr_holidays, self).write(cr, uid, ids, vals, context=context) self.add_follower(cr, uid, ids, employee_id, context=context) return hr_holiday_id def holidays_reset(self, cr, uid, ids, context=None): self.write(cr, uid, ids, { 'state': 'draft', 'manager_id': False, 'manager_id2': False, }) to_unlink = [] for record in self.browse(cr, uid, ids, context=context): for record2 in record.linked_request_ids: self.holidays_reset(cr, uid, [record2.id], context=context) to_unlink.append(record2.id) if to_unlink: self.unlink(cr, uid, to_unlink, context=context) return True def holidays_first_validate(self, cr, uid, ids, context=None): obj_emp = self.pool.get('hr.employee') ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)]) manager = ids2 and ids2[0] or False self.holidays_first_validate_notificate(cr, uid, ids, context=context) return self.write(cr, uid, ids, {'state':'validate1', 'manager_id': manager}) def holidays_validate(self, cr, uid, ids, context=None):
[ " obj_emp = self.pool.get('hr.employee')" ]
1,956
lcc
python
null
7dd56f936af4445521f33f3902093e6fbc8fc6051abd5488
// --------------------------------------------------------------------------------- // Copyright (C) 2007-2010 Chillisoft Solutions // // This file is part of the Habanero framework. // // Habanero is a free framework: 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. // // The Habanero framework 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 the Habanero framework. If not, see <http://www.gnu.org/licenses/>. // --------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using Habanero.Base; using Habanero.BO; using Habanero.Faces.Base; using Habanero.Faces.Base.Resources; using MessageBoxButtons = System.Windows.Forms.MessageBoxButtons; using MessageBoxIcon = System.Windows.Forms.MessageBoxIcon; namespace Habanero.Faces.Win { /// <summary> /// Provides a DataGridView that is adapted to show business objects /// </summary> public abstract class GridBaseWin : DataGridViewWin, IGridBase { public GridColumnAutoSizingStrategies ColumnAutoSizingStrategy { get; set; } public int ColumnAutoSizingPadding { get; set; } public bool EnableAlternateRowColoring { get; set; } public bool HideObjectIDColumn { get; set; } public bool AutoResizeColumnsOnGridResize { get; set; } private readonly GridBaseManager _manager; private Timer _resizeTimer; private DateTime _lastResize; private bool _resizeRequired; /// <summary> /// Constructor for <see cref="GridBaseWin"/> /// </summary> protected GridBaseWin() { ConfirmDeletion = false; CheckUserConfirmsDeletionDelegate = CheckUserWantsToDelete; _manager = new GridBaseManager(this); GridBaseManager.CollectionChanged += delegate { FireCollectionChanged(); ImplementColumnAutoSizingStrategy(); ImplementAlternatRowColoring(); }; GridBaseManager.BusinessObjectSelected += delegate { FireBusinessObjectSelected(); }; DoubleClick += DoubleClickHandler; if (GlobalUIRegistry.UIStyleHints != null) { var gridHints = GlobalUIRegistry.UIStyleHints.GridHints; this.DefaultCellStyle.Padding = new Padding(gridHints.Padding.Left, gridHints.Padding.Top, gridHints.Padding.Right, gridHints.Padding.Bottom); var vpad = this.DefaultCellStyle.Padding.Top + this.DefaultCellStyle.Padding.Bottom; this.ColumnHeadersHeight += vpad; this.RowTemplate.Height += vpad; this.ColumnAutoSizingStrategy = gridHints.ColumnAutoSizingStrategy; this.ColumnAutoSizingPadding = gridHints.ColumnAutoSizingPadding; this.EnableAlternateRowColoring = gridHints.EnableAlternateRowColoring; this.ImplementAlternatRowColoring(); this.HideObjectIDColumn = gridHints.HideObjectIDColumn; this.CollectionChanged += (s, e) => { this.SetIDColumnVisibility(!this.HideObjectIDColumn); }; } this._resizeTimer = new Timer() { Enabled = true, Interval = 1000 }; this._resizeTimer.Tick += (sender, e) => { if (!this.AutoResizeColumnsOnGridResize) return; if (this._resizeRequired && (this._lastResize.AddMilliseconds(this._resizeTimer.Interval) < DateTime.Now)) { this._resizeRequired = false; this.ImplementColumnAutoSizingStrategy(); } }; this.Resize += (sender, e) => { this._resizeRequired = true; this._lastResize = DateTime.Now; }; } private void SetIDColumnVisibility(bool visible) { var toHide = new List<DataGridViewColumnWin>(); foreach (DataGridViewColumnWin col in this.Columns) { if (col.Name == "HABANERO_OBJECTID") { toHide.Add(col); } } foreach (var col in toHide) col.Visible = visible; } private void ImplementAlternatRowColoring() { if (!this.EnableAlternateRowColoring) { this.AlternatingRowsDefaultCellStyle = null; } else { var s = new DataGridViewCellStyle(); var bg = SystemColors.Window; var fg = SystemColors.WindowText; s.ForeColor = fg; s.BackColor = Color.FromArgb(this.ApproachColor(fg.R, bg.R), this.ApproachColor(fg.G, bg.G), this.ApproachColor(fg.B, bg.B)); this.AlternatingRowsDefaultCellStyle = s; } } private byte ApproachColor(byte fg, byte bg) { int fore = (int)fg; int back = (int)bg; return (byte)(back + (0.1 * (fore - back))); } protected void ImplementColumnAutoSizingStrategy() { if (this.ColumnAutoSizingStrategy == GridColumnAutoSizingStrategies.None) return; if (this.Columns.Count == 0) return; var grid = this as DataGridView; if (this.ColumnAutoSizingStrategy == GridColumnAutoSizingStrategies.FitEqual) { for (var i = 0; i < grid.Columns.Count; i++) grid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; return; } grid.Columns[grid.Columns.Count-1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; var requiredWidths = this.GetColumnHeaderRequiredWidths(); var columnCount = requiredWidths.Count; if (columnCount == 0) return; this.DetermineRequiredColumnWidths(requiredWidths, columnCount); this.DistributeAvailableColumnWidths(requiredWidths); for (var i = 0; i < (grid.Columns.Count-1); i++) { if (requiredWidths[i] > -1) { grid.Columns[i].Width = requiredWidths[i]; grid.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None; } } this.AutoResizeColumns(); } private List<int> GetColumnHeaderRequiredWidths() { var requiredWidths = new List<int>(); var padding = this.ColumnAutoSizingPadding; using (var gfx = this.CreateGraphics()) { for (var i = 0; i < this.Columns.Count; i++) { if (this.Columns[i].Visible) { var heading = this.Columns[i].HeaderText; var size = gfx.MeasureString(heading, this.Font); requiredWidths.Add((int)(Math.Ceiling(size.Width) + padding)); } else requiredWidths.Add(-1); } } return requiredWidths; } private void DistributeAvailableColumnWidths(List<int> requiredWidths) { var totalRequiredWidth = requiredWidths.Where(w => w > -1).Sum(); var columnCount = requiredWidths.Where(w => w > -1).Count(); if (columnCount < 1) return; if (totalRequiredWidth < this.Width) { var averageAdd = (this.Width - totalRequiredWidth) / columnCount; for (var i = 0; i < columnCount; i++) { if (requiredWidths[i] < 0) continue; requiredWidths[i] += averageAdd; } } } private void DetermineRequiredColumnWidths(List<int> requiredWidths, int columnCount) { var padding = this.ColumnAutoSizingPadding; using (var gfx = this.CreateGraphics()) { foreach (DataGridViewRowWin row in this.Rows) { for (var i = 0; i < columnCount; i++) { if (requiredWidths[i] < 0) continue; var value = (row.Cells[i].Value == null) ? "" : row.Cells[i].Value.ToString(); var size = gfx.MeasureString(value, this.Font); var requiredWidth = size.Width + padding; if (requiredWidth > requiredWidths[i]) requiredWidths[i] = (int) Math.Ceiling((decimal) requiredWidth); } } } } /// <summary> /// Displays a message box to the user to check if they want to proceed with /// deleting the selected rows. /// </summary> /// <returns>Returns true if the user does want to delete</returns> public virtual bool CheckUserWantsToDelete() { return MessageBox.Show (Messages.CheckUserWantsToDelete, Messages.Delete, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == System.Windows.Forms.DialogResult.Yes; } /// <summary> /// Occurs when a business object is selected /// </summary> public event EventHandler<BOEventArgs> BusinessObjectSelected; /// <summary> /// Occurs when the collection in the grid is changed /// </summary> public event EventHandler CollectionChanged; /// <summary> /// Event raised when the filter has been updated. /// </summary> public event EventHandler FilterUpdated; /// <summary> /// Occurs when a row is double-clicked by the user /// </summary> public event RowDoubleClickedHandler RowDoubleClicked; /// <summary> /// Gets and sets the UI definition used to initialise the grid structure (the UI name is indicated /// by the "name" attribute on the UI element in the class definitions /// </summary> public string UiDefName { get { return GridBaseManager.UiDefName; } set { GridBaseManager.UiDefName = value; } } /// <summary> /// Gets and sets the class definition used to initialise the grid structure /// </summary> public IClassDef ClassDef { get { return GridBaseManager.ClassDef; } set { GridBaseManager.ClassDef = value; } } ///<summary> /// Refreshes the row values for the specified <see cref="IBusinessObject"/>. ///</summary> ///<param name="businessObject">The <see cref="IBusinessObject"/> for which the row must be refreshed.</param> public void RefreshBusinessObjectRow(IBusinessObject businessObject) { this._manager.RefreshBusinessObjectRow(businessObject); } /// <summary> /// Handles the event of a double-click /// </summary> /// <param name="sender">The object that notified of the event</param> /// <param name="e">Attached arguments regarding the event</param> private void DoubleClickHandler(object sender, EventArgs e) { try { Point pt = this.PointToClient(Cursor.Position); HitTestInfo hti = this.HitTest(pt.X, pt.Y); if (hti.Type == DataGridViewHitTestType.Cell) { FireRowDoubleClicked(SelectedBusinessObject); } } catch (Exception ex) { GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "Error "); } } /// <summary> /// Creates an event for a row being double-clicked /// </summary> /// <param name="selectedBo">The business object to which the /// double-click applies</param> public void FireRowDoubleClicked(IBusinessObject selectedBo) { if (RowDoubleClicked != null) { RowDoubleClicked(this, new BOEventArgs(selectedBo)); } } /// <summary> /// Returns the grid base manager for this grid, which centralises common /// logic for the different implementations /// </summary> protected GridBaseManager GridBaseManager { get { return _manager; } } /// <summary> /// Creates a dataset provider that is applicable to this grid. For example, a readonly grid would /// return a <see cref="ReadOnlyDataSetProvider"/>, while an editable grid would return an editable one. /// </summary> /// <param name="col">The collection to create the datasetprovider for</param> /// <returns>Returns the data set provider</returns> public abstract IDataSetProvider CreateDataSetProvider(IBusinessObjectCollection col); private void FireBusinessObjectSelected() { if (this.BusinessObjectSelected != null) { this.BusinessObjectSelected(this, new BOEventArgs(this.SelectedBusinessObject)); } } /// <summary> /// Sets the business object collection displayed in the grid. This /// collection must be pre-loaded using the collection's Load() command. /// The default UI definition will be used, that is a 'ui' element /// without a 'name' attribute. /// </summary> /// <param name="col">The collection of business objects to display. This /// collection must be pre-loaded.</param> [Obsolete("Pls use BusinessObjectCollection Property")] public void SetBusinessObjectCollection(IBusinessObjectCollection col) { BusinessObjectCollection = col; } /// <summary> /// Gets and Sets the business object collection displayed in the grid. This /// collection must be pre-loaded using the collection's Load() command or from the /// <see cref="IBusinessObjectLoader"/>. /// The default UI definition will be used, that is a 'ui' element /// without a 'name' attribute. /// </summary> public IBusinessObjectCollection BusinessObjectCollection { get { return GridBaseManager.GetBusinessObjectCollection(); } set { GridBaseManager.SetBusinessObjectCollection(value); } } /// <summary> /// Returns the business object collection being displayed in the grid /// </summary> /// <returns>Returns a business collection</returns> [Obsolete("Pls use BusinessObjectCollection Property")] public IBusinessObjectCollection GetBusinessObjectCollection() { return BusinessObjectCollection; } /// <summary> /// Returns the business object at the specified row number /// </summary> /// <param name="row">The row number in question</param> /// <returns>Returns the busines object at that row, or null /// if none is found</returns> public IBusinessObject GetBusinessObjectAtRow(int row) { return GridBaseManager.GetBusinessObjectAtRow(row); } /// <summary> /// Gets and sets whether this selector autoselects the first item or not when a new collection is set. /// </summary> public bool AutoSelectFirstItem { get { return GridBaseManager.AutoSelectFirstItem; } set { GridBaseManager.AutoSelectFirstItem = value; } } ///<summary> /// Returns the row for the specified <see cref="IBusinessObject"/>. ///</summary> ///<param name="businessObject">The <see cref="IBusinessObject"/> to search for.</param> ///<returns>Returns the row for the specified <see cref="IBusinessObject"/>, /// or null if the <see cref="IBusinessObject"/> is not found in the grid.</returns> public IDataGridViewRow GetBusinessObjectRow(IBusinessObject businessObject) { return GridBaseManager.GetBusinessObjectRow(businessObject); } private void FireCollectionChanged() { if (this.CollectionChanged != null) { this.CollectionChanged(this, EventArgs.Empty); } } /// <summary> /// Clears the business object collection and the rows in the data table /// </summary> public void Clear() { GridBaseManager.Clear(); } /// <summary> /// Gets and sets the currently selected business object in the grid /// </summary> public IBusinessObject SelectedBusinessObject { get { return GridBaseManager.SelectedBusinessObject; } set { GridBaseManager.SelectedBusinessObject = value; FireBusinessObjectSelected(); } } /// <summary> /// Gets a List of currently selected business objects /// </summary> public IList<BusinessObject> SelectedBusinessObjects { get { //DataGridViewRow row = new DataGridViewRow(); //row.DataBoundItem return GridBaseManager.SelectedBusinessObjects; } } #region IGridBase Members /// <summary> /// Gets and sets the delegated grid loader for the grid. /// <br/> /// This allows the user to implememt a custom /// loading strategy. This can be used to load a collection of business objects into a grid with images or buttons /// that implement custom code. (Grids loaded with a custom delegate generally cannot be set up to filter /// (grid filters a dataview based on filter criteria), /// but can be set up to search (a business object collection loaded with criteria). /// For a grid to be filterable the grid must load with a dataview. /// <br/> /// If no grid loader is specified then the default grid loader is employed. This consists of parsing the collection into /// a dataview and setting this as the datasource. /// </summary> public GridLoaderDelegate GridLoader { get { return GridBaseManager.GridLoader; } set { GridBaseManager.GridLoader = value; } } /// <summary> /// Gets the grid's DataSet provider, which loads the collection's /// data into a DataSet suitable for the grid /// </summary> public IDataSetProvider DataSetProvider { get { return GridBaseManager.DataSetProvider; } } ///<summary> /// Returns the name of the column being used for tracking the business object identity. /// If a <see cref="IDataSetProvider"/> is used then it will be the <see cref="IDataSetProvider.IDColumnName"/> /// Else it will be "HABANERO_OBJECTID". ///</summary> public string IDColumnName { get { return GridBaseManager.IDColumnName; } } /* /// <summary> /// Fires an event indicating that the selected business object /// is being edited /// </summary> /// <param name="bo">The business object being edited</param> public void SelectedBusinessObjectEdited(BusinessObject bo) { FireSelectedBusinessObjectEdited(bo); }*/ /* private void FireSelectedBusinessObjectEdited(IBusinessObject bo) { if (this.BusinessObjectEdited != null) { this.BusinessObjectEdited(this, new BOEventArgs(bo)); } }*/ /* /// <summary> /// Fires the Selected Business Object Edited Event for <paramref name="bo"/> /// </summary> /// <param name="bo">The Business object the event is being fired for</param> public void FireBusinessObjectEditedEvent(BusinessObject bo) { FireSelectedBusinessObjectEdited(bo); }*/ /* /// <summary> /// Occurs when a business object is being edited /// </summary> public event EventHandler<BOEventArgs> BusinessObjectEdited;*/ /// <summary> /// Reloads the grid based on the grid returned by GetBusinessObjectCollection /// </summary> public void RefreshGrid() { GridBaseManager.RefreshGrid(); } #endregion /// <summary> /// Applies a filter clause to the data table and updates the filter. /// The filter allows you to determine which objects to display using /// some criteria. This is typically generated by an <see cref="IFilterControl"/>. /// </summary> /// <param name="filterClause">The filter clause</param> public void ApplyFilter(IFilterClause filterClause) { GridBaseManager.ApplyFilter(filterClause); FireFilterUpdated(); } /// <summary> /// Applies a search clause to the underlying collection and reloads the grid. /// The search allows you to determine which objects to display using /// some criteria. This is typically generated by the an <see cref="IFilterControl"/>. /// </summary> /// <param name="searchClause">The search clause</param> /// <param name="orderBy"></param> public void ApplySearch(IFilterClause searchClause, string orderBy) { this.GridBaseManager.ApplySearch(searchClause, orderBy); FireFilterUpdated(); } /// <summary> /// Applies a search clause to the underlying collection and reloads the grid. /// The search allows you to determine which objects to display using /// some criteria. This is typically generated by the an <see cref="IFilterControl"/>. /// </summary> /// <param name="searchClause">The search clause</param> /// <param name="orderBy"></param> public void ApplySearch(string searchClause, string orderBy) { GridBaseManager.ApplySearch(searchClause, orderBy); FireFilterUpdated(); } /// <summary> /// Calls the FilterUpdated() method, passing this instance as the /// sender /// </summary> private void FireFilterUpdated() { if (this.FilterUpdated != null) { this.FilterUpdated(this, new EventArgs()); } } /// <summary>Gets the number of items displayed in the <see cref="IBOColSelector"></see>.</summary> /// <returns>The number of items in the <see cref="IBOColSelector"></see>.</returns> int IBOColSelector.NoOfItems { get { return this.Rows.Count; } } /// <summary> /// Gets or sets the boolean value that determines whether to confirm /// deletion with the user when they have chosen to delete a row /// </summary> public bool ConfirmDeletion { get; set; } /// <summary> /// Gets or sets the delegate that checks whether the user wants to delete selected rows /// </summary> public CheckUserConfirmsDeletion CheckUserConfirmsDeletionDelegate { get; set; } /// <summary> /// Uses the <see cref="ConfirmDeletion"/> and <see cref="CheckUserConfirmsDeletion"/> to determine /// Whether the <see cref="SelectedBusinessObject"/> must be deleted or not. /// </summary> /// <returns></returns> protected bool MustDelete() { return !ConfirmDeletion || (ConfirmDeletion && CheckUserConfirmsDeletionDelegate()); } /// <summary> /// Gets and sets whether the Control is enabled or not /// </summary> bool IBOColSelector.ControlEnabled { get { return this.Enabled; }
[ " set { this.Enabled = value; }" ]
2,288
lcc
csharp
null
17cb34da8ac4cba50c3cd902f4bb130d217b32fbce400737
// created on 10/12/2002 at 20:37 using System; using System.Collections.Generic; using System.Runtime.InteropServices; using xServer.Core.NAudio.Wave.MmeInterop; namespace xServer.Core.NAudio.Mixer { /// <summary> /// Represents a mixer line (source or destination) /// </summary> public class MixerLine { private MixerInterop.MIXERLINE mixerLine; private IntPtr mixerHandle; private MixerFlags mixerHandleType; /// <summary> /// Creates a new mixer destination /// </summary> /// <param name="mixerHandle">Mixer Handle</param> /// <param name="destinationIndex">Destination Index</param> /// <param name="mixerHandleType">Mixer Handle Type</param> public MixerLine(IntPtr mixerHandle, int destinationIndex, MixerFlags mixerHandleType) { this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; mixerLine = new MixerInterop.MIXERLINE(); mixerLine.cbStruct = Marshal.SizeOf(mixerLine); mixerLine.dwDestination = destinationIndex; MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.GetLineInfoOfDestination), "mixerGetLineInfo"); } /// <summary> /// Creates a new Mixer Source For a Specified Source /// </summary> /// <param name="mixerHandle">Mixer Handle</param> /// <param name="destinationIndex">Destination Index</param> /// <param name="sourceIndex">Source Index</param> /// <param name="mixerHandleType">Flag indicating the meaning of mixerHandle</param> public MixerLine(IntPtr mixerHandle, int destinationIndex, int sourceIndex, MixerFlags mixerHandleType) { this.mixerHandle = mixerHandle; this.mixerHandleType = mixerHandleType; mixerLine = new MixerInterop.MIXERLINE(); mixerLine.cbStruct = Marshal.SizeOf(mixerLine); mixerLine.dwDestination = destinationIndex; mixerLine.dwSource = sourceIndex; MmException.Try(MixerInterop.mixerGetLineInfo(mixerHandle, ref mixerLine, mixerHandleType | MixerFlags.GetLineInfoOfSource), "mixerGetLineInfo"); } /// <summary> /// Creates a new Mixer Source /// </summary> /// <param name="waveInDevice">Wave In Device</param> public static int GetMixerIdForWaveIn(int waveInDevice) { int mixerId = -1; MmException.Try(MixerInterop.mixerGetID((IntPtr)waveInDevice, out mixerId, MixerFlags.WaveIn), "mixerGetID"); return mixerId; } /// <summary> /// Mixer Line Name /// </summary> public String Name { get { return mixerLine.szName; } } /// <summary> /// Mixer Line short name /// </summary> public String ShortName { get { return mixerLine.szShortName; } } /// <summary> /// The line ID /// </summary> public int LineId { get { return mixerLine.dwLineID; } } /// <summary> /// Component Type /// </summary> public MixerLineComponentType ComponentType { get { return mixerLine.dwComponentType; } } /// <summary> /// Mixer destination type description /// </summary> public String TypeDescription { get { switch (mixerLine.dwComponentType) { // destinations case MixerLineComponentType.DestinationUndefined: return "Undefined Destination"; case MixerLineComponentType.DestinationDigital: return "Digital Destination"; case MixerLineComponentType.DestinationLine: return "Line Level Destination"; case MixerLineComponentType.DestinationMonitor: return "Monitor Destination"; case MixerLineComponentType.DestinationSpeakers: return "Speakers Destination"; case MixerLineComponentType.DestinationHeadphones: return "Headphones Destination"; case MixerLineComponentType.DestinationTelephone: return "Telephone Destination"; case MixerLineComponentType.DestinationWaveIn: return "Wave Input Destination"; case MixerLineComponentType.DestinationVoiceIn: return "Voice Recognition Destination"; // sources case MixerLineComponentType.SourceUndefined: return "Undefined Source"; case MixerLineComponentType.SourceDigital: return "Digital Source"; case MixerLineComponentType.SourceLine: return "Line Level Source"; case MixerLineComponentType.SourceMicrophone: return "Microphone Source"; case MixerLineComponentType.SourceSynthesizer: return "Synthesizer Source"; case MixerLineComponentType.SourceCompactDisc: return "Compact Disk Source"; case MixerLineComponentType.SourceTelephone: return "Telephone Source"; case MixerLineComponentType.SourcePcSpeaker: return "PC Speaker Source"; case MixerLineComponentType.SourceWaveOut: return "Wave Out Source"; case MixerLineComponentType.SourceAuxiliary: return "Auxiliary Source"; case MixerLineComponentType.SourceAnalog: return "Analog Source"; default: return "Invalid Component Type"; } } } /// <summary> /// Number of channels /// </summary> public int Channels { get { return mixerLine.cChannels; } } /// <summary> /// Number of sources /// </summary> public int SourceCount { get { return mixerLine.cConnections; } } /// <summary> /// Number of controls /// </summary> public int ControlsCount { get { return mixerLine.cControls; } } /// <summary> /// Is this destination active /// </summary> public bool IsActive { get { return (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_ACTIVE) != 0; } } /// <summary> /// Is this destination disconnected /// </summary> public bool IsDisconnected { get { return (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_DISCONNECTED) != 0; } } /// <summary> /// Is this destination a source /// </summary> public bool IsSource { get { return (mixerLine.fdwLine & MixerInterop.MIXERLINE_LINEF.MIXERLINE_LINEF_SOURCE) != 0; } } /// <summary> /// Gets the specified source /// </summary> public MixerLine GetSource(int sourceIndex) { if(sourceIndex < 0 || sourceIndex >= SourceCount) { throw new ArgumentOutOfRangeException("sourceIndex"); } return new MixerLine(mixerHandle, mixerLine.dwDestination, sourceIndex, this.mixerHandleType); } /// <summary> /// Enumerator for the controls on this Mixer Limne /// </summary> public IEnumerable<MixerControl> Controls { get { return MixerControl.GetMixerControls(this.mixerHandle, this, this.mixerHandleType); } } /// <summary> /// Enumerator for the sources on this Mixer Line /// </summary> public IEnumerable<MixerLine> Sources { get { for (int source = 0; source < SourceCount; source++) { yield return GetSource(source); } } } /// <summary> /// The name of the target output device /// </summary> public string TargetName { get { return mixerLine.szPname; } } /// <summary> /// Describes this Mixer Line (for diagnostic purposes) /// </summary> public override string ToString() {
[ " return String.Format(\"{0} {1} ({2} controls, ID={3})\", " ]
672
lcc
csharp
null
102833fe5a636f960b4e9762aced1a6f79de4abd212d5ced
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# 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/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:24 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Bogdan Tofei */ public class EmergencyAttendanceForTimeAmendmentsVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo copy(ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObjectDest, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_EmergencyAttendance(valueObjectSrc.getID_EmergencyAttendance()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // ArrivalDateTime valueObjectDest.setArrivalDateTime(valueObjectSrc.getArrivalDateTime()); // TriageDateTime valueObjectDest.setTriageDateTime(valueObjectSrc.getTriageDateTime()); // AmbulanceArrivalDateTime valueObjectDest.setAmbulanceArrivalDateTime(valueObjectSrc.getAmbulanceArrivalDateTime()); // ConclusionDateTime valueObjectDest.setConclusionDateTime(valueObjectSrc.getConclusionDateTime()); // ExpectedArrivalDateTime valueObjectDest.setExpectedArrivalDateTime(valueObjectSrc.getExpectedArrivalDateTime()); // Outcome valueObjectDest.setOutcome(valueObjectSrc.getOutcome()); // EndOfRegistrationDateTime valueObjectDest.setEndOfRegistrationDateTime(valueObjectSrc.getEndOfRegistrationDateTime()); // RegistrationDateTime valueObjectDest.setRegistrationDateTime(valueObjectSrc.getRegistrationDateTime()); // DischargeDateTime valueObjectDest.setDischargeDateTime(valueObjectSrc.getDischargeDateTime()); // CareContext valueObjectDest.setCareContext(valueObjectSrc.getCareContext()); // customID valueObjectDest.setCustomID(valueObjectSrc.getCustomID()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.admin.domain.objects.EmergencyAttendance objects. */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(java.util.Set domainObjectSet) { return createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.admin.domain.objects.EmergencyAttendance objects. */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection voList = new ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.admin.domain.objects.EmergencyAttendance domainObject = (ims.core.admin.domain.objects.EmergencyAttendance) iterator.next(); ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.admin.domain.objects.EmergencyAttendance objects. */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(java.util.List domainObjectList) { return createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.admin.domain.objects.EmergencyAttendance objects. */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection createEmergencyAttendanceForTimeAmendmentsVoCollectionFromEmergencyAttendance(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection voList = new ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.admin.domain.objects.EmergencyAttendance domainObject = (ims.core.admin.domain.objects.EmergencyAttendance) domainObjectList.get(i); ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.admin.domain.objects.EmergencyAttendance set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractEmergencyAttendanceSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection voCollection) { return extractEmergencyAttendanceSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractEmergencyAttendanceSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo vo = voCollection.get(i); ims.core.admin.domain.objects.EmergencyAttendance domainObject = EmergencyAttendanceForTimeAmendmentsVoAssembler.extractEmergencyAttendance(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.admin.domain.objects.EmergencyAttendance list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractEmergencyAttendanceList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection voCollection) { return extractEmergencyAttendanceList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractEmergencyAttendanceList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo vo = voCollection.get(i); ims.core.admin.domain.objects.EmergencyAttendance domainObject = EmergencyAttendanceForTimeAmendmentsVoAssembler.extractEmergencyAttendance(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.admin.domain.objects.EmergencyAttendance object. * @param domainObject ims.core.admin.domain.objects.EmergencyAttendance */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo create(ims.core.admin.domain.objects.EmergencyAttendance domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.admin.domain.objects.EmergencyAttendance object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo create(DomainObjectMap map, ims.core.admin.domain.objects.EmergencyAttendance domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObject = (ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo) map.getValueObject(domainObject, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.admin.domain.objects.EmergencyAttendance */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo insert(ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObject, ims.core.admin.domain.objects.EmergencyAttendance domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.admin.domain.objects.EmergencyAttendance */ public static ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo insert(DomainObjectMap map, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObject, ims.core.admin.domain.objects.EmergencyAttendance domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_EmergencyAttendance(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // ArrivalDateTime java.util.Date ArrivalDateTime = domainObject.getArrivalDateTime(); if ( null != ArrivalDateTime ) { valueObject.setArrivalDateTime(new ims.framework.utils.DateTime(ArrivalDateTime) ); } // TriageDateTime java.util.Date TriageDateTime = domainObject.getTriageDateTime(); if ( null != TriageDateTime ) { valueObject.setTriageDateTime(new ims.framework.utils.DateTime(TriageDateTime) ); } // AmbulanceArrivalDateTime java.util.Date AmbulanceArrivalDateTime = domainObject.getAmbulanceArrivalDateTime(); if ( null != AmbulanceArrivalDateTime ) { valueObject.setAmbulanceArrivalDateTime(new ims.framework.utils.DateTime(AmbulanceArrivalDateTime) ); } // ConclusionDateTime java.util.Date ConclusionDateTime = domainObject.getConclusionDateTime(); if ( null != ConclusionDateTime ) { valueObject.setConclusionDateTime(new ims.framework.utils.DateTime(ConclusionDateTime) ); } // ExpectedArrivalDateTime java.util.Date ExpectedArrivalDateTime = domainObject.getExpectedArrivalDateTime(); if ( null != ExpectedArrivalDateTime ) { valueObject.setExpectedArrivalDateTime(new ims.framework.utils.DateTime(ExpectedArrivalDateTime) ); } // Outcome ims.domain.lookups.LookupInstance instance6 = domainObject.getOutcome(); if ( null != instance6 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance6.getImage() != null) { img = new ims.framework.utils.ImagePath(instance6.getImage().getImageId(), instance6.getImage().getImagePath()); } color = instance6.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.AttendanceOutcome voLookup6 = new ims.emergency.vo.lookups.AttendanceOutcome(instance6.getId(),instance6.getText(), instance6.isActive(), null, img, color); ims.emergency.vo.lookups.AttendanceOutcome parentVoLookup6 = voLookup6; ims.domain.lookups.LookupInstance parent6 = instance6.getParent(); while (parent6 != null) { if (parent6.getImage() != null) { img = new ims.framework.utils.ImagePath(parent6.getImage().getImageId(), parent6.getImage().getImagePath() ); } else { img = null; } color = parent6.getColor(); if (color != null) color.getValue(); parentVoLookup6.setParent(new ims.emergency.vo.lookups.AttendanceOutcome(parent6.getId(),parent6.getText(), parent6.isActive(), null, img, color)); parentVoLookup6 = parentVoLookup6.getParent(); parent6 = parent6.getParent(); } valueObject.setOutcome(voLookup6); } // EndOfRegistrationDateTime java.util.Date EndOfRegistrationDateTime = domainObject.getEndOfRegistrationDateTime(); if ( null != EndOfRegistrationDateTime ) { valueObject.setEndOfRegistrationDateTime(new ims.framework.utils.DateTime(EndOfRegistrationDateTime) ); } // RegistrationDateTime java.util.Date RegistrationDateTime = domainObject.getRegistrationDateTime(); if ( null != RegistrationDateTime ) { valueObject.setRegistrationDateTime(new ims.framework.utils.DateTime(RegistrationDateTime) ); } // DischargeDateTime java.util.Date DischargeDateTime = domainObject.getDischargeDateTime(); if ( null != DischargeDateTime ) { valueObject.setDischargeDateTime(new ims.framework.utils.DateTime(DischargeDateTime) ); } // CareContext if (domainObject.getCareContext() != null) { if(domainObject.getCareContext() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCareContext(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(id, -1)); } else { valueObject.setCareContext(new ims.core.admin.vo.CareContextRefVo(domainObject.getCareContext().getId(), domainObject.getCareContext().getVersion())); } } // customID valueObject.setCustomID(domainObject.getCustomID()); return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.admin.domain.objects.EmergencyAttendance extractEmergencyAttendance(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObject) { return extractEmergencyAttendance(domainFactory, valueObject, new HashMap()); } public static ims.core.admin.domain.objects.EmergencyAttendance extractEmergencyAttendance(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_EmergencyAttendance(); ims.core.admin.domain.objects.EmergencyAttendance domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.admin.domain.objects.EmergencyAttendance)domMap.get(valueObject); } // ims.emergency.vo.EmergencyAttendanceForTimeAmendmentsVo ID_EmergencyAttendance field is unknown domainObject = new ims.core.admin.domain.objects.EmergencyAttendance(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EmergencyAttendance()); if (domMap.get(key) != null) { return (ims.core.admin.domain.objects.EmergencyAttendance)domMap.get(key); } domainObject = (ims.core.admin.domain.objects.EmergencyAttendance) domainFactory.getDomainObject(ims.core.admin.domain.objects.EmergencyAttendance.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_EmergencyAttendance()); ims.framework.utils.DateTime dateTime1 = valueObject.getArrivalDateTime(); java.util.Date value1 = null; if ( dateTime1 != null ) { value1 = dateTime1.getJavaDate(); } domainObject.setArrivalDateTime(value1); ims.framework.utils.DateTime dateTime2 = valueObject.getTriageDateTime(); java.util.Date value2 = null; if ( dateTime2 != null ) { value2 = dateTime2.getJavaDate(); } domainObject.setTriageDateTime(value2); ims.framework.utils.DateTime dateTime3 = valueObject.getAmbulanceArrivalDateTime(); java.util.Date value3 = null; if ( dateTime3 != null ) { value3 = dateTime3.getJavaDate(); } domainObject.setAmbulanceArrivalDateTime(value3); ims.framework.utils.DateTime dateTime4 = valueObject.getConclusionDateTime(); java.util.Date value4 = null; if ( dateTime4 != null ) { value4 = dateTime4.getJavaDate(); } domainObject.setConclusionDateTime(value4); ims.framework.utils.DateTime dateTime5 = valueObject.getExpectedArrivalDateTime(); java.util.Date value5 = null; if ( dateTime5 != null ) { value5 = dateTime5.getJavaDate(); } domainObject.setExpectedArrivalDateTime(value5); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value6 = null; if ( null != valueObject.getOutcome() ) { value6 = domainFactory.getLookupInstance(valueObject.getOutcome().getID()); } domainObject.setOutcome(value6); ims.framework.utils.DateTime dateTime7 = valueObject.getEndOfRegistrationDateTime(); java.util.Date value7 = null; if ( dateTime7 != null ) { value7 = dateTime7.getJavaDate(); } domainObject.setEndOfRegistrationDateTime(value7); ims.framework.utils.DateTime dateTime8 = valueObject.getRegistrationDateTime(); java.util.Date value8 = null; if ( dateTime8 != null ) { value8 = dateTime8.getJavaDate(); } domainObject.setRegistrationDateTime(value8); ims.framework.utils.DateTime dateTime9 = valueObject.getDischargeDateTime(); java.util.Date value9 = null; if ( dateTime9 != null ) { value9 = dateTime9.getJavaDate(); } domainObject.setDischargeDateTime(value9); ims.core.admin.domain.objects.CareContext value10 = null; if ( null != valueObject.getCareContext() ) {
[ "\t\t\tif (valueObject.getCareContext().getBoId() == null)" ]
1,991
lcc
java
null
25a88155c976a139f0f67418b062d4e28ff8b66c2718bc66
# Copyright 2013 The Servo Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your # option. This file may not be copied, modified, or distributed # except according to those terms. from __future__ import print_function, unicode_literals import os import os.path as path import subprocess import sys from time import time from mach.decorators import ( CommandArgument, CommandProvider, Command, ) from servo.command_base import CommandBase, cd def is_headless_build(): return int(os.getenv('SERVO_HEADLESS', 0)) == 1 def notify_linux(title, text): try: import dbus bus = dbus.SessionBus() notify_obj = bus.get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") method = notify_obj.get_dbus_method("Notify", "org.freedesktop.Notifications") method(title, 0, "", text, "", [], [], -1) except: raise Exception("Please make sure that the Python dbus module is installed!") def notify_win(title, text): from ctypes import Structure, windll, POINTER, sizeof from ctypes.wintypes import DWORD, HANDLE, WINFUNCTYPE, BOOL, UINT class FLASHWINDOW(Structure): _fields_ = [("cbSize", UINT), ("hwnd", HANDLE), ("dwFlags", DWORD), ("uCount", UINT), ("dwTimeout", DWORD)] FlashWindowExProto = WINFUNCTYPE(BOOL, POINTER(FLASHWINDOW)) FlashWindowEx = FlashWindowExProto(("FlashWindowEx", windll.user32)) FLASHW_CAPTION = 0x01 FLASHW_TRAY = 0x02 FLASHW_TIMERNOFG = 0x0C params = FLASHWINDOW(sizeof(FLASHWINDOW), windll.kernel32.GetConsoleWindow(), FLASHW_CAPTION | FLASHW_TRAY | FLASHW_TIMERNOFG, 3, 0) FlashWindowEx(params) def notify_darwin(title, text): try: import Foundation bundleDict = Foundation.NSBundle.mainBundle().infoDictionary() bundleIdentifier = 'CFBundleIdentifier' if bundleIdentifier not in bundleDict: bundleDict[bundleIdentifier] = 'mach' note = Foundation.NSUserNotification.alloc().init() note.setTitle_(title) note.setInformativeText_(text) now = Foundation.NSDate.dateWithTimeInterval_sinceDate_(0, Foundation.NSDate.date()) note.setDeliveryDate_(now) centre = Foundation.NSUserNotificationCenter.defaultUserNotificationCenter() centre.scheduleNotification_(note) except ImportError: raise Exception("Please make sure that the Python pyobjc module is installed!") def notify_build_done(elapsed): """Generate desktop notification when build is complete and the elapsed build time was longer than 30 seconds.""" if elapsed > 30: notify("Servo build", "Completed in %0.2fs" % elapsed) def notify(title, text): """Generate a desktop notification using appropriate means on supported platforms Linux, Windows, and Mac OS. On unsupported platforms, this function acts as a no-op.""" platforms = { "linux": notify_linux, "win": notify_win, "darwin": notify_darwin } func = platforms.get(sys.platform) if func is not None: try: func(title, text) except Exception as e: extra = getattr(e, "message", "") print("[Warning] Could not generate notification! %s" % extra, file=sys.stderr) def call(*args, **kwargs): """Wrap `subprocess.call`, printing the command if verbose=True.""" verbose = kwargs.pop('verbose', False) if verbose: print(' '.join(args[0])) return subprocess.call(*args, **kwargs) @CommandProvider class MachCommands(CommandBase): @Command('build', description='Build Servo', category='build') @CommandArgument('--target', '-t', default=None, help='Cross compile for given target platform') @CommandArgument('--release', '-r', action='store_true', help='Build in release mode') @CommandArgument('--dev', '-d', action='store_true', help='Build in development mode') @CommandArgument('--jobs', '-j', default=None, help='Number of jobs to run in parallel') @CommandArgument('--android', default=None, action='store_true', help='Build for Android') @CommandArgument('--debug-mozjs', default=None, action='store_true', help='Enable debug assertions in mozjs') @CommandArgument('--verbose', '-v', action='store_true', help='Print verbose output') @CommandArgument('params', nargs='...', help="Command-line arguments to be passed through to Cargo") def build(self, target=None, release=False, dev=False, jobs=None, android=None, verbose=False, debug_mozjs=False, params=None): if android is None: android = self.config["build"]["android"] opts = params or [] features = [] base_path = self.get_target_dir() release_path = path.join(base_path, "release", "servo") dev_path = path.join(base_path, "debug", "servo") release_exists = path.exists(release_path) dev_exists = path.exists(dev_path) if not (release or dev): if self.config["build"]["mode"] == "dev": dev = True elif self.config["build"]["mode"] == "release": release = True elif release_exists and not dev_exists: release = True elif dev_exists and not release_exists: dev = True else: print("Please specify either --dev (-d) for a development") print(" build, or --release (-r) for an optimized build.") sys.exit(1) if release and dev: print("Please specify either --dev or --release.") sys.exit(1) self.ensure_bootstrapped() if release: opts += ["--release"] if target: opts += ["--target", target] if jobs is not None: opts += ["-j", jobs] if verbose: opts += ["-v"] if android: # Ensure the APK builder submodule has been built first apk_builder_dir = "support/android-rs-glue" with cd(path.join(apk_builder_dir, "apk-builder")): status = call(["cargo", "build"], env=self.build_env(), verbose=verbose) if status: return status opts += ["--target", "arm-linux-androideabi"] if debug_mozjs or self.config["build"]["debug-mozjs"]: features += ["script/debugmozjs"] if is_headless_build(): opts += ["--no-default-features"] features += ["headless"] if android: features += ["android_glue"] if features: opts += ["--features", "%s" % ' '.join(features)] build_start = time() env = self.build_env() if android: # Build OpenSSL for android make_cmd = ["make"] if jobs is not None: make_cmd += ["-j" + jobs] with cd(self.android_support_dir()): status = call( make_cmd + ["-f", "openssl.makefile"], env=self.build_env(), verbose=verbose) if status: return status openssl_dir = path.join(self.android_support_dir(), "openssl-1.0.1k") env['OPENSSL_LIB_DIR'] = openssl_dir env['OPENSSL_INCLUDE_DIR'] = path.join(openssl_dir, "include") env['OPENSSL_STATIC'] = 'TRUE' status = call(
[ " [\"cargo\", \"build\"] + opts," ]
688
lcc
python
null
ff8f7d496166e1a205f67ca69caa4f63247ff40c16b5e326
/** * Copyright (C) 2001-2020 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.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/. */ package com.rapidminer.operator.learner.rules; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Vector; import com.rapidminer.example.Attribute; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.operator.Model; import com.rapidminer.operator.OperatorCapability; import com.rapidminer.operator.OperatorDescription; import com.rapidminer.operator.OperatorException; import com.rapidminer.operator.learner.AbstractLearner; import com.rapidminer.operator.learner.PredictionModel; import com.rapidminer.parameter.ParameterType; import com.rapidminer.parameter.ParameterTypeBoolean; import com.rapidminer.parameter.ParameterTypeCategory; import com.rapidminer.parameter.ParameterTypeInt; import com.rapidminer.parameter.UndefinedParameterError; /** * This operator returns the best rule regarding WRAcc using exhaustive search. Features like the * incorporation of other metrics and the search for more than a single rule are prepared. * * The search strategy is BFS, with save pruning whenever applicable. This operator can easily be * extended to support other search strategies. * * @author Martin Scholz */ public class BestRuleInduction extends AbstractLearner { /** Helper class containing a rule and an upper bound for the score. */ public static class RuleWithScoreUpperBound implements Comparable<Object> { private final ConjunctiveRuleModel rule; private final double scoreUpperBound; public RuleWithScoreUpperBound(ConjunctiveRuleModel rule, double scoreUpperBound) { this.rule = rule; this.scoreUpperBound = scoreUpperBound; } public ConjunctiveRuleModel getRule() { return this.rule; } public double getScoreBound() { return this.scoreUpperBound; } @Override public int compareTo(Object obj) { if (obj instanceof RuleWithScoreUpperBound) { double otherScore = ((RuleWithScoreUpperBound) obj).getScoreBound(); if (this.getScoreBound() < otherScore) { return -1; } else if (this.getScoreBound() > otherScore) { return 1; } else { return 0; } } else { return this.getClass().getName().compareTo(obj.getClass().getName()); } } @Override public boolean equals(Object o) { if (!(o instanceof RuleWithScoreUpperBound)) { return false; } else { return this.rule.equals(((RuleWithScoreUpperBound) o).rule); } } @Override public int hashCode() { return this.rule.hashCode(); } } private static final String PARAMETER_MAX_DEPTH = "max_depth"; private static final String PARAMETER_UTILITY_FUNCTION = "utility_function"; private static final String PARAMETER_MAX_CACHE = "max_cache"; private static final String PARAMETER_RELATIVE_TO_PREDICTIONS = "relative_to_predictions"; private static final String WRACC = "weighted relative accuracy"; private static final String BINOMIAL = "binomial test function"; private static final String[] UTILITY_FUNCTION_LIST = new String[] { WRACC, BINOMIAL }; private double globalP; private double globalN; protected ConjunctiveRuleModel bestRule; private double bestScore; private int maxDepth; // nodes under consideration private final Vector<RuleWithScoreUpperBound> openNodes = new Vector<RuleWithScoreUpperBound>(); // keep track of rules that have been pruned, to avoid // evaluations for any kind of refinements private final Vector<ConjunctiveRuleModel> prunedNodes = new Vector<ConjunctiveRuleModel>(); public BestRuleInduction(OperatorDescription description) { super(description); } @Override public boolean supportsCapability(OperatorCapability lc) { if (lc == com.rapidminer.operator.OperatorCapability.POLYNOMINAL_ATTRIBUTES) { return true; } if (lc == com.rapidminer.operator.OperatorCapability.BINOMINAL_ATTRIBUTES) { return true; } if (lc == com.rapidminer.operator.OperatorCapability.BINOMINAL_LABEL) { return true; } if (lc == com.rapidminer.operator.OperatorCapability.WEIGHTED_EXAMPLES) { return true; } return false; } protected void initHighscore() { this.bestRule = null; this.bestScore = Double.NEGATIVE_INFINITY; } /** * Adds a rule to the set of best rules if its score is high enough. Currently just a single * rule is stored. Additionally it is checked whether the rule is bad enough to be pruned. * * @return true iff the rule can be pruned */ protected boolean communicateToHighscore(ConjunctiveRuleModel rule, double[] counts) throws UndefinedParameterError { double optimisticScore = this.getOptimisticScore(counts); if (optimisticScore <= this.getPruningScore()) { return true; // indicates pruning } else { double posScore = this.getScore(counts, true); double negScore = this.getScore(counts, false); if (posScore > this.bestScore) { this.bestRule = rule; this.bestScore = posScore; } if (negScore > this.bestScore) { ConjunctiveRuleModel negRule = new ConjunctiveRuleModel(rule, rule.getLabel().getMapping().getNegativeIndex()); this.bestRule = negRule; this.bestScore = negScore; } return false; // no pruning } } /** @return the best rule found */ protected ConjunctiveRuleModel getBestRule() { return this.bestRule; } /** @return the lowest score of the stored best rules for pruning */ protected double getPruningScore() { return this.bestScore; } @Override public Model learn(ExampleSet exampleSet) throws OperatorException { this.initHighscore(); int positiveLabel = exampleSet.getAttributes().getLabel().getMapping().getPositiveIndex(); // int negativeLabel = exampleSet.getLabel().getNegativeIndex(); ConjunctiveRuleModel defaultRule = new ConjunctiveRuleModel(exampleSet, positiveLabel); // ConjunctiveRuleModel negRule = new // ConjunctiveRuleModel(exampleSet.getLabel(), negativeLabel); double[] globalCounts = this.getCounts(defaultRule, exampleSet); this.globalP = globalCounts[0]; this.globalN = globalCounts[1]; this.communicateToHighscore(defaultRule, globalCounts); double optimisticScore = this.getOptimisticScore(globalCounts); this.openNodes.clear(); this.prunedNodes.clear(); this.addRulesToOpenNodes(defaultRule.getAllRefinedRules(exampleSet), optimisticScore); int length = 1; maxDepth = this.getParameterAsInt(PARAMETER_MAX_DEPTH); int maxCache = this.getParameterAsInt(PARAMETER_MAX_CACHE); while (!this.openNodes.isEmpty() && length <= maxDepth) { int ignored = 0; log("Evaluating " + this.openNodes.size() + " rules of length " + length); if (this.openNodes.size() > maxCache) { log("Ignoring all but the " + maxCache + " rules with highest support."); } RuleWithScoreUpperBound[] ruleArray = new RuleWithScoreUpperBound[this.openNodes.size()]; this.openNodes.toArray(ruleArray); Arrays.sort(ruleArray); int stopAtIndex = Math.max(0, ruleArray.length - maxCache); this.openNodes.clear(); for (int i = ruleArray.length - 1; i >= stopAtIndex; i--) { RuleWithScoreUpperBound rulePlusScore = ruleArray[i]; ConjunctiveRuleModel rule = rulePlusScore.getRule(); if (this.isRefinementOfPrunedRule(rule)) { ignored++; } else if (rulePlusScore.getScoreBound() <= this.getPruningScore()) { ignored++; // This pruning could not be derived from prunedNodes and // may be useful // later on for refined rules with a less precise optimistic // estimate. this.prunedNodes.add(rulePlusScore.getRule()); } else { this.expandNode(rule, exampleSet); } checkForStop(); } log("Could ignore " + ignored + " rules as refinements of pruned rules or by optimistic estimates."); log("Number of pruned rules in cache: " + this.prunedNodes.size()); log("Best rule is " + this.getBestRule().toString()); log("Score is " + this.getPruningScore()); length++; } this.openNodes.clear(); this.prunedNodes.clear(); return this.getBestRule(); } /** * Annotates the collection of ConjunctiveRuleModels with an optimistic score they may achieve * in the best case and adds them to the collection of open nodes. */ private void addRulesToOpenNodes(Collection<ConjunctiveRuleModel> rules, double scoreUpperBound) { if (scoreUpperBound <= this.getPruningScore()) { return; } for (ConjunctiveRuleModel rule : rules) { this.openNodes.add(new RuleWithScoreUpperBound(rule, scoreUpperBound)); } } /** * Evaluates a single rule by computing its score, and the best possible score after refining * this rule. If this cannot improve over the currently best rules, then the refinements are * pruned. Otherwise all refinements plus optimistic estimates are added to the collection of * open nodes. * * If the evaluated rule is good enough, then it is stored toghether with its score. */ private void expandNode(ConjunctiveRuleModel rule, ExampleSet exampleSet) throws OperatorException { // Compute counts: double[] counts = this.getCounts(rule, exampleSet); // Store in highscore if necessary and check whether it may be pruned. boolean pruning = this.communicateToHighscore(rule, counts); if (pruning == true) { this.prunedNodes.add(rule); // Nothing to add to the collection of open nodes .. } else if (rule.getRuleLength() < maxDepth) { // Store all the refinements for later investigation: this.addRulesToOpenNodes(rule.getAllRefinedRules(exampleSet), this.getOptimisticScore(counts)); } } /** * @param rule * a ConjuctiveRuleModel for which it is checked whether a more general rule has * already been pruned. * @return true, if this rule is a refinement of a pruned rule. The rules are compared using the * method <code>ConjunctiveRuleModel.isRefinementOf(ConjunctiveRuleModel model)</code> */ public boolean isRefinementOfPrunedRule(ConjunctiveRuleModel rule) { for (ConjunctiveRuleModel prunedRule : prunedNodes) { // In this collection all rules predict positive, but the scores are // computed for the best label. For this reason the following // refinement test is valid. if (rule.isRefinementOf(prunedRule)) { return true; } } return false; } /** * Computes the WRAcc or BINOMIAL TEST FUNCTION based on p, n, and the global values P and N * stored in this object. First two entries of counts are p and n, optionally estimates for p * and n can be supplied as further parameters. */ protected double getScore(double[] counts, boolean predictPositives) throws UndefinedParameterError { double p = counts[0]; double n = counts[1]; double cov = (p + n) / (globalP + globalN); double pnRel = predictPositives ? p : n; String function = UTILITY_FUNCTION_LIST[this.getParameterAsInt(PARAMETER_UTILITY_FUNCTION)]; UndefinedParameterError upe = new UndefinedParameterError(PARAMETER_UTILITY_FUNCTION, this); double score; if (this.getParameterAsBoolean(PARAMETER_RELATIVE_TO_PREDICTIONS) == false || counts.length != 4) { double pnAbs = predictPositives ? globalP : globalN; if (function.equals(WRACC)) { score = cov * (pnRel / (p + n) - pnAbs / (globalP + globalN)); } else if (function.equals(BINOMIAL)) { score = Math.sqrt(cov) * (pnRel / (p + n) - pnAbs / (globalP + globalN)); } else { throw upe; } } else { double estP = counts[2]; double estN = counts[3]; double pnEst = predictPositives ? estP : estN; if (function.equals(WRACC)) { score = cov * (pnRel / (p + n) - pnEst / (estP + estN)); } else if (function.equals(BINOMIAL)) { score = Math.sqrt(cov) * (pnRel / (p + n) - pnEst / (estP + estN)); } else { throw upe; } } return score; } /** * Computes the best possible score that might be achieved by refining the rule. During learning * the conclusion is normalized to "positive", so the better of the estimates of the better * conclusion is returned. */ protected double getOptimisticScore(double[] counts) throws UndefinedParameterError { double p = counts[0]; double n = counts[1]; if (this.getParameterAsBoolean(PARAMETER_RELATIVE_TO_PREDICTIONS) == false || counts.length != 4) { // For reasonable utility functions adding just negatives decreases // the score. return Math.max(this.getScore(new double[] { p, 0 }, true), this.getScore(new double[] { 0, n }, false)); } else { // Improvement for positive rules: discard all negatives, which are // at the same time considered to be positives with confidence of 1 // by the given prediction. As a complex second step discarding // further // positives might help to improve the score, since this allows to // lower the estimated precision term. // To keep things simple a non-tight optimistic score is computed: // 1. Keep all positives, discard all negatives: p'=p, n'=0 // 2. Lower the estimated confidence to 0, simply estP' = 0, estN' = // 0. // Analogously for the negatively predicting rule. double estP = counts[2];
[ "\t\t\tdouble estN = counts[3];" ]
1,642
lcc
java
null
2248a8f904da25fd9ea3437cf9c3da1e73876f14aa5dfa87
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Management; using System.Text; using System.Windows.Forms; using GitCommands; using GitCommands.Git; using GitCommands.Patches; using GitExtUtils.GitUI; using GitUIPluginInterfaces; using Microsoft.WindowsAPICodePack.Dialogs; using ResourceManager; namespace GitUI.CommandsDialogs { public sealed partial class FormStash : GitModuleForm { private readonly TranslationString _currentWorkingDirChanges = new("Current working directory changes"); private readonly TranslationString _noStashes = new("There are no stashes."); private readonly TranslationString _stashUntrackedFilesNotSupportedCaption = new("Stash untracked files"); private readonly TranslationString _stashUntrackedFilesNotSupported = new("Stash untracked files is not supported in the version of msysgit you are using. Please update msysgit to at least version 1.7.7 to use this option."); private readonly TranslationString _stashDropConfirmTitle = new("Drop Stash Confirmation"); private readonly TranslationString _cannotBeUndone = new("This action cannot be undone."); private readonly TranslationString _areYouSure = new("Are you sure you want to drop the stash? This action cannot be undone."); private readonly TranslationString _dontShowAgain = new("Don't show me this message again."); private readonly AsyncLoader _asyncLoader = new(); public bool ManageStashes { get; set; } private GitStash _currentWorkingDirStashItem; [Obsolete("For VS designer and translation test only. Do not remove.")] private FormStash() { InitializeComponent(); CompleteTheInitialization(); } public FormStash(GitUICommands commands) : base(commands) { InitializeComponent(); View.ExtraDiffArgumentsChanged += delegate { StashedSelectedIndexChanged(null, null); }; View.TopScrollReached += FileViewer_TopScrollReached; View.BottomScrollReached += FileViewer_BottomScrollReached; CompleteTheInitialization(); } private void CompleteTheInitialization() { KeyPreview = true; View.EscapePressed += () => DialogResult = DialogResult.Cancel; splitContainer1.SplitterDistance = DpiUtil.Scale(280); InitializeComplete(); } protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.Escape && e.Modifiers == Keys.None) { var focusedControl = this.FindFocusedControl(); var comboBox = focusedControl as ComboBox; if (comboBox is not null && comboBox.DroppedDown) { comboBox.DroppedDown = false; } else { var textBox = focusedControl as TextBoxBase; if (textBox is not null && textBox.SelectionLength > 0) { textBox.SelectionLength = 0; } else { DialogResult = DialogResult.Cancel; } } // do not let the modal form react itself on this preview of the Escape key press e.SuppressKeyPress = true; e.Handled = true; } base.OnKeyDown(e); } protected override void OnKeyUp(KeyEventArgs e) { if (e.KeyCode == Keys.Escape && e.Modifiers == Keys.None) { // do not let the modal form react itself on this preview of the Escape key press e.SuppressKeyPress = true; e.Handled = true; } base.OnKeyUp(e); } private void FormStashFormClosing(object sender, FormClosingEventArgs e) { AppSettings.StashKeepIndex = StashKeepIndex.Checked; AppSettings.IncludeUntrackedFilesInManualStash = chkIncludeUntrackedFiles.Checked; } private void FormStashLoad(object sender, EventArgs e) { StashKeepIndex.Checked = AppSettings.StashKeepIndex; chkIncludeUntrackedFiles.Checked = AppSettings.IncludeUntrackedFilesInManualStash; ResizeStashesWidth(); } private void Initialize() { var stashedItems = Module.GetStashes().ToList(); _currentWorkingDirStashItem = new GitStash(-1, _currentWorkingDirChanges.Text); stashedItems.Insert(0, _currentWorkingDirStashItem); Stashes.Text = ""; StashMessage.Text = ""; Stashes.SelectedItem = null; Stashes.ComboBox.DisplayMember = nameof(GitStash.Message); Stashes.Items.Clear(); foreach (GitStash stashedItem in stashedItems) { Stashes.Items.Add(stashedItem); } if (ManageStashes && Stashes.Items.Count > 1) { // more than just the default ("Current working directory changes") Stashes.SelectedIndex = 1; // -> auto-select first non-default } else if (Stashes.Items.Count > 0) { // (no stashes) -> select default ("Current working directory changes") Stashes.SelectedIndex = 0; } } private void InitializeSoft() { GitStash gitStash = Stashes.SelectedItem as GitStash; Stashed.GroupByRevision = false; Stashed.ClearDiffs(); Loading.Visible = true; Loading.IsAnimating = true; Stashes.Enabled = false; refreshToolStripButton.Enabled = false; toolStripButton_customMessage.Enabled = false; if (gitStash == _currentWorkingDirStashItem) { toolStripButton_customMessage.Enabled = true; _asyncLoader.LoadAsync(() => Module.GetAllChangedFiles(), LoadGitItemStatuses); Clear.Enabled = false; // disallow Drop (of current working directory) Apply.Enabled = false; // disallow Apply (of current working directory) } else if (gitStash is not null) { _asyncLoader.LoadAsync(() => Module.GetStashDiffFiles(gitStash.Name), LoadGitItemStatuses); Clear.Enabled = true; // allow Drop Apply.Enabled = true; // allow Apply } } private void FileViewer_TopScrollReached(object sender, EventArgs e) { Stashed.SelectPreviousVisibleItem(); View.ScrollToBottom(); } private void FileViewer_BottomScrollReached(object sender, EventArgs e) { Stashed.SelectNextVisibleItem(); View.ScrollToTop(); } private void LoadGitItemStatuses(IReadOnlyList<GitItemStatus> gitItemStatuses) { GitStash gitStash = Stashes.SelectedItem as GitStash; if (gitStash == _currentWorkingDirStashItem) { // FileStatusList has no interface for both worktree<-index, index<-HEAD at the same time // Must be handled when displaying var headId = Module.RevParse("HEAD"); var headRev = new GitRevision(headId); var indexRev = new GitRevision(ObjectId.IndexId) { ParentIds = new[] { headId } }; var workTreeRev = new GitRevision(ObjectId.WorkTreeId) { ParentIds = new[] { ObjectId.IndexId } }; var indexItems = gitItemStatuses.Where(item => item.Staged == StagedStatus.Index).ToList(); var workTreeItems = gitItemStatuses.Where(item => item.Staged != StagedStatus.Index).ToList(); Stashed.SetStashDiffs(headRev, indexRev, ResourceManager.Strings.Index, indexItems, workTreeRev, ResourceManager.Strings.Workspace, workTreeItems); } else {
[ " var firstId = Module.RevParse(gitStash.Name + \"^\");" ]
671
lcc
csharp
null
f54df722d8cb6050f8b9b79929415e488a47e64578808ae4
import cobjects from cobjects import CBuffer, CObject import sixtracklib as st from sixtracklib.stcommon import st_ARCH_BEAM_ELEMENTS_BUFFER_ID, \ st_NullAssignAddressItem, st_AssignAddressItem_p, \ st_buffer_size_t, st_object_type_id_t, st_arch_status_t, st_arch_size_t, \ st_ARCH_STATUS_SUCCESS, st_ARCH_ILLEGAL_BUFFER_ID, \ st_AssignAddressItem_are_equal, st_AssignAddressItem_are_not_equal, \ st_AssignAddressItem_compare_less import sixtracklib_test as testlib from sixtracklib_test.stcommon import st_AssignAddressItem_print_out if __name__ == '__main__': lattice = st.Elements() lattice.Drift(length=0.0) lattice.Drift(length=0.1) lattice.Drift(length=0.2) bm0_index = lattice.cbuffer.n_objects lattice.BeamMonitor() lattice.Drift(length=0.3) lattice.Drift(length=0.4) lattice.Drift(length=0.5) bm1_index = lattice.cbuffer.n_objects lattice.BeamMonitor() lattice.Drift(length=0.3) lattice.Drift(length=0.4) lattice.Drift(length=0.5) bm2_index = lattice.cbuffer.n_objects lattice.BeamMonitor() assert lattice.cbuffer.get_object(bm0_index).out_address == 0 assert lattice.cbuffer.get_object(bm1_index).out_address == 0 assert lattice.cbuffer.get_object(bm2_index).out_address == 0 pset = st.ParticlesSet() pset.Particles(num_particles=100) output_buffer = st.ParticlesSet() out_buffer0_index = output_buffer.cbuffer.n_objects output_buffer.Particles(num_particles=100) out_buffer1_index = output_buffer.cbuffer.n_objects output_buffer.Particles(num_particles=512) job = st.CudaTrackJob(lattice, pset) # hand the output_buffer over to the track job: output_buffer_id = job.add_stored_buffer(cbuffer=output_buffer) assert output_buffer_id != st_ARCH_ILLEGAL_BUFFER_ID.value # use the predefined lattice_buffer_id value to refer to the # beam elements buffer lattice_buffer_id = st_ARCH_BEAM_ELEMENTS_BUFFER_ID.value # use the _type_id attributes of beam monitors and particle sets to # refer to these object types: particle_set_type_id = output_buffer.cbuffer.get_object( out_buffer0_index)._typeid beam_monitor_type_id = lattice.cbuffer.get_object(bm0_index)._typeid assert job.total_num_assign_items == 0 assert not job.has_assign_items(lattice_buffer_id, output_buffer_id) assert job.num_assign_items(lattice_buffer_id, output_buffer_id) == 0 # -------------------------------------------------------------------------- # Create the assignment item for out_buffer0 -> bm0 out0_to_bm0_addr_assign_item = st.AssignAddressItem( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm0_index, dest_pointer_offset=24, # Magic number, offset of out_address from begin src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer0_index, src_pointer_offset=0 # We assign the starting address of the particle set ) assert out0_to_bm0_addr_assign_item.dest_elem_type_id == \ beam_monitor_type_id assert out0_to_bm0_addr_assign_item.dest_buffer_id == lattice_buffer_id assert out0_to_bm0_addr_assign_item.dest_elem_index == bm0_index assert out0_to_bm0_addr_assign_item.dest_pointer_offset == 24 assert out0_to_bm0_addr_assign_item.src_elem_type_id == \ particle_set_type_id assert out0_to_bm0_addr_assign_item.src_buffer_id == output_buffer_id assert out0_to_bm0_addr_assign_item.src_elem_index == out_buffer0_index assert out0_to_bm0_addr_assign_item.src_pointer_offset == 0 # perform the assignment of assign_out0_to_bm0_item ptr_item_0_to_0 = job.add_assign_address_item( out0_to_bm0_addr_assign_item) assert ptr_item_0_to_0 != st_NullAssignAddressItem assert job.total_num_assign_items == 1 assert job.has_assign_items(lattice_buffer_id, output_buffer_id) assert job.num_assign_items(lattice_buffer_id, output_buffer_id) == 1 assert job.has_assign_item(item=ptr_item_0_to_0) assert job.has_assign_item(item=out0_to_bm0_addr_assign_item) assert job.has_assign_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm0_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer0_index, src_pointer_offset=0) assert not job.has_assign_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm1_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer1_index, src_pointer_offset=0) assert not job.has_assign_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm2_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer0_index, src_pointer_offset=0) item_0_to_0_index = job.index_of_assign_address_item(item=ptr_item_0_to_0) assert not(item_0_to_0_index is None) # -------------------------------------------------------------------------- # Create the assignment item for out_buffer1 -> bm1 at the time of # passing it on to the track job: ptr_item_1_to_1 = job.add_assign_address_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm1_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer1_index, src_pointer_offset=0) assert ptr_item_1_to_1 != st_NullAssignAddressItem assert job.total_num_assign_items == 2 assert job.has_assign_items(lattice_buffer_id, output_buffer_id) assert job.num_assign_items(lattice_buffer_id, output_buffer_id) == 2 assert job.has_assign_item(item=ptr_item_1_to_1) assert not job.has_assign_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm2_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer0_index, src_pointer_offset=0) item_1_to_1_index = job.index_of_assign_address_item(ptr_item_1_to_1) assert not(item_1_to_1_index is None) # Create the assignment item for out_buffer0 -> bm2 # Create a copy of out0_to_bm0_addr_assign_item on the same buffer # TODO: figure out a better way to do this? out0_to_bm2_addr_assign_item = st.AssignAddressItem( **{k != '_buffer' and k or 'cbuffer': getattr(out0_to_bm0_addr_assign_item, k) for k in [*[f[0] for f in st.AssignAddressItem.get_fields()], '_buffer']}) # out0_to_bm2_addr_assign_item is actually the same as # out0_to_bm0_addr_assign_item -> if we try to add this item unmodified, # we should again effectively get ptr_item0_to_0: ptr_item_0_to_2 = job.add_assign_address_item( out0_to_bm2_addr_assign_item) assert ptr_item_0_to_2 != st_NullAssignAddressItem assert st_AssignAddressItem_are_equal( ptr_item_0_to_2, job.ptr_assign_address_item( dest_buffer_id=lattice_buffer_id, src_buffer_id=output_buffer_id, index=item_0_to_0_index)) assert job.total_num_assign_items == 2 assert job.has_assign_items(lattice_buffer_id, output_buffer_id) assert job.num_assign_items(lattice_buffer_id, output_buffer_id) == 2 assert job.has_assign_item(item=ptr_item_0_to_2) assert not job.has_assign_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm2_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_pointer_offset=0) # modify out0_to_bm2_addr_assign_item to target the third beam monitor # located at bm2_index: out0_to_bm2_addr_assign_item.dest_elem_index = bm2_index # try again to add -> this time it should result in a new item: ptr_item_0_to_2 = job.add_assign_address_item( out0_to_bm2_addr_assign_item) assert ptr_item_0_to_2 != st_NullAssignAddressItem assert st_AssignAddressItem_are_not_equal( ptr_item_0_to_2, job.ptr_assign_address_item( dest_buffer_id=lattice_buffer_id, src_buffer_id=output_buffer_id, index=item_0_to_0_index)) assert job.total_num_assign_items == 3 assert job.has_assign_items(lattice_buffer_id, output_buffer_id) assert job.num_assign_items(lattice_buffer_id, output_buffer_id) == 3 assert job.has_assign_item(item=out0_to_bm2_addr_assign_item) assert job.has_assign_item(item=ptr_item_0_to_2) assert job.has_assign_item( dest_elem_type_id=beam_monitor_type_id, dest_buffer_id=lattice_buffer_id, dest_elem_index=bm2_index, dest_pointer_offset=24, src_elem_type_id=particle_set_type_id, src_buffer_id=output_buffer_id, src_elem_index=out_buffer0_index, src_pointer_offset=0) # -------------------------------------------------------------------------- # finish assembly of assign items: job.commit_address_assignments() # perform assignment of address items: job.assign_all_addresses() job.collect_beam_elements() assert lattice.cbuffer.get_object(bm0_index).out_address != 0
[ " assert lattice.cbuffer.get_object(bm1_index).out_address != 0" ]
594
lcc
python
null
0c30966965780fab171d0c89cad81d1c373553c851c2aba7
/* * ==================================================================== * 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package ch.boye.httpclientandroidlib.auth; import java.util.Locale; import ch.boye.httpclientandroidlib.HttpHost; import ch.boye.httpclientandroidlib.annotation.Immutable; import ch.boye.httpclientandroidlib.util.Args; import ch.boye.httpclientandroidlib.util.LangUtils; /** * The class represents an authentication scope consisting of a host name, * a port number, a realm name and an authentication scheme name which * {@link Credentials Credentials} apply to. * * * @since 4.0 */ @Immutable public class AuthScope { /** * The <tt>null</tt> value represents any host. In the future versions of * HttpClient the use of this parameter will be discontinued. */ public static final String ANY_HOST = null; /** * The <tt>-1</tt> value represents any port. */ public static final int ANY_PORT = -1; /** * The <tt>null</tt> value represents any realm. */ public static final String ANY_REALM = null; /** * The <tt>null</tt> value represents any authentication scheme. */ public static final String ANY_SCHEME = null; /** * Default scope matching any host, port, realm and authentication scheme. * In the future versions of HttpClient the use of this parameter will be * discontinued. */ public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME); /** The authentication scheme the credentials apply to. */ private final String scheme; /** The realm the credentials apply to. */ private final String realm; /** The host the credentials apply to. */ private final String host; /** The port the credentials apply to. */ private final int port; /** Creates a new credentials scope for the given * <tt>host</tt>, <tt>port</tt>, <tt>realm</tt>, and * <tt>authentication scheme</tt>. * * @param host the host the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credentials are applicable to * any port. * @param realm the realm the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any realm. * @param scheme the authentication scheme the credentials apply to. * May be set to <tt>null</tt> if credentials are applicable to * any authentication scheme. */ public AuthScope(final String host, final int port, final String realm, final String scheme) { this.host = (host == null) ? ANY_HOST: host.toLowerCase(Locale.ENGLISH); this.port = (port < 0) ? ANY_PORT: port; this.realm = (realm == null) ? ANY_REALM: realm; this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase(Locale.ENGLISH); } /** * @since 4.2 */ public AuthScope(final HttpHost host, final String realm, final String schemeName) { this(host.getHostName(), host.getPort(), realm, schemeName); } /** * @since 4.2 */ public AuthScope(final HttpHost host) { this(host, ANY_REALM, ANY_SCHEME); } /** Creates a new credentials scope for the given * <tt>host</tt>, <tt>port</tt>, <tt>realm</tt>, and any * authentication scheme. * * @param host the host the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credentials are applicable to * any port. * @param realm the realm the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any realm. */ public AuthScope(final String host, final int port, final String realm) { this(host, port, realm, ANY_SCHEME); } /** Creates a new credentials scope for the given * <tt>host</tt>, <tt>port</tt>, any realm name, and any * authentication scheme. * * @param host the host the credentials apply to. May be set * to <tt>null</tt> if credentials are applicable to * any host. * @param port the port the credentials apply to. May be set * to negative value if credentials are applicable to * any port. */ public AuthScope(final String host, final int port) { this(host, port, ANY_REALM, ANY_SCHEME); } /** * Creates a copy of the given credentials scope. */ public AuthScope(final AuthScope authscope) { super(); Args.notNull(authscope, "Scope"); this.host = authscope.getHost(); this.port = authscope.getPort(); this.realm = authscope.getRealm(); this.scheme = authscope.getScheme(); } /** * @return the host */ public String getHost() { return this.host; } /** * @return the port */ public int getPort() { return this.port; } /** * @return the realm name */ public String getRealm() { return this.realm; } /** * @return the scheme type */ public String getScheme() { return this.scheme; } /** * Tests if the authentication scopes match. * * @return the match factor. Negative value signifies no match. * Non-negative signifies a match. The greater the returned value * the closer the match. */ public int match(final AuthScope that) { int factor = 0; if (LangUtils.equals(this.scheme, that.scheme)) { factor += 1; } else { if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) { return -1; } } if (LangUtils.equals(this.realm, that.realm)) { factor += 2; } else { if (this.realm != ANY_REALM && that.realm != ANY_REALM) { return -1; } } if (this.port == that.port) { factor += 4; } else { if (this.port != ANY_PORT && that.port != ANY_PORT) { return -1; } } if (LangUtils.equals(this.host, that.host)) { factor += 8; } else { if (this.host != ANY_HOST && that.host != ANY_HOST) { return -1; } } return factor; } /** * @see java.lang.Object#equals(Object) */ @Override public boolean equals(final Object o) { if (o == null) { return false; }
[ " if (o == this) {" ]
1,028
lcc
java
null
2a2a9209a97ca8cd4029fb006e641c88c4b4df72c457a731
// // This file is part of the OpenLink Software Virtuoso Open-Source (VOS) // project. // // Copyright (C) 1998-2012 OpenLink Software // // This project 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; only version 2 of the License, 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. // // 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 St, Fifth Floor, Boston, MA 02110-1301 USA // // using System; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Security.Cryptography; using System.Text; using Microsoft.Web.Services; using Microsoft.Web.Services.Security; using Microsoft.Web.Services.Security.Tokens; using Microsoft.Web.Services.Security.X509; using System.Runtime.InteropServices; using System.Diagnostics; using System.Xml.Serialization; using System.Web.Services.Protocols; using System.Web.Services; namespace OpenLink.Virtuoso.WSS.AsymmetricEncryption { /// <summary> /// This is a sample which allows the user to send /// a message encrypted with an RSA and tripple-des keys. /// </summary> public class AddClient { int a, b; string url; AddClient(string[] args) { Hashtable arguments = null; ParseArguments(args, ref arguments); if (arguments.Contains("?")) { Usage(); } try { ConvertArgument(arguments, "a", ref a); ConvertArgument(arguments, "b", ref b); url = (string) arguments["url"]; } catch (Exception) { Usage(); throw; } } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { AddClient client = null; try { client = new AddClient(args); } catch (Exception) { Console.WriteLine("\nOne or more of the required arguments are missing or incorrectly formed."); return; } try { client.Run(); } catch (Exception ex) { Error(ex); return; } } void Run() { CallWebService(a, b, url); } void Usage() { Console.WriteLine("Usage: AsymmetricEncryptionClient /a number /b number"); Console.WriteLine(" Required arguments:"); Console.WriteLine(" /url The Secure service endpoint"); Console.WriteLine(" /" + "a".PadRight(20) + "An integer. First number to add."); Console.WriteLine(" /" + "b".PadRight(20) + "An integer. Second number to add."); } protected void ConvertArgument(Hashtable args, string argName, ref int arg) { if (!args.Contains(argName)) { throw new ArgumentException(argName); } arg = int.Parse(args[argName] as string); } protected void ConvertArgument(Hashtable args, string argName, ref long arg) { if (!args.Contains(argName)) { throw new ArgumentException(argName); } arg = long.Parse(args[argName] as string); } protected void ConvertArgument(Hashtable args, string argName, ref bool arg) { if (!args.Contains(argName)) { throw new ArgumentException(argName); } arg = bool.Parse(args[argName] as string); } protected string GetOption(string arg) { if (!arg.StartsWith("/") && !arg.StartsWith("-")) return null; return arg.Substring(1); } protected void ParseArguments(string[] args, ref Hashtable table) { table = new Hashtable(); int index = 0; while (index < args.Length) { string option = GetOption(args[index]); if (option != null) { if (index+1 < args.Length && GetOption(args[index+1]) == null) { table[option] = args[++index]; } else { table[option] = "true"; } } index++; } } protected static void Error(Exception e) { StringBuilder sb = new StringBuilder(); if (e is System.Web.Services.Protocols.SoapException) { System.Web.Services.Protocols.SoapException se = e as System.Web.Services.Protocols.SoapException; sb.Append("SOAP-Fault code: " + se.Code.ToString()); sb.Append("\n"); } if (e != null) { sb.Append(e.ToString()); } Console.WriteLine("*** Exception Raised ***"); Console.WriteLine(sb.ToString()); Console.WriteLine("************************"); } private void CallWebService(int a, int b, string url) { // Instantiate an instance of the web service proxy AddNumbers serviceProxy = new AddNumbers(); SoapContext requestContext = serviceProxy.RequestSoapContext; // Get the Asymmetric key X509SecurityToken token = GetEncryptionToken(); if (token == null) throw new ApplicationException("No security token provided."); // Add an EncryptedData element to the security collection // to encrypt the request. requestContext.Security.Elements.Add(new EncryptedData(token)); if (url != null) serviceProxy.Url = url; // Call the service Console.WriteLine("Calling {0}", serviceProxy.Url); int sum = serviceProxy.AddInt(a, b); // Success! string message = string.Format("{0} + {1} = {2}", a, b, sum); Console.WriteLine("Web Service returned: {0}", message); } /// <summary> /// Returns the X.509 SecurityToken that will be used to encrypt the /// messages. /// </summary> /// <returns>Returns </returns> public X509SecurityToken GetEncryptionToken() { X509SecurityToken token = null; // // The certificate for the target receiver should have been imported // into the "My" certificate store. This store is listed as "Personal" // in the Certificate Manager // X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore); bool open = store.OpenRead(); try { // // Open a dialog to allow user to select the certificate to use // StoreDialog dialog = new StoreDialog(store); X509Certificate cert = dialog.SelectCertificate(IntPtr.Zero, "Select Certificate", "Choose a Certificate below for encrypting."); if (cert == null) { throw new ApplicationException("You chose not to select an X509 certificate for encrypting your messages."); } else if (!cert.SupportsDataEncryption) { throw new ApplicationException("The certificate must support key encipherment."); } else { token = new X509SecurityToken(cert); } } finally { if (store != null) { store.Close(); } } return token; } } class StoreDialog { X509CertificateStore store; public StoreDialog(X509CertificateStore store) { this.store = store; } static bool IsWinXP() { OperatingSystem os = Environment.OSVersion; Version v = os.Version; if (os.Platform == PlatformID.Win32NT && v.Major >= 5 && v.Minor >= 1) { return true; } return false; } /// <summary> /// Displays a dialog that can be used to select a certificate from the store. /// </summary> public X509Certificate SelectCertificate(IntPtr hwnd, string title, string displayString) { if (store.Handle == IntPtr.Zero) throw new InvalidOperationException("Store is not open"); if (IsWinXP()) { IntPtr certPtr = CryptUIDlgSelectCertificateFromStore(store.Handle, hwnd, title, displayString, 0/*dontUseColumn*/, 0 /*flags*/, IntPtr.Zero); if (certPtr != IntPtr.Zero) { return new X509Certificate(certPtr); } } else { SelectCertificateDialog dlg = new SelectCertificateDialog(store); if (dlg.ShowDialog() != DialogResult.OK) { return null; } else { return dlg.Certificate; } } return null; } [DllImport("cryptui", CharSet=CharSet.Unicode, SetLastError=true)] internal extern static IntPtr CryptUIDlgSelectCertificateFromStore(IntPtr hCertStore, IntPtr hwnd, string pwszTitle, string pwszDisplayString, uint dwDontUseColumn, uint dwFlags, IntPtr pvReserved); } /// <summary> /// SelectCertificateDialog. /// </summary> class SelectCertificateDialog : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.Windows.Forms.Button _okBtn; private System.Windows.Forms.Button _cancelBtn; private X509CertificateStore _store; private System.Windows.Forms.ListView _certList; private System.Windows.Forms.ColumnHeader _certName; private X509Certificate _certificate = null; public SelectCertificateDialog(X509CertificateStore store) : base() { _store = store; // Required for Windows Form Designer support // InitializeComponent(); } public X509Certificate Certificate { get { return _certificate; } } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._okBtn = new System.Windows.Forms.Button(); this._cancelBtn = new System.Windows.Forms.Button(); this._certList = new System.Windows.Forms.ListView(); this._certName = new System.Windows.Forms.ColumnHeader(); this.SuspendLayout(); // // _okBtn // this._okBtn.Location = new System.Drawing.Point(96, 232); this._okBtn.Name = "_okBtn"; this._okBtn.TabIndex = 1; this._okBtn.Text = "OK"; this._okBtn.Click += new System.EventHandler(this.OkBtn_Click); // // _cancelBtn // this._cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._cancelBtn.Location = new System.Drawing.Point(192, 232); this._cancelBtn.Name = "_cancelBtn"; this._cancelBtn.TabIndex = 2; this._cancelBtn.Text = "Cancel"; this._cancelBtn.Click += new System.EventHandler(this.CancelBtn_Click); // // _certList // this._certList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[]{ this._certName}); this._certList.Dock = System.Windows.Forms.DockStyle.Top; this._certList.FullRowSelect = true; this._certList.MultiSelect = false; this._certList.Name = "_certList"; this._certList.Size = new System.Drawing.Size(292, 176); this._certList.TabIndex = 3; this._certList.View = System.Windows.Forms.View.Details; // // _certName // this._certName.Text = "Name"; this._certName.Width = 92; // // SelectCertificateDialog // this.AcceptButton = this._okBtn; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this._cancelBtn; this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.AddRange(new System.Windows.Forms.Control[]{ this._certList, this._cancelBtn, this._okBtn}); this.Name = "SelectCertificateDialog"; this.Text = "SelectCertificateDialog"; this.ResumeLayout(false); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (_store == null) { throw new Exception("No store to open"); } if (_store.Handle == IntPtr.Zero) { throw new Exception("Store not open for reading"); } X509CertificateCollection coll = _store.Certificates; foreach(X509Certificate cert in coll) { ListViewItem item = new ListViewItem(cert.GetName()); this._certList.Items.Add(item); } } private void OkBtn_Click(object sender, System.EventArgs e) { _certificate = null; if (_certList.SelectedItems != null && _certList.SelectedItems.Count == 1) { X509CertificateCollection coll = _store.FindCertificateBySubjectName(_certList.SelectedItems[0].Text); if (coll != null && coll.Count == 1) { _certificate = coll[0] as X509Certificate; } } this.Close(); this.DialogResult = DialogResult.OK; } private void CancelBtn_Click(object sender, System.EventArgs e) { _certificate = null; } } // // Web Service Proxy class // [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="VirtuosoWSSecure", Namespace="http://temp.uri/")] // Instead of deriving from System.Web.Services.Protocols.SoapHttpClientProtocol, // WSE Web Service proxies must derive from Microsoft.Web.Services.WebServicesClientProtocol public class AddNumbers : Microsoft.Web.Services.WebServicesClientProtocol { public AddNumbers() { this.Url = "http://localhost:8890/SecureWebServices"; } [System.Web.Services.Protocols.SoapRpcMethodAttribute("http://temp.uri/#AddInt", RequestNamespace="http://temp.uri/", ResponseNamespace="http://temp.uri/")] [return: System.Xml.Serialization.SoapElementAttribute("CallReturn")] public int AddInt(int a, int b) { object[] results = this.Invoke("AddInt", new object[] { a, b}); return ((int)(results[0])); } public System.IAsyncResult BeginAddInt(int a, int b, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddInt", new object[] { a,
[ " b}, callback, asyncState);" ]
1,364
lcc
csharp
null
985588e7dc66ac6d50e0fe4a6602f7b58eb5fef402be68fa
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * 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 theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at trademark@heliumv.com). * * 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/>. * * Contact: developers@heliumv.com ******************************************************************************/ package com.lp.server.artikel.service; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import com.lp.server.system.service.PaneldatenDto; public class SeriennrChargennrMitMengeDto implements Serializable { /** * */ public static List<SeriennrChargennrMitMengeDto> erstelleDtoAusEinerSeriennummer( String seriennummer) { return erstelleSrnDtoArrayAusStringArray(new String[] { seriennummer }); } public static List<SeriennrChargennrMitMengeDto> erstelleDtoAusEinerChargennummer( String chargennummer, BigDecimal menge) { return erstelleChnrDtoArrayAusStringArrayUndMengen( new String[] { chargennummer }, new BigDecimal[] { menge }); } public SeriennrChargennrMitMengeDto() { } public SeriennrChargennrMitMengeDto(String cSeriennrChargennr, BigDecimal menge) { nMenge = menge; this.cSeriennrChargennr = cSeriennrChargennr; } public SeriennrChargennrMitMengeDto(String cSeriennrChargennr, String cVersion, BigDecimal menge) { nMenge = menge; this.cSeriennrChargennr = cSeriennrChargennr; this.cVersion = cVersion; } public static List erstelleSrnDtoArrayAusStringArray(String[] snrs) { ArrayList alSnrs = new ArrayList(); if (snrs != null) { for (int i = 0; i < snrs.length; i++) { SeriennrChargennrMitMengeDto dto = new SeriennrChargennrMitMengeDto(); dto.setCSeriennrChargennr(snrs[i]); dto.setNMenge(new BigDecimal(1)); alSnrs.add(dto); } } else { SeriennrChargennrMitMengeDto dto = new SeriennrChargennrMitMengeDto(); dto.setCSeriennrChargennr(null); dto.setNMenge(null); alSnrs.add(dto); } return alSnrs; } public static boolean sind2ListenGleich( List<SeriennrChargennrMitMengeDto> liste1, List<SeriennrChargennrMitMengeDto> liste2) { if (liste1 == null && liste2 == null) { return true; } if (liste1 == null && liste2 != null) { if (liste2.size() == 1 && liste2.get(0).getCSeriennrChargennr() == null) { return true; } else { return false; } } if (liste2 == null && liste1 != null) { if (liste1.size() == 1 && liste1.get(0).getCSeriennrChargennr() == null) { return true; } else { return false; } } if (liste1.size() == liste2.size()) { for (int i = 0; i < liste1.size(); i++) { SeriennrChargennrMitMengeDto eintrag1 = liste1.get(i); SeriennrChargennrMitMengeDto eintrag2 = liste2.get(i); String cSNR1 = ""; if (eintrag1.getCSeriennrChargennr() != null) { cSNR1 = eintrag1.getCSeriennrChargennr(); } String cSNR2 = ""; if (eintrag2.getCSeriennrChargennr() != null) { cSNR2 = eintrag2.getCSeriennrChargennr(); } if (eintrag1.getNMenge().equals(eintrag2.getNMenge()) && cSNR1.equals(cSNR2)) { } else { return false; } } return true; } else { return false; } } public static List add2SnrChnrDtos( List<SeriennrChargennrMitMengeDto> vorhandeneListe, List<SeriennrChargennrMitMengeDto> toAdd) { ArrayList alSnrs = new ArrayList(); if (vorhandeneListe != null) { if (toAdd != null) { for (int i = 0; i < toAdd.size(); i++) { vorhandeneListe.add(toAdd.get(i)); } } } else { vorhandeneListe = toAdd; } return alSnrs; } public static List add2SnrChnrDtos( List<SeriennrChargennrMitMengeDto> vorhandeneListe, SeriennrChargennrAufLagerDto toAdd) { ArrayList alSnrs = new ArrayList(); if (toAdd != null) { SeriennrChargennrMitMengeDto a = new SeriennrChargennrMitMengeDto( toAdd.getCSeriennrChargennr(), toAdd.getCVersion(), toAdd.getNMenge()); vorhandeneListe.add(a); } return alSnrs; } public static List erstelleChnrDtoArrayAusStringArrayUndMengen( String[] snrs, BigDecimal mengen[]) { ArrayList alSnrs = new ArrayList(); if (snrs != null) { for (int i = 0; i < snrs.length; i++) { SeriennrChargennrMitMengeDto dto = new SeriennrChargennrMitMengeDto(); dto.setCSeriennrChargennr(snrs[i]); dto.setNMenge(mengen[i]); alSnrs.add(dto); } } return alSnrs; } public static String erstelleStringAusMehrerenSeriennummern( List<SeriennrChargennrMitMengeDto> snrs) { String s = null; if (snrs != null && snrs.size() > 0) { s = ""; for (int i = 0; i < snrs.size(); i++) { if (snrs.get(i).getCSeriennrChargennr() != null) { s += snrs.get(i).getCSeriennrChargennr();
[ "\t\t\t\t\tif (!(i == snrs.size() - 1)) {" ]
724
lcc
java
null
60c91ffa1d58e4c6d52c0ae275b009bc330e180493b0d2e3
using UnityCMF.CCore; using UnityCMF.ECore; // PROTECTED REGION ID(ETypedElement.Namespaces) ENABLED START // PROTECTED REGION END namespace UnityCMF.ECore { public interface ETypedElement : EModelElement,ENamedElement { bool Ordered { get; set; } void SetOrdered(bool value, object data); bool Unique { get; set; } void SetUnique(bool value, object data); int LowerBound { get; set; } void SetLowerBound(int value, object data); int UpperBound { get; set; } void SetUpperBound(int value, object data); bool Many { get; } bool Required { get; } EClassifier EType { get; set; } void SetEType(EClassifier value, object data); EGenericType EGenericType { get; set; } void SetEGenericType(EGenericType value, object data); } public class ETypedElementImpl : ENamedElementImpl, ETypedElement { public ETypedElementImpl(UnityCMF.ECore.EClass eClass) : base(eClass) { // PROTECTED REGION ID(ETypedElement.Constructor) ENABLED START // PROTECTED REGION END } #region client code // PROTECTED REGION ID(ETypedElement.ClientCode) ENABLED START // PROTECTED REGION END #endregion #region derived features and operations public bool Many { get { // PROTECTED REGION ID(ETypedElement.Many) ENABLED START return UpperBound == -1 || UpperBound > 1; // PROTECTED REGION END } } public bool Required { get { // PROTECTED REGION ID(ETypedElement.Required) ENABLED START return default(bool); // PROTECTED REGION END } } #endregion private bool _ordered; public bool Ordered { get { return _ordered; } set { bool oldValue = _ordered; _ordered = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_Ordered)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_Ordered, oldValue, value, -1, null)); } } } public void SetOrdered(bool value, object data) { bool oldValue = _ordered; _ordered = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_Ordered)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_Ordered, oldValue, value, -1, data)); } } private bool _unique; public bool Unique { get { return _unique; } set { bool oldValue = _unique; _unique = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_Unique)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_Unique, oldValue, value, -1, null)); } } } public void SetUnique(bool value, object data) { bool oldValue = _unique; _unique = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_Unique)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_Unique, oldValue, value, -1, data)); } } private int _lowerBound; public int LowerBound { get { return _lowerBound; } set { int oldValue = _lowerBound; _lowerBound = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_LowerBound)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_LowerBound, oldValue, value, -1, null)); } } } public void SetLowerBound(int value, object data) { int oldValue = _lowerBound; _lowerBound = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_LowerBound)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_LowerBound, oldValue, value, -1, data)); } } private int _upperBound; public int UpperBound { get { return _upperBound; } set { int oldValue = _upperBound; _upperBound = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_UpperBound)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_UpperBound, oldValue, value, -1, null)); } } } public void SetUpperBound(int value, object data) { int oldValue = _upperBound; _upperBound = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_UpperBound)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_UpperBound, oldValue, value, -1, data)); } } private EClassifier _eType; public EClassifier EType { get { return _eType; } set { EClassifier oldValue = _eType; _eType = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_EType)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_EType, oldValue, value, -1, null)); } } } public void SetEType(EClassifier value, object data) { EClassifier oldValue = _eType; _eType = value; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_EType)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_EType, oldValue, value, -1, data)); } } private EGenericType _eGenericType; public EGenericType EGenericType { get { return _eGenericType; } set { EGenericType oldValue = _eGenericType; _eGenericType = value; if (oldValue != null) (oldValue as CObjectImpl).CContainer = null; if (value != null) (value as CObjectImpl).CContainer = this; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_EGenericType)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_EGenericType, oldValue, value, -1, null)); } } } public void SetEGenericType(EGenericType value, object data) { EGenericType oldValue = _eGenericType; _eGenericType = value; if (oldValue != null) (oldValue as CObjectImpl).CContainer = null; if (value != null) (value as CObjectImpl).CContainer = this; if (CNotificationRequired(ECoreMeta.cINSTANCE.Package.ETypedElement_EGenericType)) { CNotify(new CAction(this, CActionType.SET, ECoreMeta.cINSTANCE.Package.ETypedElement_EGenericType, oldValue, value, -1, data)); } } public override void CSet(EStructuralFeature feature, object value) { switch(feature.Name) { case "ordered" : Ordered = (bool)value; break; case "unique" : Unique = (bool)value; break; case "lowerBound" : LowerBound = (int)value; break; case "upperBound" : UpperBound = (int)value; break; case "eType" :
[ "\t\t\t\t\tEType = (EClassifier)value;" ]
642
lcc
csharp
null
7a60f7b18cb99dc78088418a1c233691053449386e7273eb
#!/usr/bin/env python3 from argparse import ArgumentParser from encrypted_archive_index import EncryptedArchiveIndex import sys from getpass import getpass from key_deriver import KeyDeriver import log from archive_encryptor import ArchiveEncryptor, EncryptedArchiveCorruptException import consts import os def new_password(prompt, confirm_prompt='Confirm Password: '): while True: password = getpass(prompt) confirm_password = getpass(confirm_prompt) if password == confirm_password: break log.msg('Passwords do not match - please try again') log.msg() return password def load_archive_index(path): eai = EncryptedArchiveIndex(path) if not eai.exists(): log.info('cryptostasis', 'Archive Index does not exist - going through first time setup') log.msg('===== First Time Setup =====') log.msg('You\'ll need to set a password used to encrypt the archive index') password = new_password('New Index Password: ') eai.init_new() master_key = eai.derive_master_key(password) eai.update_master_key(master_key) archive_index = eai.create_new_index() archive_index.save() return archive_index else: log.info('cryptostasis', 'Attempting to load archive index') try: eai.load() log.info('cryptostasis', 'Successfully loaded archive index') except Exception as e: log.msg('Failed to load archive index') log.debug('cryptostasis', str(e)) sys.exit(1) password = getpass('Index Password: ') master_key = eai.derive_master_key(password) if not eai.verify_master_key(master_key): log.msg('Incorrect password') sys.exit(1) if not eai.verify_index_integrity(master_key): log.msg('Index corrupt') sys.exit(1) return eai.decrypt_index(master_key) def get_input_strm(args): if args.input_file is not None: return open(args.input_file, 'rb') return sys.stdin.buffer def get_output_strm(args): if args.output_file is not None: return open(args.output_file, 'wb') return sys.stdout.buffer # Actions def encrypt_archive(archive_index, args): input_strm = get_input_strm(args) output_strm = get_output_strm(args) archive_name = args.archive_name if archive_index.name_exists(archive_name): log.msg('\'{}\' archive exists - quitting'.format(archive_name)) sys.exit(1) arch_enc = ArchiveEncryptor(archive_index) arch_enc.encrypt_archive(input_strm, output_strm, archive_name) input_strm.close() output_strm.flush() output_strm.close() def decrypt_archive(archive_index, args): input_strm = get_input_strm(args) output_strm = get_output_strm(args) arch_enc = ArchiveEncryptor(archive_index) success = True try: archive_entry = arch_enc.decrypt_archive(input_strm, output_strm) if archive_entry is not None: log.msg('Successfully decrypted \'{}\' archive'.format(archive_entry.name)) else: log.msg('Could not find th decryption key for this archive - are you sure that it is an encrypted archive?') success = False except Exception as e: log.msg('Something went wrong trying to decrypt the archive') log.debug('cryptostasis', 'Decryption failed - stack trace:\n{}'.format(str(e))) success = False except EncryptedArchiveCorruptException as e: log.msg('Failed to decrypt archive: {}'.format(e.message)) if e is EncryptedArchiveCorruptException: log.info('cryptostasis', 'Corrupt archive - {}'.format(e.reason)) log.debug('cryptostasis', 'Full exception:\n{}'.format(str(e))) success = False input_strm.close() output_strm.flush() output_strm.close() if not success: if args.output_file is not None: os.remove(args.output_file) return 1 def list_index(archive_index, args): log.msg(str(archive_index)) def change_password(archive_index, args): new_pass = new_password('Enter the new index password: ') eai = archive_index.encrypted_archive_index eai.password_salt = KeyDeriver.new_salt() if args.time_cost is not None: eai.time_cost = args.time_cost if args.memory_cost is not None: eai.memory_cost = args.memory_cost if args.parallelism is not None: eai.parallelism = args.parallelism master_key = archive_index.encrypted_archive_index.derive_master_key(new_pass) archive_index.encrypted_archive_index.update_master_key(master_key) archive_index.save() log.msg('Successfully changed index password') def main(): parser = ArgumentParser() parser.add_argument('-v', '--verbose', action='count', default=0, dest='verbosity') parser.add_argument('-V', '--version', dest='version', help='Show version and exit', action='store_true') parser.add_argument('--log-file', type=str, dest='log_file', help='Path to log file (use with --verbose)') parser.add_argument( '-I', '--index', type=str, dest='index_file', default=consts.INDEX_DEFAULT_LOCATION, help='Archive Index File (defaults to {})'.format(consts.INDEX_DEFAULT_LOCATION) ) actions = parser.add_subparsers() encrypt_subparser = actions.add_parser('encrypt', help='Encrypt an archive') encrypt_subparser.set_defaults(func=encrypt_archive) encrypt_subparser.add_argument('archive_name') encrypt_subparser.add_argument('-f', '--input-file', type=str, dest='input_file', help='Input archive file (defaults to STDIN)') encrypt_subparser.add_argument('-o', '--output-file', type=str, dest='output_file', help='Encrypted output archive file (defaults to STDOUT)') decrypt_subparser = actions.add_parser('decrypt', help='Decrypt an archive') decrypt_subparser.set_defaults(func=decrypt_archive) decrypt_subparser.add_argument('-f', '--input-file', type=str, dest='input_file', help='Input encrypted archive file (defaults to STDIN)') decrypt_subparser.add_argument('-o', '--output-file', type=str, dest='output_file', help='Output archive file (defaults to STDOUT)') list_subparser = actions.add_parser('list', help='List entries in the index') list_subparser.set_defaults(func=list_index) change_password_subparser = actions.add_parser( 'passwd', description = ( 'When changing the encryption password, you can also configure the Key Derivation Function (KDF) parameters. ' + 'If they are not set, they default to the current parameters as loaded from the index. ' + 'When creating a new index, the parameters are time_cost = {}, memory_cost = {}, and parallelism = {}' .format(consts.DEFAULT_TIME_COST, consts.DEFAULT_MEMORY_COST, consts.DEFAULT_PARALLELISM) ), help = 'Change index password' ) change_password_subparser.set_defaults(func=change_password) change_password_subparser.add_argument('-t', '--time-cost', type=int, dest='time_cost', help='The time cost parameter passed to the KDF') change_password_subparser.add_argument('-m', '--memory-cost', type=int, dest='memory_cost', help='The memory cost parameter passed to the KDF') change_password_subparser.add_argument('-p', '--parallelism', type=int, dest='parallelism', help='The parallelism parameter passed to the KDF') args = parser.parse_args() if args.version: log.msg('Cryptostasis v{}'.format(consts.VERSION)) sys.exit(0) log.level = args.verbosity log.info('cryptostasis', 'Verbosity level: {}'.format(args.verbosity)) if args.log_file is not None: log.msg('Writing logs to: {}'.format(args.log_file))
[ " log.log_strm = open(args.log_file, 'w')" ]
626
lcc
python
null
cd81bc2e4c0a7dc1e4f6a340a63de44a5b0e7a055b43a7b3
## ## This file is part of the libsigrokdecode project. ## ## Copyright (C) 2012-2014 Uwe Hermann <uwe@hermann-uwe.de> ## ## 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 St, Fifth Floor, Boston, MA 02110-1301 USA ## import sigrokdecode as srd # Normal commands (CMD) cmd_names = { 0: 'GO_IDLE_STATE', 1: 'SEND_OP_COND', 6: 'SWITCH_FUNC', 8: 'SEND_IF_COND', 9: 'SEND_CSD', 10: 'SEND_CID', 12: 'STOP_TRANSMISSION', 13: 'SEND_STATUS', 16: 'SET_BLOCKLEN', 17: 'READ_SINGLE_BLOCK', 18: 'READ_MULTIPLE_BLOCK', 24: 'WRITE_BLOCK', 25: 'WRITE_MULTIPLE_BLOCK', 27: 'PROGRAM_CSD', 28: 'SET_WRITE_PROT', 29: 'CLR_WRITE_PROT', 30: 'SEND_WRITE_PROT', 32: 'ERASE_WR_BLK_START_ADDR', 33: 'ERASE_WR_BLK_END_ADDR', 38: 'ERASE', 42: 'LOCK_UNLOCK', 55: 'APP_CMD', 56: 'GEN_CMD', 58: 'READ_OCR', 59: 'CRC_ON_OFF', # CMD60-63: Reserved for manufacturer } # Application-specific commands (ACMD) acmd_names = { 13: 'SD_STATUS', 18: 'Reserved for SD security applications', 22: 'SEND_NUM_WR_BLOCKS', 23: 'SET_WR_BLK_ERASE_COUNT', 25: 'Reserved for SD security applications', 26: 'Reserved for SD security applications', 38: 'Reserved for SD security applications', 41: 'SD_SEND_OP_COND', 42: 'SET_CLR_CARD_DETECT', 43: 'Reserved for SD security applications', 44: 'Reserved for SD security applications', 45: 'Reserved for SD security applications', 46: 'Reserved for SD security applications', 47: 'Reserved for SD security applications', 48: 'Reserved for SD security applications', 49: 'Reserved for SD security applications', 51: 'SEND_SCR', } class Decoder(srd.Decoder): api_version = 2 id = 'sdcard_spi' name = 'SD card (SPI mode)' longname = 'Secure Digital card (SPI mode)' desc = 'Secure Digital card (SPI mode) low-level protocol.' license = 'gplv2+' inputs = ['spi'] outputs = ['sdcard_spi'] annotations = \ tuple(('cmd%d' % i, 'CMD%d' % i) for i in range(64)) + \ tuple(('acmd%d' % i, 'ACMD%d' % i) for i in range(64)) + ( \ ('r1', 'R1 reply'), ('r1b', 'R1B reply'), ('r2', 'R2 reply'), ('r3', 'R3 reply'), ('r7', 'R7 reply'), ('bits', 'Bits'), ('bit-warnings', 'Bit warnings'), ) annotation_rows = ( ('bits', 'Bits', (134, 135)), ('cmd-reply', 'Commands/replies', tuple(range(134))), ) def __init__(self, **kwargs): self.state = 'IDLE' self.samplenum = 0 self.ss, self.es = 0, 0 self.bit_ss, self.bit_es = 0, 0 self.cmd_ss, self.cmd_es = 0, 0 self.cmd_token = [] self.cmd_token_bits = [] self.is_acmd = False # Indicates CMD vs. ACMD self.blocklen = 0 self.read_buf = [] self.cmd_str = '' def start(self): self.out_ann = self.register(srd.OUTPUT_ANN) def putx(self, data): self.put(self.cmd_ss, self.cmd_es, self.out_ann, data) def putc(self, cmd, desc): self.putx([cmd, ['%s: %s' % (self.cmd_str, desc)]]) def putb(self, data): self.put(self.bit_ss, self.bit_es, self.out_ann, data) def cmd_name(self, cmd): c = acmd_names if self.is_acmd else cmd_names return c.get(cmd, 'Unknown') def handle_command_token(self, mosi, miso): # Command tokens (6 bytes) are sent (MSB-first) by the host. # # Format: # - CMD[47:47]: Start bit (always 0) # - CMD[46:46]: Transmitter bit (1 == host) # - CMD[45:40]: Command index (BCD; valid: 0-63) # - CMD[39:08]: Argument # - CMD[07:01]: CRC7 # - CMD[00:00]: End bit (always 1) if len(self.cmd_token) == 0: self.cmd_ss = self.ss self.cmd_token.append(mosi) self.cmd_token_bits.append(self.mosi_bits) # All command tokens are 6 bytes long. if len(self.cmd_token) < 6: return self.cmd_es = self.es t = self.cmd_token # CMD or ACMD? s = 'ACMD' if self.is_acmd else 'CMD' def tb(byte, bit): return self.cmd_token_bits[5 - byte][bit] # Bits[47:47]: Start bit (always 0) bit, self.bit_ss, self.bit_es = tb(5, 7)[0], tb(5, 7)[1], tb(5, 7)[2] if bit == 0: self.putb([134, ['Start bit: %d' % bit]]) else: self.putb([135, ['Start bit: %s (Warning: Must be 0!)' % bit]]) # Bits[46:46]: Transmitter bit (1 == host) bit, self.bit_ss, self.bit_es = tb(5, 6)[0], tb(5, 6)[1], tb(5, 6)[2] if bit == 1: self.putb([134, ['Transmitter bit: %d' % bit]]) else: self.putb([135, ['Transmitter bit: %d (Warning: Must be 1!)' % bit]]) # Bits[45:40]: Command index (BCD; valid: 0-63) cmd = self.cmd_index = t[0] & 0x3f self.bit_ss, self.bit_es = tb(5, 5)[1], tb(5, 0)[2] self.putb([134, ['Command: %s%d (%s)' % (s, cmd, self.cmd_name(cmd))]]) # Bits[39:8]: Argument self.arg = (t[1] << 24) | (t[2] << 16) | (t[3] << 8) | t[4] self.bit_ss, self.bit_es = tb(4, 7)[1], tb(1, 0)[2] self.putb([134, ['Argument: 0x%04x' % self.arg]]) # Bits[7:1]: CRC7 # TODO: Check CRC7. crc = t[5] >> 1 self.bit_ss, self.bit_es = tb(0, 7)[1], tb(0, 1)[2] self.putb([134, ['CRC7: 0x%01x' % crc]]) # Bits[0:0]: End bit (always 1) bit, self.bit_ss, self.bit_es = tb(0, 0)[0], tb(0, 0)[1], tb(0, 0)[2] self.putb([134, ['End bit: %d' % bit]]) if bit == 1: self.putb([134, ['End bit: %d' % bit]]) else: self.putb([135, ['End bit: %d (Warning: Must be 1!)' % bit]]) # Handle command. if cmd in (0, 1, 9, 16, 17, 41, 49, 55, 59): self.state = 'HANDLE CMD%d' % cmd self.cmd_str = '%s%d (%s)' % (s, cmd, self.cmd_name(cmd)) else: self.state = 'HANDLE CMD999' a = '%s%d: %02x %02x %02x %02x %02x %02x' % ((s, cmd) + tuple(t)) self.putx([cmd, [a]]) def handle_cmd0(self): # CMD0: GO_IDLE_STATE self.putc(0, 'Reset the SD card') self.state = 'GET RESPONSE R1' def handle_cmd1(self): # CMD1: SEND_OP_COND self.putc(1, 'Send HCS info and activate the card init process') hcs = (self.arg & (1 << 30)) >> 30 self.bit_ss = self.cmd_token_bits[5 - 4][6][1] self.bit_es = self.cmd_token_bits[5 - 4][6][2] self.putb([134, ['HCS: %d' % hcs]]) self.state = 'GET RESPONSE R1' def handle_cmd9(self): # CMD9: SEND_CSD (128 bits / 16 bytes) self.putc(9, 'Ask card to send its card specific data (CSD)') if len(self.read_buf) == 0: self.cmd_ss = self.ss self.read_buf.append(self.miso) # FIXME ### if len(self.read_buf) < 16: if len(self.read_buf) < 16 + 4: return self.cmd_es = self.es self.read_buf = self.read_buf[4:] ### TODO: Document or redo. self.putx([9, ['CSD: %s' % self.read_buf]]) # TODO: Decode all bits. self.read_buf = [] ### self.state = 'GET RESPONSE R1' self.state = 'IDLE' def handle_cmd10(self): # CMD10: SEND_CID (128 bits / 16 bytes) self.putc(10, 'Ask card to send its card identification (CID)') self.read_buf.append(self.miso) if len(self.read_buf) < 16: return self.putx([10, ['CID: %s' % self.read_buf]]) # TODO: Decode all bits. self.read_buf = [] self.state = 'GET RESPONSE R1' def handle_cmd16(self): # CMD16: SET_BLOCKLEN self.blocklen = self.arg # TODO: Sanity check on block length. self.putc(16, 'Set the block length to %d bytes' % self.blocklen) self.state = 'GET RESPONSE R1' def handle_cmd17(self): # CMD17: READ_SINGLE_BLOCK self.putc(17, 'Read a block from address 0x%04x' % self.arg) if len(self.read_buf) == 0: self.cmd_ss = self.ss self.read_buf.append(self.miso) if len(self.read_buf) < self.blocklen + 2: # FIXME return self.cmd_es = self.es self.read_buf = self.read_buf[2:] # FIXME self.putx([17, ['Block data: %s' % self.read_buf]]) self.read_buf = [] self.state = 'GET RESPONSE R1' def handle_cmd49(self): self.state = 'GET RESPONSE R1' def handle_cmd55(self): # CMD55: APP_CMD self.putc(55, 'Next command is an application-specific command') self.is_acmd = True self.state = 'GET RESPONSE R1' def handle_cmd59(self): # CMD59: CRC_ON_OFF crc_on_off = self.arg & (1 << 0) s = 'on' if crc_on_off == 1 else 'off' self.putc(59, 'Turn the SD card CRC option %s' % s) self.state = 'GET RESPONSE R1' def handle_acmd41(self): # ACMD41: SD_SEND_OP_COND self.putc(64 + 41, 'Send HCS info and activate the card init process') self.state = 'GET RESPONSE R1' def handle_cmd999(self): self.state = 'GET RESPONSE R1' def handle_cid_register(self): # Card Identification (CID) register, 128bits cid = self.cid # Manufacturer ID: CID[127:120] (8 bits) mid = cid[15] # OEM/Application ID: CID[119:104] (16 bits) oid = (cid[14] << 8) | cid[13] # Product name: CID[103:64] (40 bits) pnm = 0 for i in range(12, 8 - 1, -1): pnm <<= 8 pnm |= cid[i] # Product revision: CID[63:56] (8 bits) prv = cid[7] # Product serial number: CID[55:24] (32 bits) psn = 0 for i in range(6, 3 - 1, -1): psn <<= 8 psn |= cid[i] # RESERVED: CID[23:20] (4 bits) # Manufacturing date: CID[19:8] (12 bits) # TODO # CRC7 checksum: CID[7:1] (7 bits) # TODO # Not used, always 1: CID[0:0] (1 bit) # TODO def handle_response_r1(self, res): # The R1 response token format (1 byte). # Sent by the card after every command except for SEND_STATUS. self.cmd_ss, self.cmd_es = self.miso_bits[7][1], self.miso_bits[0][2] self.putx([65, ['R1: 0x%02x' % res]]) def putbit(bit, data): b = self.miso_bits[bit] self.bit_ss, self.bit_es = b[1], b[2] self.putb([134, data]) # Bit 0: 'In idle state' bit s = '' if (res & (1 << 0)) else 'not ' putbit(0, ['Card is %sin idle state' % s]) # Bit 1: 'Erase reset' bit s = '' if (res & (1 << 1)) else 'not ' putbit(1, ['Erase sequence %scleared' % s]) # Bit 2: 'Illegal command' bit s = 'I' if (res & (1 << 2)) else 'No i' putbit(2, ['%sllegal command detected' % s]) # Bit 3: 'Communication CRC error' bit s = 'failed' if (res & (1 << 3)) else 'was successful' putbit(3, ['CRC check of last command %s' % s]) # Bit 4: 'Erase sequence error' bit s = 'E' if (res & (1 << 4)) else 'No e' putbit(4, ['%srror in the sequence of erase commands' % s]) # Bit 5: 'Address error' bit s = 'M' if (res & (1 << 4)) else 'No m' putbit(5, ['%sisaligned address used in command' % s]) # Bit 6: 'Parameter error' bit s = '' if (res & (1 << 4)) else 'not ' putbit(6, ['Command argument %soutside allowed range' % s]) # Bit 7: Always set to 0 putbit(7, ['Bit 7 (always 0)']) self.state = 'IDLE' def handle_response_r1b(self, res): # TODO pass def handle_response_r2(self, res): # TODO pass def handle_response_r3(self, res): # TODO pass # Note: Response token formats R4 and R5 are reserved for SDIO. # TODO: R6? def handle_response_r7(self, res): # TODO pass def decode(self, ss, es, data): ptype, mosi, miso = data # For now, only use DATA and BITS packets. if ptype not in ('DATA', 'BITS'): return # Store the individual bit values and ss/es numbers. The next packet # is guaranteed to be a 'DATA' packet belonging to this 'BITS' one.
[ " if ptype == 'BITS':" ]
1,650
lcc
python
null
467203b77592a0dbc3eb517669aab5cd995bdb6136767dd3
// This file was generated automatically by the Snowball to Java compiler package edu.nyu.stex.data.preprocess.snowball; /** * This class was automatically generated by a snowball to Java compiler It * implements the stemming algorithm defined by a snowball script. */ public class romanianStemmer extends SnowballStemmer { private static final long serialVersionUID = 1L; private final static romanianStemmer methodObject = new romanianStemmer(); private final static Among a_0[] = {new Among("", -1, 3, "", methodObject), new Among("I", 0, 1, "", methodObject), new Among("U", 0, 2, "", methodObject)}; private final static Among a_1[] = { new Among("ea", -1, 3, "", methodObject), new Among("a\u0163ia", -1, 7, "", methodObject), new Among("aua", -1, 2, "", methodObject), new Among("iua", -1, 4, "", methodObject), new Among("a\u0163ie", -1, 7, "", methodObject), new Among("ele", -1, 3, "", methodObject), new Among("ile", -1, 5, "", methodObject), new Among("iile", 6, 4, "", methodObject), new Among("iei", -1, 4, "", methodObject), new Among("atei", -1, 6, "", methodObject), new Among("ii", -1, 4, "", methodObject), new Among("ului", -1, 1, "", methodObject), new Among("ul", -1, 1, "", methodObject), new Among("elor", -1, 3, "", methodObject), new Among("ilor", -1, 4, "", methodObject), new Among("iilor", 14, 4, "", methodObject)}; private final static Among a_2[] = { new Among("icala", -1, 4, "", methodObject), new Among("iciva", -1, 4, "", methodObject), new Among("ativa", -1, 5, "", methodObject), new Among("itiva", -1, 6, "", methodObject), new Among("icale", -1, 4, "", methodObject), new Among("a\u0163iune", -1, 5, "", methodObject), new Among("i\u0163iune", -1, 6, "", methodObject), new Among("atoare", -1, 5, "", methodObject), new Among("itoare", -1, 6, "", methodObject), new Among("\u0103toare", -1, 5, "", methodObject), new Among("icitate", -1, 4, "", methodObject), new Among("abilitate", -1, 1, "", methodObject), new Among("ibilitate", -1, 2, "", methodObject), new Among("ivitate", -1, 3, "", methodObject), new Among("icive", -1, 4, "", methodObject), new Among("ative", -1, 5, "", methodObject), new Among("itive", -1, 6, "", methodObject), new Among("icali", -1, 4, "", methodObject), new Among("atori", -1, 5, "", methodObject), new Among("icatori", 18, 4, "", methodObject), new Among("itori", -1, 6, "", methodObject), new Among("\u0103tori", -1, 5, "", methodObject), new Among("icitati", -1, 4, "", methodObject), new Among("abilitati", -1, 1, "", methodObject), new Among("ivitati", -1, 3, "", methodObject), new Among("icivi", -1, 4, "", methodObject), new Among("ativi", -1, 5, "", methodObject), new Among("itivi", -1, 6, "", methodObject), new Among("icit\u0103i", -1, 4, "", methodObject), new Among("abilit\u0103i", -1, 1, "", methodObject), new Among("ivit\u0103i", -1, 3, "", methodObject), new Among("icit\u0103\u0163i", -1, 4, "", methodObject), new Among("abilit\u0103\u0163i", -1, 1, "", methodObject), new Among("ivit\u0103\u0163i", -1, 3, "", methodObject), new Among("ical", -1, 4, "", methodObject), new Among("ator", -1, 5, "", methodObject), new Among("icator", 35, 4, "", methodObject), new Among("itor", -1, 6, "", methodObject), new Among("\u0103tor", -1, 5, "", methodObject), new Among("iciv", -1, 4, "", methodObject), new Among("ativ", -1, 5, "", methodObject), new Among("itiv", -1, 6, "", methodObject), new Among("ical\u0103", -1, 4, "", methodObject), new Among("iciv\u0103", -1, 4, "", methodObject), new Among("ativ\u0103", -1, 5, "", methodObject), new Among("itiv\u0103", -1, 6, "", methodObject)}; private final static Among a_3[] = { new Among("ica", -1, 1, "", methodObject), new Among("abila", -1, 1, "", methodObject), new Among("ibila", -1, 1, "", methodObject), new Among("oasa", -1, 1, "", methodObject), new Among("ata", -1, 1, "", methodObject), new Among("ita", -1, 1, "", methodObject), new Among("anta", -1, 1, "", methodObject), new Among("ista", -1, 3, "", methodObject), new Among("uta", -1, 1, "", methodObject), new Among("iva", -1, 1, "", methodObject), new Among("ic", -1, 1, "", methodObject), new Among("ice", -1, 1, "", methodObject), new Among("abile", -1, 1, "", methodObject), new Among("ibile", -1, 1, "", methodObject), new Among("isme", -1, 3, "", methodObject), new Among("iune", -1, 2, "", methodObject), new Among("oase", -1, 1, "", methodObject), new Among("ate", -1, 1, "", methodObject), new Among("itate", 17, 1, "", methodObject), new Among("ite", -1, 1, "", methodObject), new Among("ante", -1, 1, "", methodObject), new Among("iste", -1, 3, "", methodObject), new Among("ute", -1, 1, "", methodObject), new Among("ive", -1, 1, "", methodObject), new Among("ici", -1, 1, "", methodObject), new Among("abili", -1, 1, "", methodObject), new Among("ibili", -1, 1, "", methodObject), new Among("iuni", -1, 2, "", methodObject), new Among("atori", -1, 1, "", methodObject), new Among("osi", -1, 1, "", methodObject), new Among("ati", -1, 1, "", methodObject), new Among("itati", 30, 1, "", methodObject), new Among("iti", -1, 1, "", methodObject), new Among("anti", -1, 1, "", methodObject), new Among("isti", -1, 3, "", methodObject), new Among("uti", -1, 1, "", methodObject), new Among("i\u015Fti", -1, 3, "", methodObject), new Among("ivi", -1, 1, "", methodObject), new Among("it\u0103i", -1, 1, "", methodObject), new Among("o\u015Fi", -1, 1, "", methodObject), new Among("it\u0103\u0163i", -1, 1, "", methodObject), new Among("abil", -1, 1, "", methodObject), new Among("ibil", -1, 1, "", methodObject), new Among("ism", -1, 3, "", methodObject), new Among("ator", -1, 1, "", methodObject), new Among("os", -1, 1, "", methodObject), new Among("at", -1, 1, "", methodObject), new Among("it", -1, 1, "", methodObject), new Among("ant", -1, 1, "", methodObject), new Among("ist", -1, 3, "", methodObject), new Among("ut", -1, 1, "", methodObject), new Among("iv", -1, 1, "", methodObject), new Among("ic\u0103", -1, 1, "", methodObject), new Among("abil\u0103", -1, 1, "", methodObject), new Among("ibil\u0103", -1, 1, "", methodObject), new Among("oas\u0103", -1, 1, "", methodObject), new Among("at\u0103", -1, 1, "", methodObject), new Among("it\u0103", -1, 1, "", methodObject), new Among("ant\u0103", -1, 1, "", methodObject), new Among("ist\u0103", -1, 3, "", methodObject), new Among("ut\u0103", -1, 1, "", methodObject), new Among("iv\u0103", -1, 1, "", methodObject)}; private final static Among a_4[] = { new Among("ea", -1, 1, "", methodObject), new Among("ia", -1, 1, "", methodObject), new Among("esc", -1, 1, "", methodObject), new Among("\u0103sc", -1, 1, "", methodObject), new Among("ind", -1, 1, "", methodObject), new Among("\u00E2nd", -1, 1, "", methodObject), new Among("are", -1, 1, "", methodObject), new Among("ere", -1, 1, "", methodObject), new Among("ire", -1, 1, "", methodObject), new Among("\u00E2re", -1, 1, "", methodObject), new Among("se", -1, 2, "", methodObject), new Among("ase", 10, 1, "", methodObject), new Among("sese", 10, 2, "", methodObject), new Among("ise", 10, 1, "", methodObject), new Among("use", 10, 1, "", methodObject), new Among("\u00E2se", 10, 1, "", methodObject), new Among("e\u015Fte", -1, 1, "", methodObject), new Among("\u0103\u015Fte", -1, 1, "", methodObject), new Among("eze", -1, 1, "", methodObject), new Among("ai", -1, 1, "", methodObject), new Among("eai", 19, 1, "", methodObject), new Among("iai", 19, 1, "", methodObject), new Among("sei", -1, 2, "", methodObject), new Among("e\u015Fti", -1, 1, "", methodObject), new Among("\u0103\u015Fti", -1, 1, "", methodObject), new Among("ui", -1, 1, "", methodObject), new Among("ezi", -1, 1, "", methodObject), new Among("\u00E2i", -1, 1, "", methodObject), new Among("a\u015Fi", -1, 1, "", methodObject), new Among("se\u015Fi", -1, 2, "", methodObject), new Among("ase\u015Fi", 29, 1, "", methodObject), new Among("sese\u015Fi", 29, 2, "", methodObject), new Among("ise\u015Fi", 29, 1, "", methodObject), new Among("use\u015Fi", 29, 1, "", methodObject), new Among("\u00E2se\u015Fi", 29, 1, "", methodObject), new Among("i\u015Fi", -1, 1, "", methodObject), new Among("u\u015Fi", -1, 1, "", methodObject), new Among("\u00E2\u015Fi", -1, 1, "", methodObject), new Among("a\u0163i", -1, 2, "", methodObject), new Among("ea\u0163i", 38, 1, "", methodObject), new Among("ia\u0163i", 38, 1, "", methodObject), new Among("e\u0163i", -1, 2, "", methodObject), new Among("i\u0163i", -1, 2, "", methodObject), new Among("\u00E2\u0163i", -1, 2, "", methodObject), new Among("ar\u0103\u0163i", -1, 1, "", methodObject), new Among("ser\u0103\u0163i", -1, 2, "", methodObject), new Among("aser\u0103\u0163i", 45, 1, "", methodObject), new Among("seser\u0103\u0163i", 45, 2, "", methodObject), new Among("iser\u0103\u0163i", 45, 1, "", methodObject), new Among("user\u0103\u0163i", 45, 1, "", methodObject), new Among("\u00E2ser\u0103\u0163i", 45, 1, "", methodObject), new Among("ir\u0103\u0163i", -1, 1, "", methodObject), new Among("ur\u0103\u0163i", -1, 1, "", methodObject), new Among("\u00E2r\u0103\u0163i", -1, 1, "", methodObject), new Among("am", -1, 1, "", methodObject), new Among("eam", 54, 1, "", methodObject), new Among("iam", 54, 1, "", methodObject), new Among("em", -1, 2, "", methodObject), new Among("asem", 57, 1, "", methodObject), new Among("sesem", 57, 2, "", methodObject), new Among("isem", 57, 1, "", methodObject), new Among("usem", 57, 1, "", methodObject), new Among("\u00E2sem", 57, 1, "", methodObject), new Among("im", -1, 2, "", methodObject), new Among("\u00E2m", -1, 2, "", methodObject), new Among("\u0103m", -1, 2, "", methodObject), new Among("ar\u0103m", 65, 1, "", methodObject), new Among("ser\u0103m", 65, 2, "", methodObject), new Among("aser\u0103m", 67, 1, "", methodObject), new Among("seser\u0103m", 67, 2, "", methodObject), new Among("iser\u0103m", 67, 1, "", methodObject), new Among("user\u0103m", 67, 1, "", methodObject), new Among("\u00E2ser\u0103m", 67, 1, "", methodObject), new Among("ir\u0103m", 65, 1, "", methodObject), new Among("ur\u0103m", 65, 1, "", methodObject), new Among("\u00E2r\u0103m", 65, 1, "", methodObject), new Among("au", -1, 1, "", methodObject), new Among("eau", 76, 1, "", methodObject), new Among("iau", 76, 1, "", methodObject), new Among("indu", -1, 1, "", methodObject), new Among("\u00E2ndu", -1, 1, "", methodObject), new Among("ez", -1, 1, "", methodObject), new Among("easc\u0103", -1, 1, "", methodObject), new Among("ar\u0103", -1, 1, "", methodObject), new Among("ser\u0103", -1, 2, "", methodObject), new Among("aser\u0103", 84, 1, "", methodObject), new Among("seser\u0103", 84, 2, "", methodObject), new Among("iser\u0103", 84, 1, "", methodObject), new Among("user\u0103", 84, 1, "", methodObject), new Among("\u00E2ser\u0103", 84, 1, "", methodObject), new Among("ir\u0103", -1, 1, "", methodObject), new Among("ur\u0103", -1, 1, "", methodObject), new Among("\u00E2r\u0103", -1, 1, "", methodObject), new Among("eaz\u0103", -1, 1, "", methodObject)}; private final static Among a_5[] = {new Among("a", -1, 1, "", methodObject), new Among("e", -1, 1, "", methodObject), new Among("ie", 1, 1, "", methodObject), new Among("i", -1, 1, "", methodObject), new Among("\u0103", -1, 1, "", methodObject)}; private static final char g_v[] = {17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 32, 0, 0, 4}; private boolean B_standard_suffix_removed; private int I_p2; private int I_p1; private int I_pV; private void copy_from(romanianStemmer other) { B_standard_suffix_removed = other.B_standard_suffix_removed; I_p2 = other.I_p2; I_p1 = other.I_p1; I_pV = other.I_pV; super.copy_from(other); } private boolean r_prelude() { int v_1; int v_2; int v_3; // (, line 31 // repeat, line 32 replab0: while (true) { v_1 = cursor; lab1: do { // goto, line 32 golab2: while (true) { v_2 = cursor; lab3: do { // (, line 32 if (!(in_grouping(g_v, 97, 259))) { break lab3; } // [, line 33 bra = cursor; // or, line 33 lab4: do { v_3 = cursor; lab5: do { // (, line 33 // literal, line 33 if (!(eq_s(1, "u"))) { break lab5; } // ], line 33 ket = cursor; if (!(in_grouping(g_v, 97, 259))) { break lab5; } // <-, line 33 slice_from("U"); break lab4; } while (false); cursor = v_3; // (, line 34 // literal, line 34 if (!(eq_s(1, "i"))) { break lab3; } // ], line 34 ket = cursor; if (!(in_grouping(g_v, 97, 259))) { break lab3; } // <-, line 34 slice_from("I"); } while (false); cursor = v_2; break golab2; } while (false); cursor = v_2; if (cursor >= limit) { break lab1; } cursor++; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; } private boolean r_mark_regions() { int v_1; int v_2; int v_3; int v_6; int v_8; // (, line 38 I_pV = limit; I_p1 = limit; I_p2 = limit; // do, line 44 v_1 = cursor; lab0: do { // (, line 44 // or, line 46 lab1: do { v_2 = cursor; lab2: do { // (, line 45 if (!(in_grouping(g_v, 97, 259))) { break lab2; } // or, line 45 lab3: do { v_3 = cursor; lab4: do { // (, line 45 if (!(out_grouping(g_v, 97, 259))) { break lab4; } // gopast, line 45 golab5: while (true) { lab6: do { if (!(in_grouping(g_v, 97, 259))) { break lab6; } break golab5; } while (false); if (cursor >= limit) { break lab4; } cursor++; } break lab3; } while (false); cursor = v_3; // (, line 45 if (!(in_grouping(g_v, 97, 259))) { break lab2; } // gopast, line 45 golab7: while (true) { lab8: do { if (!(out_grouping(g_v, 97, 259))) { break lab8; } break golab7; } while (false); if (cursor >= limit) { break lab2; } cursor++; } } while (false); break lab1; } while (false); cursor = v_2; // (, line 47 if (!(out_grouping(g_v, 97, 259))) { break lab0; } // or, line 47 lab9: do { v_6 = cursor; lab10: do { // (, line 47 if (!(out_grouping(g_v, 97, 259))) { break lab10; } // gopast, line 47 golab11: while (true) { lab12: do { if (!(in_grouping(g_v, 97, 259))) { break lab12; } break golab11; } while (false); if (cursor >= limit) { break lab10; } cursor++; } break lab9; } while (false); cursor = v_6; // (, line 47 if (!(in_grouping(g_v, 97, 259))) { break lab0; } // next, line 47 if (cursor >= limit) { break lab0; } cursor++; } while (false); } while (false); // setmark pV, line 48 I_pV = cursor; } while (false); cursor = v_1; // do, line 50 v_8 = cursor; lab13: do { // (, line 50 // gopast, line 51 golab14: while (true) { lab15: do { if (!(in_grouping(g_v, 97, 259))) { break lab15; } break golab14; } while (false); if (cursor >= limit) { break lab13; } cursor++; } // gopast, line 51 golab16: while (true) { lab17: do { if (!(out_grouping(g_v, 97, 259))) { break lab17; } break golab16; } while (false); if (cursor >= limit) { break lab13; } cursor++; } // setmark p1, line 51 I_p1 = cursor; // gopast, line 52 golab18: while (true) { lab19: do { if (!(in_grouping(g_v, 97, 259))) { break lab19; } break golab18; } while (false); if (cursor >= limit) { break lab13; } cursor++; } // gopast, line 52 golab20: while (true) { lab21: do { if (!(out_grouping(g_v, 97, 259))) { break lab21; } break golab20; } while (false); if (cursor >= limit) { break lab13; } cursor++; } // setmark p2, line 52 I_p2 = cursor; } while (false); cursor = v_8; return true; } private boolean r_postlude() { int among_var; int v_1; // repeat, line 56 replab0: while (true) { v_1 = cursor; lab1: do { // (, line 56 // [, line 58 bra = cursor; // substring, line 58 among_var = find_among(a_0, 3); if (among_var == 0) { break lab1; } // ], line 58 ket = cursor; switch (among_var) { case 0: break lab1; case 1: // (, line 59 // <-, line 59 slice_from("i"); break; case 2: // (, line 60 // <-, line 60 slice_from("u"); break; case 3: // (, line 61 // next, line 61 if (cursor >= limit) { break lab1; } cursor++; break; } continue replab0; } while (false); cursor = v_1; break replab0; } return true; } private boolean r_RV() { if (!(I_pV <= cursor)) { return false; } return true; } private boolean r_R1() { if (!(I_p1 <= cursor)) { return false; } return true; } private boolean r_R2() { if (!(I_p2 <= cursor)) { return false; } return true; } private boolean r_step_0() { int among_var; int v_1; // (, line 72 // [, line 73 ket = cursor; // substring, line 73 among_var = find_among_b(a_1, 16); if (among_var == 0) { return false; } // ], line 73 bra = cursor; // call R1, line 73 if (!r_R1()) { return false; } switch (among_var) { case 0: return false; case 1: // (, line 75 // delete, line 75 slice_del(); break; case 2: // (, line 77 // <-, line 77 slice_from("a"); break; case 3: // (, line 79 // <-, line 79 slice_from("e"); break; case 4: // (, line 81 // <-, line 81 slice_from("i"); break; case 5: // (, line 83 // not, line 83 { v_1 = limit - cursor; lab0: do { // literal, line 83 if (!(eq_s_b(2, "ab"))) { break lab0; } return false; } while (false); cursor = limit - v_1; } // <-, line 83 slice_from("i"); break; case 6: // (, line 85 // <-, line 85 slice_from("at"); break; case 7: // (, line 87 // <-, line 87 slice_from("a\u0163i"); break; } return true; } private boolean r_combo_suffix() { int among_var; int v_1; // test, line 91 v_1 = limit - cursor; // (, line 91 // [, line 92 ket = cursor; // substring, line 92 among_var = find_among_b(a_2, 46); if (among_var == 0) { return false; } // ], line 92 bra = cursor; // call R1, line 92 if (!r_R1()) { return false; } // (, line 92 switch (among_var) { case 0: return false; case 1: // (, line 100 // <-, line 101 slice_from("abil"); break; case 2: // (, line 103 // <-, line 104 slice_from("ibil"); break; case 3: // (, line 106 // <-, line 107 slice_from("iv"); break; case 4: // (, line 112 // <-, line 113 slice_from("ic"); break; case 5: // (, line 117 // <-, line 118 slice_from("at"); break; case 6: // (, line 121 // <-, line 122 slice_from("it"); break; } // set standard_suffix_removed, line 125 B_standard_suffix_removed = true; cursor = limit - v_1; return true; } private boolean r_standard_suffix() { int among_var; int v_1; // (, line 129 // unset standard_suffix_removed, line 130 B_standard_suffix_removed = false; // repeat, line 131 replab0: while (true) { v_1 = limit - cursor; lab1: do { // call combo_suffix, line 131 if (!r_combo_suffix()) { break lab1; } continue replab0; } while (false); cursor = limit - v_1; break replab0; } // [, line 132 ket = cursor; // substring, line 132 among_var = find_among_b(a_3, 62); if (among_var == 0) { return false; } // ], line 132 bra = cursor; // call R2, line 132 if (!r_R2()) { return false; } // (, line 132 switch (among_var) { case 0: return false; case 1: // (, line 148 // delete, line 149 slice_del(); break; case 2: // (, line 151 // literal, line 152 if (!(eq_s_b(1, "\u0163"))) { return false; } // ], line 152 bra = cursor; // <-, line 152 slice_from("t"); break; case 3: // (, line 155 // <-, line 156 slice_from("ist"); break; } // set standard_suffix_removed, line 160 B_standard_suffix_removed = true; return true; } private boolean r_verb_suffix() { int among_var; int v_1; int v_2; int v_3; // setlimit, line 164 v_1 = limit - cursor; // tomark, line 164 if (cursor < I_pV) { return false; } cursor = I_pV; v_2 = limit_backward; limit_backward = cursor; cursor = limit - v_1; // (, line 164 // [, line 165 ket = cursor; // substring, line 165 among_var = find_among_b(a_4, 94); if (among_var == 0) { limit_backward = v_2; return false; } // ], line 165 bra = cursor; switch (among_var) { case 0: limit_backward = v_2; return false; case 1: // (, line 200 // or, line 200 lab0: do { v_3 = limit - cursor; lab1: do { if (!(out_grouping_b(g_v, 97, 259))) { break lab1; } break lab0; } while (false);
[ " cursor = limit - v_3;" ]
3,016
lcc
java
null
b20a8d2aec9be1407977fc8294fc849403fe93cc367f38d6
package lcm.spy; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; import javax.swing.tree.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import java.util.jar.*; import java.util.zip.*; import lcm.util.*; import java.lang.reflect.*; import lcm.lcm.*; /** Spy main class. **/ public class Spy { JFrame jf; LCM lcm; JDesktopPane jdp; LCMTypeDatabase handlers; HashMap<String, ChannelData> channelMap = new HashMap<String, ChannelData>(); ArrayList<ChannelData> channelList = new ArrayList<ChannelData>(); ChannelTableModel _channelTableModel = new ChannelTableModel(); TableSorter channelTableModel = new TableSorter(_channelTableModel); JTable channelTable = new JTable(channelTableModel); ArrayList<SpyPlugin> plugins = new ArrayList<SpyPlugin>(); JButton clearButton = new JButton("Clear"); public Spy(String lcmurl) throws IOException { jf = new JFrame("LCM Spy"); jdp = new JDesktopPane(); jdp.setBackground(new Color(0, 0, 160)); jf.setLayout(new BorderLayout()); jf.add(jdp, BorderLayout.CENTER); jf.setSize(1024, 768); jf.setVisible(true); // sortedChannelTableModel.addMouseListenerToHeaderInTable(channelTable); channelTableModel.setTableHeader(channelTable.getTableHeader()); channelTableModel.setSortingStatus(0, TableSorter.ASCENDING); handlers = new LCMTypeDatabase(); TableColumnModel tcm = channelTable.getColumnModel(); tcm.getColumn(0).setMinWidth(140); tcm.getColumn(1).setMinWidth(140); tcm.getColumn(2).setMaxWidth(100); tcm.getColumn(3).setMaxWidth(100); tcm.getColumn(4).setMaxWidth(100); tcm.getColumn(5).setMaxWidth(100); tcm.getColumn(6).setMaxWidth(100); JInternalFrame jif = new JInternalFrame("Channels", true); jif.setLayout(new BorderLayout()); jif.add(channelTable.getTableHeader(), BorderLayout.PAGE_START); // XXX weird bug, if clearButton is added after JScrollPane, we get an error. jif.add(clearButton, BorderLayout.SOUTH); jif.add(new JScrollPane(channelTable), BorderLayout.CENTER); jif.setSize(800,600); jif.setVisible(true); jdp.add(jif); if(null == lcmurl) lcm = new LCM(); else lcm = new LCM(lcmurl); lcm.subscribeAll(new MySubscriber()); new HzThread().start(); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { channelMap.clear(); channelList.clear(); channelTableModel.fireTableDataChanged(); } }); channelTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int mods=e.getModifiersEx(); if (e.getButton()==3) { showPopupMenu(e); } else if (e.getClickCount() == 2) { Point p = e.getPoint(); int row = rowAtPoint(p); ChannelData cd = channelList.get(row); boolean got_one = false; for (SpyPlugin plugin : plugins) { if (!got_one && plugin.canHandle(cd.fingerprint)) { plugin.getAction(jdp, cd).actionPerformed(null); got_one = true; } } if (!got_one) createViewer(channelList.get(row)); } } }); jf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.out.println("Spy quitting"); System.exit(0); } }); ClassDiscoverer.findClasses(new PluginClassVisitor()); System.out.println("Found "+plugins.size()+" plugins"); for (SpyPlugin plugin : plugins) { System.out.println(" "+plugin); } } class PluginClassVisitor implements ClassDiscoverer.ClassVisitor { public void classFound(String jar, Class cls) { Class interfaces[] = cls.getInterfaces(); for (Class iface : interfaces) { if (iface.equals(SpyPlugin.class)) { try { Constructor c = cls.getConstructor(new Class[0]); SpyPlugin plugin = (SpyPlugin) c.newInstance(new Object[0]); plugins.add(plugin); } catch (Exception ex) { System.out.println("ex: "+ex); } } } } } void createViewer(ChannelData cd) { if (cd.viewerFrame != null && !cd.viewerFrame.isVisible()) { cd.viewerFrame.dispose(); cd.viewer = null; } if (cd.viewer == null) { cd.viewerFrame = new JInternalFrame(cd.name, true, true); cd.viewer = new ObjectPanel(cd.name); cd.viewer.setObject(cd.last); // cd.viewer = new ObjectViewer(cd.name, cd.cls, null); cd.viewerFrame.setLayout(new BorderLayout()); cd.viewerFrame.add(new JScrollPane(cd.viewer), BorderLayout.CENTER); jdp.add(cd.viewerFrame); cd.viewerFrame.setSize(500,400); cd.viewerFrame.setVisible(true); } else { cd.viewerFrame.setVisible(true); cd.viewerFrame.moveToFront(); } } static final long utime_now() { return System.nanoTime()/1000; } class ChannelTableModel extends AbstractTableModel { public int getColumnCount() { return 8; } public int getRowCount() { return channelList.size(); } public Object getValueAt(int row, int col) { ChannelData cd = channelList.get(row); if (cd == null) return ""; switch (col) { case 0: return cd.name; case 1: if (cd.cls == null) return String.format("?? %016x", cd.fingerprint); String s = cd.cls.getName(); return s.substring(s.lastIndexOf('.')+1); case 2: return ""+cd.nreceived; case 3: return String.format("%6.2f", cd.hz); case 4: return String.format("%6.2f ms",1000.0/cd.hz); // cd.max_interval/1000.0); case 5: return String.format("%6.2f ms",(cd.max_interval - cd.min_interval)/1000.0); case 6: return String.format("%6.2f KB/s", (cd.bandwidth/1024.0)); case 7: return ""+cd.nerrors; } return "???"; } public String getColumnName(int col) { switch (col) { case 0: return "Channel"; case 1: return "Type"; case 2: return "Num Msgs"; case 3: return "Hz"; case 4: return "1/Hz"; case 5: return "Jitter"; case 6: return "Bandwidth"; case 7: return "Undecodable"; } return "???"; } } class MySubscriber implements LCMSubscriber { public void messageReceived(LCM lcm, String channel, LCMDataInputStream dins) { Object o = null; ChannelData cd = channelMap.get(channel); int msg_size = 0; try { msg_size = dins.available(); long fingerprint = (msg_size >=8) ? dins.readLong() : -1; dins.reset(); Class cls = handlers.getClassByFingerprint(fingerprint);
[ " if (cd == null) {" ]
583
lcc
java
null
e537367e5f1862611742bd63b5d29acacd7963cc58c3c0ac
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016-2017, Yanis Guenane <yanis+ansible@guenane.org> # Copyright: (c) 2017, Markus Teufelberger <mteufelberger+ansible@mgit.at> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: openssl_certificate_info version_added: '2.8' short_description: Provide information of OpenSSL X.509 certificates description: - This module allows one to query information on OpenSSL certificates. - It uses the pyOpenSSL or cryptography python library to interact with OpenSSL. If both the cryptography and PyOpenSSL libraries are available (and meet the minimum version requirements) cryptography will be preferred as a backend over PyOpenSSL (unless the backend is forced with C(select_crypto_backend)). Please note that the PyOpenSSL backend was deprecated in Ansible 2.9 and will be removed in Ansible 2.13. requirements: - PyOpenSSL >= 0.15 or cryptography >= 1.6 author: - Felix Fontein (@felixfontein) - Yanis Guenane (@Spredzy) - Markus Teufelberger (@MarkusTeufelberger) options: path: description: - Remote absolute path where the certificate file is loaded from. - Either I(path) or I(content) must be specified, but not both. type: path content: description: - Content of the X.509 certificate in PEM format. - Either I(path) or I(content) must be specified, but not both. type: str version_added: "2.10" valid_at: description: - A dict of names mapping to time specifications. Every time specified here will be checked whether the certificate is valid at this point. See the C(valid_at) return value for informations on the result. - Time can be specified either as relative time or as absolute timestamp. - Time will always be interpreted as UTC. - Valid format is C([+-]timespec | ASN.1 TIME) where timespec can be an integer + C([w | d | h | m | s]) (e.g. C(+32w1d2h), and ASN.1 TIME (i.e. pattern C(YYYYMMDDHHMMSSZ)). Note that all timestamps will be treated as being in UTC. type: dict select_crypto_backend: description: - Determines which crypto backend to use. - The default choice is C(auto), which tries to use C(cryptography) if available, and falls back to C(pyopenssl). - If set to C(pyopenssl), will try to use the L(pyOpenSSL,https://pypi.org/project/pyOpenSSL/) library. - If set to C(cryptography), will try to use the L(cryptography,https://cryptography.io/) library. - Please note that the C(pyopenssl) backend has been deprecated in Ansible 2.9, and will be removed in Ansible 2.13. From that point on, only the C(cryptography) backend will be available. type: str default: auto choices: [ auto, cryptography, pyopenssl ] notes: - All timestamp values are provided in ASN.1 TIME format, i.e. following the C(YYYYMMDDHHMMSSZ) pattern. They are all in UTC. seealso: - module: openssl_certificate ''' EXAMPLES = r''' - name: Generate a Self Signed OpenSSL certificate openssl_certificate: path: /etc/ssl/crt/ansible.com.crt privatekey_path: /etc/ssl/private/ansible.com.pem csr_path: /etc/ssl/csr/ansible.com.csr provider: selfsigned # Get information on the certificate - name: Get information on generated certificate openssl_certificate_info: path: /etc/ssl/crt/ansible.com.crt register: result - name: Dump information debug: var: result # Check whether the certificate is valid or not valid at certain times, fail # if this is not the case. The first task (openssl_certificate_info) collects # the information, and the second task (assert) validates the result and # makes the playbook fail in case something is not as expected. - name: Test whether that certificate is valid tomorrow and/or in three weeks openssl_certificate_info: path: /etc/ssl/crt/ansible.com.crt valid_at: point_1: "+1d" point_2: "+3w" register: result - name: Validate that certificate is valid tomorrow, but not in three weeks assert: that: - result.valid_at.point_1 # valid in one day - not result.valid_at.point_2 # not valid in three weeks ''' RETURN = r''' expired: description: Whether the certificate is expired (i.e. C(notAfter) is in the past) returned: success type: bool basic_constraints: description: Entries in the C(basic_constraints) extension, or C(none) if extension is not present. returned: success type: list elements: str sample: "[CA:TRUE, pathlen:1]" basic_constraints_critical: description: Whether the C(basic_constraints) extension is critical. returned: success type: bool extended_key_usage: description: Entries in the C(extended_key_usage) extension, or C(none) if extension is not present. returned: success type: list elements: str sample: "[Biometric Info, DVCS, Time Stamping]" extended_key_usage_critical: description: Whether the C(extended_key_usage) extension is critical. returned: success type: bool extensions_by_oid: description: Returns a dictionary for every extension OID returned: success type: dict contains: critical: description: Whether the extension is critical. returned: success type: bool value: description: The Base64 encoded value (in DER format) of the extension returned: success type: str sample: "MAMCAQU=" sample: '{"1.3.6.1.5.5.7.1.24": { "critical": false, "value": "MAMCAQU="}}' key_usage: description: Entries in the C(key_usage) extension, or C(none) if extension is not present. returned: success type: str sample: "[Key Agreement, Data Encipherment]" key_usage_critical: description: Whether the C(key_usage) extension is critical. returned: success type: bool subject_alt_name: description: Entries in the C(subject_alt_name) extension, or C(none) if extension is not present. returned: success type: list elements: str sample: "[DNS:www.ansible.com, IP:1.2.3.4]" subject_alt_name_critical: description: Whether the C(subject_alt_name) extension is critical. returned: success type: bool ocsp_must_staple: description: C(yes) if the OCSP Must Staple extension is present, C(none) otherwise. returned: success type: bool ocsp_must_staple_critical: description: Whether the C(ocsp_must_staple) extension is critical. returned: success type: bool issuer: description: - The certificate's issuer. - Note that for repeated values, only the last one will be returned. returned: success type: dict sample: '{"organizationName": "Ansible", "commonName": "ca.example.com"}' issuer_ordered: description: The certificate's issuer as an ordered list of tuples. returned: success type: list elements: list sample: '[["organizationName", "Ansible"], ["commonName": "ca.example.com"]]' version_added: "2.9" subject: description: - The certificate's subject as a dictionary. - Note that for repeated values, only the last one will be returned. returned: success type: dict sample: '{"commonName": "www.example.com", "emailAddress": "test@example.com"}' subject_ordered: description: The certificate's subject as an ordered list of tuples. returned: success type: list elements: list sample: '[["commonName", "www.example.com"], ["emailAddress": "test@example.com"]]' version_added: "2.9" not_after: description: C(notAfter) date as ASN.1 TIME returned: success type: str sample: 20190413202428Z not_before: description: C(notBefore) date as ASN.1 TIME returned: success type: str sample: 20190331202428Z public_key: description: Certificate's public key in PEM format returned: success type: str sample: "-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A..." public_key_fingerprints: description: - Fingerprints of certificate's public key. - For every hash algorithm available, the fingerprint is computed. returned: success type: dict sample: "{'sha256': 'd4:b3:aa:6d:c8:04:ce:4e:ba:f6:29:4d:92:a3:94:b0:c2:ff:bd:bf:33:63:11:43:34:0f:51:b0:95:09:2f:63', 'sha512': 'f7:07:4a:f0:b0:f0:e6:8b:95:5f:f9:e6:61:0a:32:68:f1..." signature_algorithm: description: The signature algorithm used to sign the certificate. returned: success type: str sample: sha256WithRSAEncryption serial_number: description: The certificate's serial number. returned: success type: int sample: 1234 version: description: The certificate version. returned: success type: int sample: 3 valid_at: description: For every time stamp provided in the I(valid_at) option, a boolean whether the certificate is valid at that point in time or not. returned: success type: dict subject_key_identifier: description: - The certificate's subject key identifier. - The identifier is returned in hexadecimal, with C(:) used to separate bytes. - Is C(none) if the C(SubjectKeyIdentifier) extension is not present. returned: success and if the pyOpenSSL backend is I(not) used type: str sample: '00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33' version_added: "2.9" authority_key_identifier: description: - The certificate's authority key identifier. - The identifier is returned in hexadecimal, with C(:) used to separate bytes. - Is C(none) if the C(AuthorityKeyIdentifier) extension is not present. returned: success and if the pyOpenSSL backend is I(not) used type: str sample: '00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33' version_added: "2.9" authority_cert_issuer: description: - The certificate's authority cert issuer as a list of general names. - Is C(none) if the C(AuthorityKeyIdentifier) extension is not present. returned: success and if the pyOpenSSL backend is I(not) used type: list elements: str sample: "[DNS:www.ansible.com, IP:1.2.3.4]" version_added: "2.9" authority_cert_serial_number: description: - The certificate's authority cert serial number. - Is C(none) if the C(AuthorityKeyIdentifier) extension is not present. returned: success and if the pyOpenSSL backend is I(not) used type: int sample: '12345' version_added: "2.9" ocsp_uri: description: The OCSP responder URI, if included in the certificate. Will be C(none) if no OCSP responder URI is included. returned: success type: str version_added: "2.9" ''' import abc import binascii import datetime import os import re import traceback from distutils.version import LooseVersion from ansible.module_utils import crypto as crypto_utils from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.six import string_types from ansible.module_utils._text import to_native, to_text, to_bytes from ansible.module_utils.compat import ipaddress as compat_ipaddress MINIMAL_CRYPTOGRAPHY_VERSION = '1.6' MINIMAL_PYOPENSSL_VERSION = '0.15' PYOPENSSL_IMP_ERR = None try: import OpenSSL from OpenSSL import crypto PYOPENSSL_VERSION = LooseVersion(OpenSSL.__version__) if OpenSSL.SSL.OPENSSL_VERSION_NUMBER >= 0x10100000: # OpenSSL 1.1.0 or newer OPENSSL_MUST_STAPLE_NAME = b"tlsfeature" OPENSSL_MUST_STAPLE_VALUE = b"status_request" else: # OpenSSL 1.0.x or older OPENSSL_MUST_STAPLE_NAME = b"1.3.6.1.5.5.7.1.24" OPENSSL_MUST_STAPLE_VALUE = b"DER:30:03:02:01:05" except ImportError: PYOPENSSL_IMP_ERR = traceback.format_exc() PYOPENSSL_FOUND = False else: PYOPENSSL_FOUND = True CRYPTOGRAPHY_IMP_ERR = None try: import cryptography from cryptography import x509 from cryptography.hazmat.primitives import serialization CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__) except ImportError: CRYPTOGRAPHY_IMP_ERR = traceback.format_exc() CRYPTOGRAPHY_FOUND = False else: CRYPTOGRAPHY_FOUND = True TIMESTAMP_FORMAT = "%Y%m%d%H%M%SZ" class CertificateInfo(crypto_utils.OpenSSLObject): def __init__(self, module, backend): super(CertificateInfo, self).__init__( module.params['path'] or '', 'present', False, module.check_mode, ) self.backend = backend self.module = module self.content = module.params['content'] if self.content is not None: self.content = self.content.encode('utf-8') self.valid_at = module.params['valid_at'] if self.valid_at: for k, v in self.valid_at.items(): if not isinstance(v, string_types): self.module.fail_json( msg='The value for valid_at.{0} must be of type string (got {1})'.format(k, type(v)) ) self.valid_at[k] = crypto_utils.get_relative_time_option(v, 'valid_at.{0}'.format(k)) def generate(self): # Empty method because crypto_utils.OpenSSLObject wants this pass def dump(self): # Empty method because crypto_utils.OpenSSLObject wants this pass @abc.abstractmethod def _get_signature_algorithm(self): pass @abc.abstractmethod def _get_subject_ordered(self): pass @abc.abstractmethod def _get_issuer_ordered(self): pass @abc.abstractmethod def _get_version(self): pass @abc.abstractmethod def _get_key_usage(self): pass @abc.abstractmethod def _get_extended_key_usage(self): pass @abc.abstractmethod def _get_basic_constraints(self): pass @abc.abstractmethod def _get_ocsp_must_staple(self): pass @abc.abstractmethod def _get_subject_alt_name(self): pass @abc.abstractmethod def _get_not_before(self): pass @abc.abstractmethod def _get_not_after(self): pass @abc.abstractmethod def _get_public_key(self, binary): pass @abc.abstractmethod def _get_subject_key_identifier(self): pass @abc.abstractmethod def _get_authority_key_identifier(self): pass @abc.abstractmethod def _get_serial_number(self): pass @abc.abstractmethod def _get_all_extensions(self): pass @abc.abstractmethod def _get_ocsp_uri(self): pass def get_info(self): result = dict() self.cert = crypto_utils.load_certificate(self.path, content=self.content, backend=self.backend) result['signature_algorithm'] = self._get_signature_algorithm() subject = self._get_subject_ordered() issuer = self._get_issuer_ordered() result['subject'] = dict() for k, v in subject: result['subject'][k] = v result['subject_ordered'] = subject result['issuer'] = dict() for k, v in issuer: result['issuer'][k] = v result['issuer_ordered'] = issuer result['version'] = self._get_version() result['key_usage'], result['key_usage_critical'] = self._get_key_usage() result['extended_key_usage'], result['extended_key_usage_critical'] = self._get_extended_key_usage() result['basic_constraints'], result['basic_constraints_critical'] = self._get_basic_constraints() result['ocsp_must_staple'], result['ocsp_must_staple_critical'] = self._get_ocsp_must_staple() result['subject_alt_name'], result['subject_alt_name_critical'] = self._get_subject_alt_name() not_before = self._get_not_before() not_after = self._get_not_after() result['not_before'] = not_before.strftime(TIMESTAMP_FORMAT) result['not_after'] = not_after.strftime(TIMESTAMP_FORMAT) result['expired'] = not_after < datetime.datetime.utcnow() result['valid_at'] = dict() if self.valid_at: for k, v in self.valid_at.items(): result['valid_at'][k] = not_before <= v <= not_after result['public_key'] = self._get_public_key(binary=False) pk = self._get_public_key(binary=True) result['public_key_fingerprints'] = crypto_utils.get_fingerprint_of_bytes(pk) if pk is not None else dict() if self.backend != 'pyopenssl': ski = self._get_subject_key_identifier() if ski is not None: ski = to_native(binascii.hexlify(ski)) ski = ':'.join([ski[i:i + 2] for i in range(0, len(ski), 2)]) result['subject_key_identifier'] = ski aki, aci, acsn = self._get_authority_key_identifier() if aki is not None: aki = to_native(binascii.hexlify(aki)) aki = ':'.join([aki[i:i + 2] for i in range(0, len(aki), 2)]) result['authority_key_identifier'] = aki result['authority_cert_issuer'] = aci result['authority_cert_serial_number'] = acsn result['serial_number'] = self._get_serial_number() result['extensions_by_oid'] = self._get_all_extensions() result['ocsp_uri'] = self._get_ocsp_uri() return result class CertificateInfoCryptography(CertificateInfo): """Validate the supplied cert, using the cryptography backend""" def __init__(self, module): super(CertificateInfoCryptography, self).__init__(module, 'cryptography') def _get_signature_algorithm(self): return crypto_utils.cryptography_oid_to_name(self.cert.signature_algorithm_oid) def _get_subject_ordered(self): result = [] for attribute in self.cert.subject: result.append([crypto_utils.cryptography_oid_to_name(attribute.oid), attribute.value]) return result def _get_issuer_ordered(self): result = [] for attribute in self.cert.issuer: result.append([crypto_utils.cryptography_oid_to_name(attribute.oid), attribute.value]) return result def _get_version(self): if self.cert.version == x509.Version.v1: return 1 if self.cert.version == x509.Version.v3: return 3 return "unknown" def _get_key_usage(self): try: current_key_ext = self.cert.extensions.get_extension_for_class(x509.KeyUsage) current_key_usage = current_key_ext.value key_usage = dict( digital_signature=current_key_usage.digital_signature, content_commitment=current_key_usage.content_commitment, key_encipherment=current_key_usage.key_encipherment, data_encipherment=current_key_usage.data_encipherment, key_agreement=current_key_usage.key_agreement, key_cert_sign=current_key_usage.key_cert_sign, crl_sign=current_key_usage.crl_sign, encipher_only=False, decipher_only=False, ) if key_usage['key_agreement']: key_usage.update(dict( encipher_only=current_key_usage.encipher_only, decipher_only=current_key_usage.decipher_only )) key_usage_names = dict( digital_signature='Digital Signature', content_commitment='Non Repudiation', key_encipherment='Key Encipherment', data_encipherment='Data Encipherment', key_agreement='Key Agreement', key_cert_sign='Certificate Sign', crl_sign='CRL Sign', encipher_only='Encipher Only', decipher_only='Decipher Only', ) return sorted([ key_usage_names[name] for name, value in key_usage.items() if value ]), current_key_ext.critical except cryptography.x509.ExtensionNotFound: return None, False def _get_extended_key_usage(self): try: ext_keyusage_ext = self.cert.extensions.get_extension_for_class(x509.ExtendedKeyUsage) return sorted([ crypto_utils.cryptography_oid_to_name(eku) for eku in ext_keyusage_ext.value ]), ext_keyusage_ext.critical except cryptography.x509.ExtensionNotFound: return None, False def _get_basic_constraints(self): try: ext_keyusage_ext = self.cert.extensions.get_extension_for_class(x509.BasicConstraints) result = [] result.append('CA:{0}'.format('TRUE' if ext_keyusage_ext.value.ca else 'FALSE')) if ext_keyusage_ext.value.path_length is not None: result.append('pathlen:{0}'.format(ext_keyusage_ext.value.path_length)) return sorted(result), ext_keyusage_ext.critical except cryptography.x509.ExtensionNotFound: return None, False def _get_ocsp_must_staple(self): try: try: # This only works with cryptography >= 2.1 tlsfeature_ext = self.cert.extensions.get_extension_for_class(x509.TLSFeature) value = cryptography.x509.TLSFeatureType.status_request in tlsfeature_ext.value except AttributeError as dummy: # Fallback for cryptography < 2.1 oid = x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.1.24") tlsfeature_ext = self.cert.extensions.get_extension_for_oid(oid) value = tlsfeature_ext.value.value == b"\x30\x03\x02\x01\x05" return value, tlsfeature_ext.critical except cryptography.x509.ExtensionNotFound: return None, False def _get_subject_alt_name(self): try: san_ext = self.cert.extensions.get_extension_for_class(x509.SubjectAlternativeName) result = [crypto_utils.cryptography_decode_name(san) for san in san_ext.value] return result, san_ext.critical except cryptography.x509.ExtensionNotFound: return None, False def _get_not_before(self): return self.cert.not_valid_before def _get_not_after(self): return self.cert.not_valid_after def _get_public_key(self, binary): return self.cert.public_key().public_bytes( serialization.Encoding.DER if binary else serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo ) def _get_subject_key_identifier(self): try: ext = self.cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) return ext.value.digest except cryptography.x509.ExtensionNotFound: return None def _get_authority_key_identifier(self): try: ext = self.cert.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier) issuer = None if ext.value.authority_cert_issuer is not None: issuer = [crypto_utils.cryptography_decode_name(san) for san in ext.value.authority_cert_issuer] return ext.value.key_identifier, issuer, ext.value.authority_cert_serial_number except cryptography.x509.ExtensionNotFound: return None, None, None def _get_serial_number(self): return self.cert.serial_number def _get_all_extensions(self): return crypto_utils.cryptography_get_extensions_from_cert(self.cert) def _get_ocsp_uri(self): try: ext = self.cert.extensions.get_extension_for_class(x509.AuthorityInformationAccess) for desc in ext.value: if desc.access_method == x509.oid.AuthorityInformationAccessOID.OCSP: if isinstance(desc.access_location, x509.UniformResourceIdentifier): return desc.access_location.value except x509.ExtensionNotFound as dummy: pass return None class CertificateInfoPyOpenSSL(CertificateInfo): """validate the supplied certificate.""" def __init__(self, module): super(CertificateInfoPyOpenSSL, self).__init__(module, 'pyopenssl') def _get_signature_algorithm(self): return to_text(self.cert.get_signature_algorithm()) def __get_name(self, name): result = [] for sub in name.get_components(): result.append([crypto_utils.pyopenssl_normalize_name(sub[0]), to_text(sub[1])]) return result def _get_subject_ordered(self): return self.__get_name(self.cert.get_subject()) def _get_issuer_ordered(self): return self.__get_name(self.cert.get_issuer()) def _get_version(self): # Version numbers in certs are off by one: # v1: 0, v2: 1, v3: 2 ... return self.cert.get_version() + 1 def _get_extension(self, short_name): for extension_idx in range(0, self.cert.get_extension_count()): extension = self.cert.get_extension(extension_idx) if extension.get_short_name() == short_name: result = [ crypto_utils.pyopenssl_normalize_name(usage.strip()) for usage in to_text(extension, errors='surrogate_or_strict').split(',') ]
[ " return sorted(result), bool(extension.get_critical())" ]
2,179
lcc
python
null
71ce6181e5bc2ca033a59fff909ae4682cbb94f61145ba04
#!/usr/bin/python # # Copyright (C) 2009-2012 Paul Davis # # 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., 675 Mass Ave, Cambridge, MA 02139, USA. # # # This file generates the header signals_generated.h, which # will be put in build/libs/pbd/pbd by waf. # # It is probably easier to read build/libs/pbd/pbd/signals_generated.h # than this if you want to read the code! # from __future__ import print_function import sys if len(sys.argv) < 2: print('Syntax: %s <path>' % sys.argv[0]) sys.exit(1) f = open(sys.argv[1], 'w') print("/** THIS FILE IS AUTOGENERATED by signals.py: CHANGES WILL BE LOST */\n", file=f) # Produce a comma-separated string from a list of substrings, # giving an optional prefix to each substring def comma_separated(n, prefix = ""): r = "" for i in range(0, len(n)): if i > 0: r += ", " r += "%s%s" % (prefix, n[i]) return r # Generate one SignalN class definition # @param f File to write to # @param n Number of parameters # @param v True to specialize the template for a void return type def signal(f, n, v): # The parameters in the form A1, A2, A3, ... An = [] for i in range(0, n): An.append("A%d" % (i + 1)) # The parameters in the form A1 a1, A2 a2, A3 a3, ... Anan = [] for a in An: Anan.append('%s %s' % (a, a.lower())) # The parameters in the form a1, a2, a3, ... an = [] for a in An: an.append(a.lower()) # If the template is fully specialized, use of typename SomeTypedef::iterator is illegal # in c++03 (should use just SomeTypedef::iterator) [although use of typename is ok in c++0x] # http://stackoverflow.com/questions/6076015/typename-outside-of-template if n == 0 and v: typename = "" else: typename = "typename " if v: print("/** A signal with %d parameters (specialisation for a void return) */" % n, file=f) else: print("/** A signal with %d parameters */" % n, file=f) if v: print("template <%s>" % comma_separated(An, "typename "), file=f) print("class Signal%d<%s> : public SignalBase" % (n, comma_separated(["void"] + An)), file=f) else: print("template <%s>" % comma_separated(["R"] + An + ["C = OptionalLastValue<R> "], "typename "), file=f) print("class Signal%d : public SignalBase" % n, file=f) print("{", file=f) print("public:", file=f) print("", file=f) if v: print("\ttypedef boost::function<void(%s)> slot_function_type;" % comma_separated(An), file=f) print("\ttypedef void result_type;", file=f) else: print("\ttypedef boost::function<R(%s)> slot_function_type;" % comma_separated(An), file=f) print("\ttypedef boost::optional<R> result_type;", file=f) print("", file=f) print("private:", file=f) print(""" /** The slots that this signal will call on emission */ typedef std::map<boost::shared_ptr<Connection>, slot_function_type> Slots; Slots _slots; """, file=f) print("public:", file=f) print("", file=f) print("\t~Signal%d () {" % n, file=f) print("\t\tboost::mutex::scoped_lock lm (_mutex);", file=f) print("\t\t/* Tell our connection objects that we are going away, so they don't try to call us */", file=f) print("\t\tfor (%sSlots::iterator i = _slots.begin(); i != _slots.end(); ++i) {" % typename, file=f) print("\t\t\ti->first->signal_going_away ();", file=f) print("\t\t}", file=f) print("\t}", file=f) print("", file=f) if n == 0: p = "" q = "" else: p = ", %s" % comma_separated(Anan) q = ", %s" % comma_separated(an) print("\tstatic void compositor (%sboost::function<void(%s)> f, EventLoop* event_loop, EventLoop::InvalidationRecord* ir%s) {" % (typename, comma_separated(An), p), file=f) print("\t\tevent_loop->call_slot (ir, boost::bind (f%s));" % q, file=f) print("\t}", file=f) print(""" /** Arrange for @a slot to be executed whenever this signal is emitted. Store the connection that represents this arrangement in @a c. NOTE: @a slot will be executed in the same thread that the signal is emitted in. */ void connect_same_thread (ScopedConnection& c, const slot_function_type& slot) { c = _connect (slot); } /** Arrange for @a slot to be executed whenever this signal is emitted. Add the connection that represents this arrangement to @a clist. NOTE: @a slot will be executed in the same thread that the signal is emitted in. */ void connect_same_thread (ScopedConnectionList& clist, const slot_function_type& slot) { clist.add_connection (_connect (slot)); } /** Arrange for @a slot to be executed in the context of @a event_loop whenever this signal is emitted. Add the connection that represents this arrangement to @a clist. If the event loop/thread in which @a slot will be executed will outlive the lifetime of any object referenced in @a slot, then an InvalidationRecord should be passed, allowing any request sent to the @a event_loop and not executed before the object is destroyed to be marked invalid. "outliving the lifetime" doesn't have a specific, detailed meaning, but is best illustrated by two contrasting examples: 1) the main GUI event loop/thread - this will outlive more or less all objects in the application, and thus when arranging for @a slot to be called in that context, an invalidation record is highly advisable. 2) a secondary event loop/thread which will be destroyed along with the objects that are typically referenced by @a slot. Assuming that the event loop is stopped before the objects are destroyed, there is no reason to pass in an invalidation record, and MISSING_INVALIDATOR may be used. */ void connect (ScopedConnectionList& clist, PBD::EventLoop::InvalidationRecord* ir, const slot_function_type& slot, PBD::EventLoop* event_loop) { if (ir) { ir->event_loop = event_loop; } """, file=f) u = [] for i in range(0, n): u.append("_%d" % (i + 1)) if n == 0: p = "" else: p = ", %s" % comma_separated(u) print("\t\tclist.add_connection (_connect (boost::bind (&compositor, slot, event_loop, ir%s)));" % p, file=f) print(""" } /** See notes for the ScopedConnectionList variant of this function. This * differs in that it stores the connection to the signal in a single * ScopedConnection rather than a ScopedConnectionList. */ void connect (ScopedConnection& c, PBD::EventLoop::InvalidationRecord* ir, const slot_function_type& slot, PBD::EventLoop* event_loop) { if (ir) { ir->event_loop = event_loop; } """, file=f) print("\t\tc = _connect (boost::bind (&compositor, slot, event_loop, ir%s));" % p, file=f) print("\t}", file=f) print(""" /** Emit this signal. This will cause all slots connected to it be executed in the order that they were connected (cross-thread issues may alter the precise execution time of cross-thread slots). */ """, file=f) if v: print("\tvoid operator() (%s)" % comma_separated(Anan), file=f) else: print("\ttypename C::result_type operator() (%s)" % comma_separated(Anan), file=f) print("\t{", file=f) print("\t\t/* First, take a copy of our list of slots as it is now */", file=f) print("", file=f) print("\t\tSlots s;", file=f) print("\t\t{", file=f) print("\t\t\tboost::mutex::scoped_lock lm (_mutex);", file=f) print("\t\t\ts = _slots;", file=f) print("\t\t}", file=f) print("", file=f) if not v: print("\t\tstd::list<R> r;", file=f) print("\t\tfor (%sSlots::iterator i = s.begin(); i != s.end(); ++i) {" % typename, file=f) print(""" /* We may have just called a slot, and this may have resulted in disconnection of other slots from us. The list copy means that this won't cause any problems with invalidated iterators, but we must check to see if the slot we are about to call is still on the list. */ bool still_there = false; { boost::mutex::scoped_lock lm (_mutex);
[ "\t\t\t\tstill_there = _slots.find (i->first) != _slots.end ();" ]
1,211
lcc
python
null
aa8714d821c58b0cafe396b92312a4fe03c223fb64a901a3
# (C) 2009 Frank-Rene Schaefer """ ABSTRACT: !! UTF16 state split is similar to UTF8 state split as shown in file !! !! "uf8_state_split.py". Please, read the documentation there about !! !! the details of the basic idea. !! Due to the fact that utf16 conversion has only two possible byte sequence lengths, 2 and 4 bytes, the state split process is significantly easier than the utf8 state split. The principle idea remains: A single transition from state A to state B is translated (sometimes) into an intermediate state transition to reflect that the unicode point is represent by a value sequence. The special case utf16 again is easier, since, for any unicode point <= 0xFFFF the representation value remains exactly the same, thus those intervals do not have to be adapted at all! Further, the identification of 'contigous' intervals where the last value runs repeatedly from min to max is restricted to the consideration of a single word. UTF16 character codes can contain at max two values (a 'surrogate pair') coded in two 'words' (1 word = 2 bytes). The overun happens every 2*10 code points. Since such intervals are pretty large and the probability that a range runs over multiple such ranges is low, it does not make sense to try to combine them. The later Hopcroft Minimization will not be overwhelmed by a little extra work. """ import os import sys sys.path.append(os.environ["QUEX_PATH"]) from quex.engine.utf16 import utf16_to_unicode, unicode_to_utf16 from quex.engine.interval_handling import Interval, NumberSet import quex.engine.state_machine.algorithm.beautifier as beautifier ForbiddenRange = Interval(0xD800, 0xE000) def do(sm): global ForbiddenRange state_list = sm.states.items() for state_index, state in state_list: # Get the 'transition_list', i.e. a list of pairs (TargetState, NumberSet) # which indicates what target state is reached via what number set. transition_list = state.target_map.get_map().items() # Clear the state's transitions, now. This way it can absorb new # transitions to intermediate states. state.target_map.clear() # Loop over all transitions for target_state_index, number_set in transition_list: # -- 1st check whether a modification is necessary if number_set.supremum() <= 0x10000: sm.states[state_index].add_transition(number_set, target_state_index) continue # -- We help: General regular expressions may not bother with # the 'ForbiddenRange'. Let us be so kind and cut it here. number_set.subtract(ForbiddenRange) number_set.cut_lesser(0) number_set.cut_greater_or_equal(0x110000) # -- Add intermediate States # We take the intervals with 'PromiseToTreatWellF' even though they # are changed. This is because the intervals would be lost anyway # after the state split, so we use the same memory and do not # cause a time consuming memory copy and constructor calls. interval_list = number_set.get_intervals(PromiseToTreatWellF=True) for interval in interval_list: create_intermediate_states(sm, state_index, target_state_index, interval) result = beautifier.do(sm) return result def do_set(NSet): """Unicode values > 0xFFFF are translated into byte sequences, thus, only number sets below that value can be transformed into number sets. They, actually remain the same. """ for interval in NSet.get_intervals(PromiseToTreatWellF=True): if interval.end > 0x10000: return None return NSet def homogeneous_chunk_n_per_character(CharacterSet): """If all characters in a unicode character set state machine require the same number of bytes to be represented this number is returned. Otherwise, 'None' is returned. RETURNS: N > 0 number of bytes required to represent any character in the given state machine. None characters in the state machine require different numbers of bytes. """ assert isinstance(CharacterSet, NumberSet) interval_list = CharacterSet.get_intervals(PromiseToTreatWellF=True) front = interval_list[0].begin # First element of number set back = interval_list[-1].end - 1 # Last element of number set # Determine number of bytes required to represent the first and the # last character of the number set. The number of bytes per character # increases monotonously, so only borders have to be considered. front_chunk_n = len(unicode_to_utf16(front)) back_chunk_n = len(unicode_to_utf16(back)) if front_chunk_n != back_chunk_n: return None else: return front_chunk_n def create_intermediate_states(sm, StartStateIdx, EndStateIdx, X): # Split the interval into a range below and above 0xFFFF. This corresponds # unicode values that are represented in utf16 via 2 and 4 bytes (1 and 2 words). interval_1word, intervals_2word = get_contigous_intervals(X) if interval_1word is not None: sm.add_transition(StartStateIdx, interval_1word, EndStateIdx) if intervals_2word is not None: for interval in intervals_2word: # Introduce intermediate state trigger_seq = get_trigger_sequence_for_interval(interval) s_idx = sm.add_transition(StartStateIdx, trigger_seq[0]) sm.add_transition(s_idx, trigger_seq[1], EndStateIdx) def get_contigous_intervals(X): """Split Unicode interval into intervals where all values have the same utf16-byte sequence length. This is fairly simple in comparison with utf8-byte sequence length: There are only two lengths: 2 bytes and 2 x 2 bytes. RETURNS: [X0, List1] X0 = the sub-interval where all values are 1 word (2 byte) utf16 encoded. None => No such interval List1 = list of contigous sub-intervals where coded as 2 words. None => No such intervals """ global ForbiddenRange if X.begin == -sys.maxint: X.begin = 0 if X.end == sys.maxint: X.end = 0x110000 assert X.end != X.begin # Empty intervals are nonsensical assert X.end <= 0x110000 # Interval must lie in unicode range assert not X.check_overlap(ForbiddenRange) # The 'forbidden range' is not to be covered. if X.end <= 0x10000: return [X, None] elif X.begin >= 0x10000: return [None, split_contigous_intervals_for_surrogates(X.begin, X.end)] else: return [Interval(X.begin, 0x10000), split_contigous_intervals_for_surrogates(0x10000, X.end)] def split_contigous_intervals_for_surrogates(Begin, End): """Splits the interval X into sub interval so that no interval runs over a 'surrogate' border of the last word. For that, it is simply checked if the End falls into the same 'surrogate' domain of 'front' (start value of front = Begin). If it does not an interval [front, end_of_domain) is split up and front is set to end of domain. This procedure repeats until front and End lie in the same domain. """ global ForbiddenRange assert Begin >= 0x10000 assert End <= 0x110000 assert End > Begin front_seq = unicode_to_utf16(Begin) back_seq = unicode_to_utf16(End - 1) # (*) First word is the same. # Then, # -- it is either a one word character. # -- it is a range of two word characters, but the range # extends in one contigous range in the second surrogate. # In both cases, the interval is contigous. if front_seq[0] == back_seq[0]: return [Interval(Begin, End)] # (*) First word is NOT the same # Separate into three domains: # # (1) Interval from Begin until second surrogate hits border 0xE000 # (2) Interval where the first surrogate inreases while second # surrogate iterates over [0xDC00, 0xDFFF] # (3) Interval from begin of last surrogate border to End result = [] end = utf16_to_unicode([front_seq[0], ForbiddenRange.end - 1]) + 1 # (1) 'Begin' until second surrogate hits border 0xE000 # (The following **must** hold according to entry condition about # front and back sequence.) assert End > end result.append(Interval(Begin, end)) if front_seq[0] + 1 != back_seq[0]: # (2) Second surrogate iterates over [0xDC00, 0xDFFF] mid_end = utf16_to_unicode([back_seq[0] - 1, ForbiddenRange.end - 1]) + 1 # (The following **must** hold according to entry condition about # front and back sequence.) assert mid_end > end result.append(Interval(end, mid_end)) end = mid_end # (3) Last surrogate border to End if End > end: result.append(Interval(end, End)) return result def get_trigger_sequence_for_interval(X): # The interval either lies entirely >= 0x10000 or entirely < 0x10000 assert X.begin >= 0x10000 or X.end < 0x10000 # An interval below < 0x10000 remains the same if X.end < 0x10000: return [ X ] # In case that the interval >= 0x10000 it the value is split up into # two values.
[ " front_seq = unicode_to_utf16(X.begin)" ]
1,192
lcc
python
null
b7aaf348eef474fc39a51484be57ea00820973ab5749b1cb
/*---------------------------------------------------------------------------*\ Compiler Generator Coco/R, Copyright (c) 1990, 2004 Hanspeter Moessenboeck, University of Linz extended by M. Loeberbauer & A. Woess, Univ. of Linz with improvements by Pat Terry, Rhodes University ------------------------------------------------------------------------------- License This file is part of Compiler Generator Coco/R 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, 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. As an exception, it is allowed to write an extension of Coco/R that is used as a plugin in non-free software. If not otherwise stated, any source code generated by Coco/R (other than Coco/R itself) does not fall under the GNU General Public License. \*---------------------------------------------------------------------------*/ // This file was generated with Coco/R C#, version: 20101106 using System.IO; using System; namespace at.jku.ssw.Coco { // ---------------------------------------------------------------------------- // Parser // ---------------------------------------------------------------------------- //! A Coco/R Parser public class Parser { public const int _EOF = 0; public const int _ident = 1; public const int _number = 2; public const int _string = 3; public const int _badString = 4; public const int _char = 5; public const int maxT = 43; //<! max term (w/o pragmas) public const int _ddtSym = 44; public const int _directive = 45; const bool T = true; const bool x = false; const int minErrDist = 2; public Scanner scanner; public Errors errors; public Token t; //!< last recognized token public Token la; //!< lookahead token int errDist = minErrDist; const int isIdent = 0; const int isLiteral = 1; public Tab tab; // other Coco objects referenced in this ATG public DFA dfa; public ParserGen pgen; bool genScanner = false; string tokenString; // used in declarations of literal tokens string noString = "-none-"; // used in declarations of literal tokens /*-------------------------------------------------------------------------*/ public Parser(Scanner scanner) { this.scanner = scanner; errors = new Errors(); } void SynErr (int n) { if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n); errDist = 0; } public void SemErr (string msg) { if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg); errDist = 0; } void Get () { for (;;) { t = la; la = scanner.Scan(); if (la.kind <= maxT) { ++errDist; break; } if (la.kind == 44) { tab.SetDDT(la.val); } if (la.kind == 45) { tab.DispatchDirective(la.val); } la = t; } } void Expect (int n) { if (la.kind==n) Get(); else { SynErr(n); } } bool StartOf (int s) { return set[s, la.kind]; } void ExpectWeak (int n, int follow) { if (la.kind == n) Get(); else { SynErr(n); while (!StartOf(follow)) Get(); } } bool WeakSeparator(int n, int syFol, int repFol) { int kind = la.kind; if (kind == n) {Get(); return true;} else if (StartOf(repFol)) {return false;} else { SynErr(n); while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) { Get(); kind = la.kind; } return StartOf(syFol); } } void Coco() { Symbol sym; Graph g; string grammarName; CharSet s; if (la.kind == 6) { Get(); int beg = t.pos + t.val.Length; while (StartOf(1)) { Get(); } tab.copyPos = new Position(beg, la.pos, 0); Expect(7); } if (StartOf(2)) { Get(); int beg = t.pos; while (StartOf(3)) { Get(); } pgen.preamblePos = new Position(beg, la.pos, 0); } Expect(8); genScanner = true; Expect(1); grammarName = t.val; if (StartOf(4)) { Get(); int beg = t.pos; while (StartOf(4)) { Get(); } pgen.semDeclPos = new Position(beg, la.pos, 0); } if (la.kind == 9) { Get(); dfa.ignoreCase = true; } if (la.kind == 10) { Get(); while (la.kind == 1) { SetDecl(); } } if (la.kind == 11) { Get(); while (la.kind == 1 || la.kind == 3 || la.kind == 5) { TokenDecl(Node.t); } } if (la.kind == 12) { Get(); while (la.kind == 1 || la.kind == 3 || la.kind == 5) { TokenDecl(Node.pr); } } while (la.kind == 13) { Get(); Graph g1, g2; bool nested = false; Expect(14); TokenExpr(out g1); Expect(15); TokenExpr(out g2); if (la.kind == 16) { Get(); nested = true; } dfa.NewComment(g1.l, g2.l, nested); } while (la.kind == 17) { Get(); Set(out s); tab.ignored.Or(s); } while (!(la.kind == 0 || la.kind == 18)) {SynErr(44); Get();} Expect(18); if (genScanner) dfa.MakeDeterministic(); tab.DeleteNodes(); while (la.kind == 1) { Get(); sym = tab.FindSym(t.val); bool undef = (sym == null); if (undef) sym = tab.NewSym(Node.nt, t.val, t.line); else { if (sym.typ == Node.nt) { if (sym.graph != null) SemErr("name declared twice"); } else SemErr("this symbol kind not allowed on left side of production"); sym.line = t.line; } bool noAttrs = (sym.attrPos == null); sym.attrPos = null; if (la.kind == 26 || la.kind == 28) { AttrDecl(sym); } if (!undef && noAttrs != (sym.attrPos == null)) SemErr("attribute mismatch between declaration and use of this symbol"); if (la.kind == 41) { SemText(out sym.semPos); } ExpectWeak(19, 5); Expression(out g); sym.graph = g.l; tab.Finish(g); ExpectWeak(20, 6); } Expect(21); Expect(1); if (grammarName != t.val) SemErr("name does not match grammar name"); tab.gramSy = tab.FindSym(grammarName); if (tab.gramSy == null) SemErr("missing production for grammar name"); else { sym = tab.gramSy; if (sym.attrPos != null) SemErr("grammar symbol must not have attributes"); } tab.noSym = tab.NewSym(Node.t, "???", 0); // noSym gets highest number tab.SetupAnys(); tab.RenumberPragmas(); if (tab.ddt[2]) tab.PrintNodes(); if (errors.count == 0) { Console.WriteLine("checking"); tab.CompSymbolSets(); if (tab.ddt[7]) tab.XRef(); if (tab.GrammarOk()) { Console.Write("parser"); pgen.WriteParser(); if (genScanner) { Console.Write(" + scanner"); dfa.WriteScanner(); if (tab.ddt[0]) dfa.PrintStates(); } Console.WriteLine(" generated"); if (tab.ddt[8]) { tab.PrintStatistics(); pgen.PrintStatistics(); } } } if (tab.ddt[6]) tab.PrintSymbolTable(); Expect(20); } void SetDecl() { CharSet s; Expect(1); string name = t.val; CharClass c = tab.FindCharClass(name); if (c != null) SemErr("name declared twice"); Expect(19); Set(out s); if (s.Elements() == 0) SemErr("character set must not be empty"); tab.NewCharClass(name, s); Expect(20); } void TokenDecl(int typ) { string name; int kind; Symbol sym; Graph g; Sym(out name, out kind); sym = tab.FindSym(name); if (sym != null) SemErr("name declared twice"); else { sym = tab.NewSym(typ, name, t.line); sym.tokenKind = Symbol.fixedToken; } tokenString = null; while (!(StartOf(7))) {SynErr(45); Get();} if (la.kind == 19) { Get(); TokenExpr(out g); Expect(20); if (kind == isLiteral) SemErr("a literal must not be declared with a structure"); tab.Finish(g); if (tokenString == null || tokenString.Equals(noString)) dfa.ConvertToStates(g.l, sym); else { // TokenExpr is a single string if (tab.literals[tokenString] != null) SemErr("token string declared twice"); tab.literals[tokenString] = sym; dfa.MatchLiteral(tokenString, sym); } } else if (StartOf(8)) { if (kind == isIdent) genScanner = false; else dfa.MatchLiteral(sym.name, sym); } else SynErr(46); if (la.kind == 41) { SemText(out sym.semPos); if (typ != Node.pr) SemErr("semantic action not allowed here"); } } void TokenExpr(out Graph g) { Graph g2; TokenTerm(out g); bool first = true; while (WeakSeparator(30,9,10) ) { TokenTerm(out g2); if (first) { tab.MakeFirstAlt(g); first = false; } tab.MakeAlternative(g, g2); } } void Set(out CharSet s) { CharSet s2; SimSet(out s); while (la.kind == 22 || la.kind == 23) { if (la.kind == 22) { Get(); SimSet(out s2); s.Or(s2); } else { Get(); SimSet(out s2); s.Subtract(s2); } } } void AttrDecl(Symbol sym) { if (la.kind == 26) { Get(); int beg = la.pos; int col = la.col; while (StartOf(11)) { if (StartOf(12)) { Get(); } else { Get(); SemErr("bad string in attributes"); } } Expect(27); if (t.pos > beg) sym.attrPos = new Position(beg, t.pos, col); } else if (la.kind == 28) { Get();
[ "\t\t\tint beg = la.pos; int col = la.col;" ]
1,264
lcc
csharp
null
ae0f2d60c0cb9d0cb36a55fcf60b29466a441974ac234dca
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (c) 2011 OpenERP S.A. <http://openerp.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, timedelta from dateutil.relativedelta import relativedelta from osv import fields, osv, orm from edi import EDIMixin from tools import DEFAULT_SERVER_DATE_FORMAT SALE_ORDER_LINE_EDI_STRUCT = { 'sequence': True, 'name': True, #custom: 'date_planned' 'product_id': True, 'product_uom': True, 'price_unit': True, #custom: 'product_qty' 'discount': True, 'notes': True, # fields used for web preview only - discarded on import 'price_subtotal': True, } SALE_ORDER_EDI_STRUCT = { 'name': True, 'origin': True, 'company_id': True, # -> to be changed into partner #custom: 'partner_ref' 'date_order': True, 'partner_id': True, #custom: 'partner_address' #custom: 'notes' 'order_line': SALE_ORDER_LINE_EDI_STRUCT, # fields used for web preview only - discarded on import 'amount_total': True, 'amount_untaxed': True, 'amount_tax': True, 'payment_term': True, 'order_policy': True, 'user_id': True, } class sale_order(osv.osv, EDIMixin): _inherit = 'sale.order' def edi_export(self, cr, uid, records, edi_struct=None, context=None): """Exports a Sale order""" edi_struct = dict(edi_struct or SALE_ORDER_EDI_STRUCT) res_company = self.pool.get('res.company') res_partner_address = self.pool.get('res.partner.address') edi_doc_list = [] for order in records: # generate the main report self._edi_generate_report_attachment(cr, uid, order, context=context) # Get EDI doc based on struct. The result will also contain all metadata fields and attachments. edi_doc = super(sale_order,self).edi_export(cr, uid, [order], edi_struct, context)[0] edi_doc.update({ # force trans-typing to purchase.order upon import '__import_model': 'purchase.order', '__import_module': 'purchase', 'company_address': res_company.edi_export_address(cr, uid, order.company_id, context=context), 'partner_address': res_partner_address.edi_export(cr, uid, [order.partner_order_id], context=context)[0], 'currency': self.pool.get('res.currency').edi_export(cr, uid, [order.pricelist_id.currency_id], context=context)[0], 'partner_ref': order.client_order_ref or False, 'notes': order.note or False, }) edi_doc_list.append(edi_doc) return edi_doc_list def _edi_import_company(self, cr, uid, edi_document, context=None): # TODO: for multi-company setups, we currently import the document in the # user's current company, but we should perhaps foresee a way to select # the desired company among the user's allowed companies self._edi_requires_attributes(('company_id','company_address'), edi_document) res_partner_address = self.pool.get('res.partner.address') res_partner = self.pool.get('res.partner') # imported company = as a new partner src_company_id, src_company_name = edi_document.pop('company_id') partner_id = self.edi_import_relation(cr, uid, 'res.partner', src_company_name, src_company_id, context=context) partner_value = {'supplier': True} res_partner.write(cr, uid, [partner_id], partner_value, context=context) # imported company_address = new partner address address_info = edi_document.pop('company_address') address_info['partner_id'] = (src_company_id, src_company_name) address_info['type'] = 'default' address_id = res_partner_address.edi_import(cr, uid, address_info, context=context) # modify edi_document to refer to new partner/address partner_address = res_partner_address.browse(cr, uid, address_id, context=context) edi_document['partner_id'] = (src_company_id, src_company_name) edi_document.pop('partner_address', False) # ignored address_edi_m2o = self.edi_m2o(cr, uid, partner_address, context=context) edi_document['partner_order_id'] = address_edi_m2o edi_document['partner_invoice_id'] = address_edi_m2o edi_document['partner_shipping_id'] = address_edi_m2o return partner_id def _edi_get_pricelist(self, cr, uid, partner_id, currency, context=None): # TODO: refactor into common place for purchase/sale, e.g. into product module partner_model = self.pool.get('res.partner') partner = partner_model.browse(cr, uid, partner_id, context=context) pricelist = partner.property_product_pricelist if not pricelist: pricelist = self.pool.get('ir.model.data').get_object(cr, uid, 'product', 'list0', context=context) if not pricelist.currency_id == currency: # look for a pricelist with the right type and currency, or make a new one pricelist_type = 'sale' product_pricelist = self.pool.get('product.pricelist') match_pricelist_ids = product_pricelist.search(cr, uid,[('type','=',pricelist_type), ('currency_id','=',currency.id)]) if match_pricelist_ids: pricelist_id = match_pricelist_ids[0] else: pricelist_name = _('EDI Pricelist (%s)') % (currency.name,) pricelist_id = product_pricelist.create(cr, uid, {'name': pricelist_name, 'type': pricelist_type, 'currency_id': currency.id, }) self.pool.get('product.pricelist.version').create(cr, uid, {'name': pricelist_name, 'pricelist_id': pricelist_id}) pricelist = product_pricelist.browse(cr, uid, pricelist_id) return self.edi_m2o(cr, uid, pricelist, context=context) def edi_import(self, cr, uid, edi_document, context=None): self._edi_requires_attributes(('company_id','company_address','order_line','date_order','currency'), edi_document) #import company as a new partner partner_id = self._edi_import_company(cr, uid, edi_document, context=context) # currency for rounding the discount calculations and for the pricelist res_currency = self.pool.get('res.currency') currency_info = edi_document.pop('currency') currency_id = res_currency.edi_import(cr, uid, currency_info, context=context) order_currency = res_currency.browse(cr, uid, currency_id) date_order = edi_document['date_order'] partner_ref = edi_document.pop('partner_ref', False) edi_document['client_order_ref'] = edi_document['name'] edi_document['name'] = partner_ref or edi_document['name'] edi_document['note'] = edi_document.pop('notes', False) edi_document['pricelist_id'] = self._edi_get_pricelist(cr, uid, partner_id, order_currency, context=context) # discard web preview fields, if present edi_document.pop('amount_total', None) edi_document.pop('amount_tax', None) edi_document.pop('amount_untaxed', None) order_lines = edi_document['order_line'] for order_line in order_lines: self._edi_requires_attributes(('date_planned', 'product_id', 'product_uom', 'product_qty', 'price_unit'), order_line) order_line['product_uom_qty'] = order_line['product_qty'] del order_line['product_qty'] date_planned = order_line.pop('date_planned') delay = 0 if date_order and date_planned: # no security_days buffer, this is the promised date given by supplier delay = (datetime.strptime(date_planned, DEFAULT_SERVER_DATE_FORMAT) - \ datetime.strptime(date_order, DEFAULT_SERVER_DATE_FORMAT)).days order_line['delay'] = delay # discard web preview fields, if present order_line.pop('price_subtotal', None) return super(sale_order,self).edi_import(cr, uid, edi_document, context=context) class sale_order_line(osv.osv, EDIMixin): _inherit='sale.order.line' def edi_export(self, cr, uid, records, edi_struct=None, context=None): """Overridden to provide sale order line fields with the expected names (sale and purchase orders have different column names)""" edi_struct = dict(edi_struct or SALE_ORDER_LINE_EDI_STRUCT) edi_doc_list = [] for line in records: edi_doc = super(sale_order_line,self).edi_export(cr, uid, [line], edi_struct, context)[0] edi_doc['__import_model'] = 'purchase.order.line'
[ " edi_doc['product_qty'] = line.product_uom_qty" ]
813
lcc
python
null
d6b0b1ba478697a4988f5e3a441475444dd822738a3d6461
/** * Copyright (c) 2010-2015, openHAB.org and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.io.rest; import java.util.Dictionary; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import org.apache.commons.lang.StringUtils; import org.atmosphere.cpr.AtmosphereServlet; import org.openhab.core.events.EventPublisher; import org.openhab.core.items.ItemRegistry; import org.openhab.io.net.http.SecureHttpContext; import org.openhab.io.rest.internal.resources.ItemResource; import org.openhab.io.rest.internal.resources.RootResource; import org.openhab.io.rest.internal.resources.SitemapResource; import org.openhab.io.servicediscovery.DiscoveryService; import org.openhab.io.servicediscovery.ServiceDescription; import org.openhab.model.core.ModelRepository; import org.openhab.ui.items.ItemUIRegistry; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; import org.osgi.service.http.HttpContext; import org.osgi.service.http.HttpService; import org.osgi.service.http.NamespaceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jersey.core.util.FeaturesAndProperties; /** * This is the main component of the REST API; it gets all required services injected, * registers itself as a servlet on the HTTP service and adds the different rest resources * to this service. * * @author Kai Kreuzer * @since 0.8.0 */ @ApplicationPath(RESTApplication.REST_SERVLET_ALIAS) public class RESTApplication extends Application { public static final String REST_SERVLET_ALIAS = "/rest"; private static final Logger logger = LoggerFactory.getLogger(RESTApplication.class); private int httpSSLPort; private int httpPort; private HttpService httpService; private DiscoveryService discoveryService; static private EventPublisher eventPublisher; static private ItemUIRegistry itemUIRegistry; static private ModelRepository modelRepository; public void setHttpService(HttpService httpService) { this.httpService = httpService; } public void unsetHttpService(HttpService httpService) { this.httpService = null; } public void setEventPublisher(EventPublisher eventPublisher) { RESTApplication.eventPublisher = eventPublisher; } public void unsetEventPublisher(EventPublisher eventPublisher) { RESTApplication.eventPublisher = null; } static public EventPublisher getEventPublisher() { return eventPublisher; } public void setItemUIRegistry(ItemUIRegistry itemUIRegistry) { RESTApplication.itemUIRegistry = itemUIRegistry; } public void unsetItemUIRegistry(ItemRegistry itemUIRegistry) { RESTApplication.itemUIRegistry = null; } static public ItemUIRegistry getItemUIRegistry() { return itemUIRegistry; } public void setModelRepository(ModelRepository modelRepository) { RESTApplication.modelRepository = modelRepository; } public void unsetModelRepository(ModelRepository modelRepository) { RESTApplication.modelRepository = null; } static public ModelRepository getModelRepository() { return modelRepository; } public void setDiscoveryService(DiscoveryService discoveryService) { this.discoveryService = discoveryService; } public void unsetDiscoveryService(DiscoveryService discoveryService) { this.discoveryService = null; } public void activate() { try { // we need to call the activator ourselves as this bundle is included in the lib folder com.sun.jersey.core.osgi.Activator jerseyActivator = new com.sun.jersey.core.osgi.Activator(); BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()) .getBundleContext(); try { jerseyActivator.start(bundleContext); } catch (Exception e) { logger.error("Could not start Jersey framework", e); } httpPort = Integer.parseInt(bundleContext.getProperty("jetty.port")); httpSSLPort = Integer.parseInt(bundleContext.getProperty("jetty.port.ssl")); Servlet atmosphereServlet = new AtmosphereServlet(); httpService.registerServlet(REST_SERVLET_ALIAS, atmosphereServlet, getJerseyServletParams(), createHttpContext()); logger.info("Started REST API at {}", REST_SERVLET_ALIAS); if (discoveryService != null) { discoveryService.registerService(getDefaultServiceDescription()); discoveryService.registerService(getSSLServiceDescription()); } } catch (ServletException se) { throw new RuntimeException(se); } catch (NamespaceException se) { throw new RuntimeException(se); } } public void deactivate() { if (this.httpService != null) { httpService.unregister(REST_SERVLET_ALIAS); logger.info("Stopped REST API"); } if (discoveryService != null) { discoveryService.unregisterService(getDefaultServiceDescription()); discoveryService.unregisterService(getSSLServiceDescription()); } } /** * Creates a {@link SecureHttpContext} which handles the security for this * Servlet * @return a {@link SecureHttpContext} */ protected HttpContext createHttpContext() { HttpContext defaultHttpContext = httpService.createDefaultHttpContext(); return new SecureHttpContext(defaultHttpContext, "openHAB.org"); } @Override public Set<Class<?>> getClasses() { Set<Class<?>> result = new HashSet<Class<?>>(); result.add(RootResource.class); result.add(ItemResource.class); result.add(SitemapResource.class); return result; } private Dictionary<String, String> getJerseyServletParams() { Dictionary<String, String> jerseyServletParams = new Hashtable<String, String>(); jerseyServletParams.put("javax.ws.rs.Application", RESTApplication.class.getName()); jerseyServletParams.put("org.atmosphere.core.servlet-mapping", RESTApplication.REST_SERVLET_ALIAS+"/*"); jerseyServletParams.put("org.atmosphere.useWebSocket", "true"); jerseyServletParams.put("org.atmosphere.useNative", "true"); jerseyServletParams.put("org.atmosphere.cpr.AtmosphereInterceptor.disableDefaults", "true"); // use the default interceptors without PaddingAtmosphereInterceptor // see: https://groups.google.com/forum/#!topic/openhab/Z-DVBXdNiYE final String[] interceptors = { "org.atmosphere.interceptor.CorsInterceptor", "org.atmosphere.interceptor.CacheHeadersInterceptor", "org.atmosphere.interceptor.AndroidAtmosphereInterceptor", "org.atmosphere.interceptor.SSEAtmosphereInterceptor", "org.atmosphere.interceptor.JSONPAtmosphereInterceptor", "org.atmosphere.interceptor.JavaScriptProtocol", "org.atmosphere.interceptor.OnDisconnectInterceptor" }; jerseyServletParams.put("org.atmosphere.cpr.AtmosphereInterceptor", StringUtils.join(interceptors, ",")); // The BroadcasterCache is set in ResourceStateChangeListener.registerItems(), because otherwise // it gets somehow overridden by other registered servlets (e.g. the CV-bundle) //jerseyServletParams.put("org.atmosphere.cpr.broadcasterCacheClass", "org.atmosphere.cache.UUIDBroadcasterCache"); jerseyServletParams.put("org.atmosphere.cpr.broadcasterLifeCyclePolicy", "IDLE_DESTROY"); jerseyServletParams.put("org.atmosphere.cpr.CometSupport.maxInactiveActivity", "3000000"); jerseyServletParams.put("org.atmosphere.cpr.broadcaster.maxProcessingThreads", "10"); // Default: unlimited! jerseyServletParams.put("org.atmosphere.cpr.broadcaster.maxAsyncWriteThreads", "10"); // Default: 200 on atmos 2.2 jerseyServletParams.put("com.sun.jersey.spi.container.ResourceFilter", "org.atmosphere.core.AtmosphereFilter"); // required because of bug http://java.net/jira/browse/JERSEY-361 jerseyServletParams.put(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true"); return jerseyServletParams; } private ServiceDescription getDefaultServiceDescription() { Hashtable<String, String> serviceProperties = new Hashtable<String, String>(); serviceProperties.put("uri", REST_SERVLET_ALIAS); return new ServiceDescription("_openhab-server._tcp.local.", "openHAB", httpPort, serviceProperties); } private ServiceDescription getSSLServiceDescription() {
[ " \tServiceDescription description = getDefaultServiceDescription();" ]
603
lcc
java
null
5b2b4575bee8bc4223e1eed289165b7fcf597782d98e9033
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.virtual.bundle; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.alfresco.model.ContentModel; import org.alfresco.repo.security.authentication.AuthenticationUtil; import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork; import org.alfresco.repo.security.permissions.NodePermissionEntry; import org.alfresco.repo.security.permissions.PermissionEntry; import org.alfresco.repo.security.permissions.PermissionServiceSPI; import org.alfresco.repo.virtual.VirtualizationIntegrationTest; import org.alfresco.repo.virtual.store.VirtualStoreImpl; import org.alfresco.repo.virtual.store.VirtualUserPermissions; import org.alfresco.service.cmr.model.FileInfo; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.security.AccessPermission; import org.alfresco.service.cmr.security.AccessStatus; import org.alfresco.service.cmr.security.PermissionService; import org.alfresco.service.cmr.site.SiteService; import org.alfresco.service.cmr.site.SiteVisibility; import org.alfresco.util.testing.category.LuceneTests; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; @Category(LuceneTests.class) @RunWith(MockitoJUnitRunner.class) public class VirtualPermissionServiceExtensionTest extends VirtualizationIntegrationTest { private PermissionServiceSPI permissionService; private String user1; private String user2; private NodeRef vf1Node2; private NodeRef virtualContent; private VirtualStoreImpl smartStore; /** original user permissions to be restored on tear down */ private VirtualUserPermissions savedUserPermissions; private NodeRef testSiteFolder = null, smartFolder = null, contributionDocsFolder = null; private SiteService siteService; private String sName = "mytestsite_ace_5162"; private NodeRef myContentSMF; private NodeRef contributionsSMF; @Before public void setUp() throws Exception { super.setUp(); // we set our own virtual user permissions in order to be context xml // independent smartStore = ctx.getBean("smartStore", VirtualStoreImpl.class); permissionService = ctx.getBean("permissionServiceImpl", PermissionServiceSPI.class); siteService = ctx.getBean("siteService", SiteService.class); user1 = "user1"; user2 = "user2"; vf1Node2 = nodeService.getChildByName(this.virtualFolder1NodeRef, ContentModel.ASSOC_CONTAINS, "Node2"); virtualContent = createContent(vf1Node2, "virtualContent").getChildRef(); this.permissionService.setPermission(this.virtualFolder1NodeRef, user1, PermissionService.DELETE_CHILDREN, true); this.permissionService.setPermission(this.virtualFolder1NodeRef, user2, PermissionService.DELETE_CHILDREN, false); this.permissionService.setPermission(this.virtualFolder1NodeRef, user1, PermissionService.READ_PERMISSIONS, true); this.permissionService.setPermission(this.virtualFolder1NodeRef, user2, PermissionService.READ_PERMISSIONS, true); this.permissionService.setPermission(this.virtualFolder1NodeRef, user1, PermissionService.READ_PROPERTIES, true); this.permissionService.setPermission(this.virtualFolder1NodeRef, user1, PermissionService.CREATE_CHILDREN, false); this.permissionService.setPermission(this.virtualFolder1NodeRef, user1, PermissionService.DELETE, true); } protected void setUpTestPermissions() { // we save the original permissions savedUserPermissions = smartStore.getUserPermissions(); VirtualUserPermissions testPermissions = new VirtualUserPermissions(savedUserPermissions); Set<String> allowSmartNodes = new HashSet<>(savedUserPermissions.getAllowSmartNodes()); // we force create children on virtual nodes allowSmartNodes.add(PermissionService.CREATE_CHILDREN); testPermissions.setAllowSmartNodes(allowSmartNodes); testPermissions.init(); smartStore.setUserPermissions(testPermissions); } @After public void tearDown() throws Exception { if (savedUserPermissions != null) { smartStore.setUserPermissions(savedUserPermissions); savedUserPermissions = null; } super.tearDown(); } private AccessStatus hasPermissionAs(final NodeRef nodeRef, final String permission, String asUser) { RunAsWork<AccessStatus> hasPermissionAs = new RunAsWork<AccessStatus>() { @Override public AccessStatus doWork() throws Exception { return permissionService.hasPermission(nodeRef, permission); } }; return AuthenticationUtil.runAs(hasPermissionAs, asUser); } @Test public void testHasPermissionAdherence_actualPath() throws Exception { // virtual nodes should adhere to actual node permission if no filing // or the actual path is specified assertEquals(AccessStatus.ALLOWED, hasPermissionAs(this.virtualFolder1NodeRef, PermissionService.DELETE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(this.virtualFolder1NodeRef, PermissionService.DELETE_CHILDREN, user2)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(vf1Node2, PermissionService.DELETE_CHILDREN, user1)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(virtualContent, PermissionService.DELETE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(vf1Node2, PermissionService.DELETE_CHILDREN, user2)); assertEquals(AccessStatus.DENIED, hasPermissionAs(virtualContent, PermissionService.DELETE_CHILDREN, user2)); this.permissionService.setPermission(this.virtualFolder1NodeRef, user1, PermissionService.DELETE_CHILDREN, false); assertEquals(AccessStatus.DENIED, hasPermissionAs(vf1Node2, PermissionService.DELETE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(virtualContent, PermissionService.DELETE_CHILDREN, user1)); } @Test public void testHasPermissionAdherence_missingFolderPath() throws Exception { NodeRef virtualFolderT5 = createVirtualizedFolder(testRootFolder.getNodeRef(), "VirtualFolderT5", TEST_TEMPLATE_5_JSON_SYS_PATH); NodeRef filingFolderVirtualNodeRef = nodeService.getChildByName(virtualFolderT5, ContentModel.ASSOC_CONTAINS, "FilingFolder_filing_path"); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, PermissionService.DELETE, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, asTypedPermission(PermissionService.DELETE), user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, asTypedPermission(PermissionService.CREATE_CHILDREN), user1)); } @Test public void testHasPermissionAdherence_folderPath() throws Exception { // virtual nodes should adhere to node permission of the node indicated // by the filing path is specified -with virtual permission overriding // when specified NodeRef virtualFolderT5 = createVirtualizedFolder(testRootFolder.getNodeRef(), "VirtualFolderT5", TEST_TEMPLATE_5_JSON_SYS_PATH); NodeRef filingFolderVirtualNodeRef = nodeService.getChildByName(virtualFolderT5, ContentModel.ASSOC_CONTAINS, "FilingFolder_filing_path"); ChildAssociationRef filingFolderChildAssoc = createFolder(rootNodeRef, "FilingFolder"); NodeRef filingFolderNodeRef = filingFolderChildAssoc.getChildRef(); this.permissionService.setPermission(filingFolderNodeRef, user1, PermissionService.READ_PERMISSIONS, true); this.permissionService.setPermission(filingFolderNodeRef, user1, PermissionService.CREATE_CHILDREN, true); this.permissionService.setPermission(filingFolderNodeRef, user2, PermissionService.CREATE_CHILDREN, false); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderNodeRef, PermissionService.DELETE, user1)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(filingFolderNodeRef, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderNodeRef, PermissionService.CREATE_CHILDREN, user2)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, PermissionService.DELETE, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, asTypedPermission(PermissionService.DELETE), user1)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(filingFolderVirtualNodeRef, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(filingFolderVirtualNodeRef, asTypedPermission(PermissionService.CREATE_CHILDREN), user1)); this.permissionService.setPermission(filingFolderNodeRef, user1, PermissionService.DELETE_CHILDREN, true); this.permissionService.setPermission(filingFolderNodeRef, user2, PermissionService.DELETE_CHILDREN, false); this.permissionService.setPermission(filingFolderNodeRef, user1, PermissionService.READ_PROPERTIES, true); this.permissionService.setPermission(filingFolderNodeRef, user1, PermissionService.CREATE_CHILDREN, false); this.permissionService.setPermission(filingFolderNodeRef, user1, PermissionService.DELETE, true); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(filingFolderNodeRef, PermissionService.DELETE, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderNodeRef, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, PermissionService.DELETE, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, asTypedPermission(PermissionService.DELETE), user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(filingFolderVirtualNodeRef, asTypedPermission(PermissionService.CREATE_CHILDREN), user1)); } @Test public void testHasPermission() throws Exception { setUpTestPermissions(); // virtual permission should override actual permissions assertEquals(AccessStatus.ALLOWED, hasPermissionAs(this.virtualFolder1NodeRef, PermissionService.DELETE, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(this.virtualFolder1NodeRef, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(vf1Node2, PermissionService.DELETE, user1)); assertEquals(AccessStatus.DENIED, hasPermissionAs(vf1Node2, asTypedPermission(PermissionService.DELETE), user1)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(vf1Node2, PermissionService.CREATE_CHILDREN, user1)); assertEquals(AccessStatus.ALLOWED, hasPermissionAs(vf1Node2, asTypedPermission(PermissionService.CREATE_CHILDREN), user1)); } @Test public void testReadonlyNodeHasPermission() throws Exception { // virtual permission should override actual permissions NodeRef aVFTestTemplate2 = createVirtualizedFolder(testRootFolder.getNodeRef(), "aVFTestTemplate2", TEST_TEMPLATE_2_JSON_SYS_PATH); NodeRef vf2Node2 = nodeService.getChildByName(aVFTestTemplate2, ContentModel.ASSOC_CONTAINS, "Node2"); final String[] deniedReadOnly = new String[] { PermissionService.UNLOCK, PermissionService.CANCEL_CHECK_OUT, PermissionService.CHANGE_PERMISSIONS, PermissionService.CREATE_CHILDREN, PermissionService.DELETE, PermissionService.WRITE, PermissionService.DELETE_NODE, PermissionService.WRITE_PROPERTIES, PermissionService.WRITE_CONTENT, PermissionService.CREATE_ASSOCIATIONS }; StringBuilder nonDeniedTrace = new StringBuilder(); for (int i = 0; i < deniedReadOnly.length; i++) { AccessStatus accessStatus = hasPermissionAs(vf2Node2, deniedReadOnly[i], user1); if (!AccessStatus.DENIED.equals(accessStatus)) { if (nonDeniedTrace.length() > 0) { nonDeniedTrace.append(","); } nonDeniedTrace.append(deniedReadOnly[i]); } } assertTrue("Non-denied permissions on RO virtual nodes : " + nonDeniedTrace, nonDeniedTrace.length() == 0); } @SuppressWarnings("unchecked") private Map<String, List<? extends PermissionEntry>> mapPermissionsByName(List<? extends PermissionEntry> entries) { Map<String, List<? extends PermissionEntry>> nameMap = new HashMap<>(); for (PermissionEntry permissionEntry : entries) { String name = permissionEntry.getPermissionReference().getName(); List<PermissionEntry> permissions = (List<PermissionEntry>) nameMap.get(name); if (permissions == null) {
[ " permissions = new ArrayList<>();" ]
897
lcc
java
null
2bcc90a8e0d4c69a7f61f382e24a8ae2c11dc6eb28b58b0a
# -*- coding: utf-8 -*- # Copyright (C) 2010, 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com> # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation; either version 2.1 of the License, or (at your # option) any later version. # This library 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 library; if not, write to the Free Software Foundation, # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from __future__ import (print_function, division, unicode_literals, absolute_import) import pytest import mock from pyudev import Enumerator, Device def pytest_funcarg__enumerator(request): context = request.getfuncargvalue('context') return context.list_devices() class TestEnumerator(object): def test_match_subsystem(self, context): devices = context.list_devices().match_subsystem('input') for device in devices: assert device.subsystem == 'input' def test_match_subsystem_nomatch(self, context): devices = context.list_devices().match_subsystem('input', nomatch=True) for device in devices: assert device.subsystem != 'input' def test_match_subsystem_nomatch_unfulfillable(self, context): devices = context.list_devices() devices.match_subsystem('input') devices.match_subsystem('input', nomatch=True) assert not list(devices) def test_match_sys_name(self, context): devices = context.list_devices().match_sys_name('sda') for device in devices: assert device.sys_name == 'sda' def test_match_property_string(self, context): devices = list(context.list_devices().match_property('DRIVER', 'usb')) for device in devices: assert device['DRIVER'] == 'usb' assert device.driver == 'usb' def test_match_property_int(self, context): devices = list(context.list_devices().match_property( 'ID_INPUT_KEY', 1)) for device in devices: assert device['ID_INPUT_KEY'] == '1' assert device.asint('ID_INPUT_KEY') == 1 def test_match_property_bool(self, context): devices = list(context.list_devices().match_property( 'ID_INPUT_KEY', True)) for device in devices: assert device['ID_INPUT_KEY'] == '1' assert device.asbool('ID_INPUT_KEY') def test_match_attribute_nomatch(self, context): devices = context.list_devices().match_attribute( 'driver', 'usb', nomatch=True) for device in devices: assert device.attributes.get('driver') != 'usb' def test_match_attribute_nomatch_unfulfillable(self, context): devices = context.list_devices() devices.match_attribute('driver', 'usb') devices.match_attribute('driver', 'usb', nomatch=True) assert not list(devices) def test_match_attribute_string(self, context): devices = list(context.list_devices().match_attribute('driver', 'usb')) for device in devices: assert device.attributes['driver'] == b'usb' def test_match_attribute_int(self, context): # busnum gives us the number of a USB bus. And any decent system # likely has two or more usb buses, so this should work on more or less # any system. I didn't find any other attribute that is likely to be # present on a wide range of system, so this is probably as general as # possible. Still it may fail because the attribute isn't present on # any device at all on the system running the test devices = list(context.list_devices().match_attribute('busnum', 2)) for device in devices: assert device.attributes['busnum'] == b'2' assert device.attributes.asint('busnum') == 2 def test_match_attribute_bool(self, context): # ro tells us whether a volumne is mounted read-only or not. And any # developers system should have at least one readable volume, thus this # test should work on all systems these tests are ever run on devices = list(context.list_devices().match_attribute('ro', False)) for device in devices: assert device.attributes['ro'] == b'0' assert not device.attributes.asbool('ro') @pytest.mark.udev_version('>= 154') def test_match_tag_mock(self, context): enumerator = context.list_devices() funcname = 'udev_enumerate_add_match_tag' spec = lambda e, t: None with mock.patch.object(enumerator._libudev, funcname, autospec=spec) as func: retval = enumerator.match_tag('spam') assert retval is enumerator func.assert_called_with(enumerator, b'spam') @pytest.mark.udev_version('>= 154') def test_match_tag(self, context): devices = list(context.list_devices().match_tag('seat')) for device in devices: assert 'seat' in device.tags @pytest.mark.parametrize('device_data', pytest.config.udev_device_sample) @pytest.mark.udev_version('>= 172') def test_match_parent(self, context, device_data): device = Device.from_path(context, device_data.device_path) parent = device.parent if parent is None: pytest.skip('Device {0!r} has no parent'.format(device)) else: children = list(context.list_devices().match_parent(parent)) assert device in children assert parent in children @pytest.mark.udev_version('>= 165') def test_match_is_initialized_mock(self, context): enumerator = context.list_devices() funcname = 'udev_enumerate_add_match_is_initialized' spec = lambda e: None with mock.patch.object(enumerator._libudev, funcname, autospec=spec) as func: retval = enumerator.match_is_initialized() assert retval is enumerator func.assert_called_with(enumerator) def test_combined_matches_of_same_type(self, context): """ Test for behaviour as observed in #1 """ properties = ('DEVTYPE', 'ID_TYPE') devices = context.list_devices() for property in properties: devices.match_property(property, 'disk') for device in devices: assert (device.get('DEVTYPE') == 'disk' or device.get('ID_TYPE') == 'disk') def test_combined_matches_of_different_types(self, context): properties = ('DEVTYPE', 'ID_TYPE') devices = context.list_devices().match_subsystem('input') for property in properties: devices.match_property(property, 'disk') devices = list(devices) assert not devices def test_match(self, context): devices = list(context.list_devices().match( subsystem='input', ID_INPUT_MOUSE=True, sys_name='mouse0')) for device in devices: assert device.subsystem == 'input' assert device.asbool('ID_INPUT_MOUSE') assert device.sys_name == 'mouse0' def test_match_passthrough_subsystem(self, enumerator): with mock.patch.object(enumerator, 'match_subsystem', autospec=True) as match_subsystem: enumerator.match(subsystem=mock.sentinel.subsystem) match_subsystem.assert_called_with(mock.sentinel.subsystem) def test_match_passthrough_sys_name(self, enumerator): with mock.patch.object(enumerator, 'match_sys_name', autospec=True) as match_sys_name: enumerator.match(sys_name=mock.sentinel.sys_name) match_sys_name.assert_called_with(mock.sentinel.sys_name) def test_match_passthrough_tag(self, enumerator): with mock.patch.object(enumerator, 'match_tag', autospec=True) as match_tag: enumerator.match(tag=mock.sentinel.tag) match_tag.assert_called_with(mock.sentinel.tag) @pytest.mark.udev_version('>= 172') def test_match_passthrough_parent(self, enumerator): with mock.patch.object(enumerator, 'match_parent', autospec=True) as match_parent: enumerator.match(parent=mock.sentinel.parent) match_parent.assert_called_with(mock.sentinel.parent) def test_match_passthrough_property(self, enumerator): with mock.patch.object(enumerator, 'match_property', autospec=True) as match_property: enumerator.match(eggs=mock.sentinel.eggs, spam=mock.sentinel.spam) assert match_property.call_count == 2 posargs = [args for args, _ in match_property.call_args_list] assert ('spam', mock.sentinel.spam) in posargs assert ('eggs', mock.sentinel.eggs) in posargs class TestContext(object): @pytest.mark.match def test_list_devices(self, context): devices = list(context.list_devices(
[ " subsystem='input', ID_INPUT_MOUSE=True, sys_name='mouse0'))" ]
769
lcc
python
null
7293c0e9f7e75148f514aaf18ac8ea75262950e00b623dfd
#!/usr/bin/env python # -*- coding: utf-8 -*- from HttpUtils import App, buildOpener class Device(object): def __init__(self, token): self.token = token self.app = App() def check_inspection(self): data = self.app.check__inspection() return data def notification_postDevicetoken(self, loginId, password, token=None, S="nosessionid"): if token == None: token = self.token params = { "S": S, # magic,don't touch "login_id": loginId, "password": password, "token": token.encode("base64") } data = self.app.notification_post__devicetoken(params) return data def newUser(self, loginId, password): # self.notification_postDevicetoken(loginId, password) return User(self.app, loginId, password) class User(object): def __init__(self, app, loginId, password): self.login_id = loginId self.password = password self.app = app self.session = None self.userId = None self.menu = Menu(self.app) self.roundtable = RoundTable(self.app) self.exploration = Exploration(self.app) def login(self): params = { "login_id": self.login_id, "password": self.password, } data = self.app.login(params) self.session = data.response.header.session_id self.userId = data.response.body.login.user_id self.cardList = data.response.header.your_data.owner_card_list.user_card return data def mainmenu(self): data = self.app.mainmenu() return data def endTutorial(self): params = { "S": self.session, "step": '8000', } data = self.app.tutorial_next(params) return data def cardUpdate(self): params = { "S": self.session, "revision": '0', } data = self.app.masterdata_card_update(params) return data def cardCategoryUpdate(self): params = { "S": self.session, "revision": '0', } data = self.app.masterdata_card__category_update(params) return data def cardComboUpdate(self): params = { "S": self.session, "revision": '0', } data = self.app.masterdata_combo_update(params) return data class RoundTable(object): def __init__(self, app): self.app = app def edit(self): params = { "move": "1", } data = self.app.roundtable_edit(params) return data def save(self, cards, leader): '7803549,15208758,17258743,empty,empty,empty,empty,empty,empty,empty,empty,empty' '17258743' cards = cards + ["empty"]*(12-len(cards)) params = { "C": ",".join(cards), "lr": leader, } data = self.app.cardselect_savedeckcard(params) return data class Menu(object): def __init__(self, app): self.app = app def menulist(self): data = self.app.menu_menulist() return data def fairyselect(self): data = self.app.menu_fairyselect() return data def friendlist(self, move = "0"): params = { "move": "0", } data = self.app.menu_friendlist(params) return data def likeUser(self, users, dialog = "1"): users = ",".join(map(lambda x:str(x),users)) params = { "dialog": dialog, "user_id": users, } data = self.app.friend_like__user(params) return data class Exploration(object): def __init__(self, app): self.app = app def getAreaList(self): data = self.app.exploration_area() return data def getFloorList(self, areaId): params = { "area_id": areaId, } data = self.app.exploration_floor(params) return data def getFloorStatus(self, areaID, floorId, check="1"): params = { "area_id": areaID, "floor_id": floorId, "check": check, # magic,don't touch } data = self.app.exploration_get__floor(params) return data def explore(self, areaId, floorId, autoBuild="1"): params = { "area_id": areaId, "floor_id": floorId, "auto_build": autoBuild, } data = self.app.exploration_explore(params) return data def fairyFloor(self, serialId, userId, check="1"): params = { "serial_id": serialId, "user_id": userId, "check": check, # magic,don't touch } data = self.app.exploration_fairy__floor(params) return data def fairybattle(self, serialId, userId): params = { "serial_id": serialId, "user_id": userId, } data = self.app.exploration_fairybattle(params) return data def fairyhistory(self, serialId, userId): params = { "serial_id": serialId, "user_id": userId, } data = self.app.exploration_fairyhistory(params) return data def fairyLose(self, serialId, userId): params = { "serial_id": serialId, "user_id": userId, } data = self.app.exploration_fairy__lose(params) return data def faityWin(self, serialId, userId): params = { "serial_id": serialId, "user_id": userId, } data = self.app.exploration_fairy__win(params) return data if __name__ == "__main__": from config import deviceToken, loginId, password
[ " device = Device(token=deviceToken)" ]
478
lcc
python
null
e172201bb15276d6c82301b6f3239ef78af9c9ab95ca59b2
#!/usr/bin/env python """Time-variable calibration for ATCA Usage: timevariation_cal.py <dataset> [--calibrator=<cal>] [--segment=<min>] [--slop=<min>] -h --help show this -c --calibrator CAL the name of the calibrator [default: 1934-638] -s --segment LEN the length of each calibration segment, in minutes [default: 2] -S --slop SLOP a tolerance on the segment length, if it makes sense to extend it, in minutes [default: 1] """ from docopt import docopt from mirpy import miriad import ephem from datetime import date, datetime, timedelta import fnmatch import os import shutil import numpy as np import sys import json import math import re # A routine to turn a Miriad type time string into a ephem Date. def mirtime_to_date(mt): year = 2000 + int(mt[0:2]) monthShort = mt[2:5] date = int(mt[5:7]) hour = int(mt[8:10]) minute = int(mt[11:13]) second = int(round(float(mt[14:18]))) monthDict = { 'JAN': 1, 'FEB': 2, 'MAR': 3, 'APR': 4, 'MAY': 5, 'JUN': 6, 'JUL': 7, 'AUG': 8, 'SEP': 9, 'OCT': 10, 'NOV': 11, 'DEC': 12 } dateString = "%4d/%02d/%02d %02d:%02d:%02d" % (year, monthDict[monthShort], date, hour, minute, second) return ephem.Date(dateString) def datetime_to_mirtime(dt): # Output a Miriad formatted date. rs = dt.strftime("%y%b%d:%H:%M:%S").lower() return rs # Use a uvlist log to get the cycle time. def filter_uvlist_variables(logfile_name): # We send back a dictionary. rd = { 'cycle_time': -1. } with open(logfile_name, "r") as fp: loglines = fp.readlines() for i in xrange(0, len(loglines)): index_elements = loglines[i].split() if ((len(index_elements) > 2) and (index_elements[0] == "inttime") and (index_elements[1] == ":")): rd['cycle_time'] = float(index_elements[2]) return rd def filter_uvlist_antennas(output): # We send back a dictionary. rd = { 'telescope': "", 'latitude': "", 'longitude': "", 'antennas': [] } outlines = output.split('\n') coords = 0 for i in xrange(0, len(outlines)): index_elements = outlines[i].split() if (len(index_elements) > 0): if (index_elements[0] == "Telescope:"): rd['telescope'] = index_elements[1] elif (index_elements[0] == "Latitude:"): rd['latitude'] = index_elements[1] elif (index_elements[0] == "Longitude:"): rd['longitude'] = index_elements[1] elif ((len(index_elements) == 3) and (index_elements[1] == "----------")): coords = 1 elif (coords == 1): ant = { 'number': int(index_elements[0]), 'coord_x': float(index_elements[1]), 'coord_y': float(index_elements[2]), 'coord_z': float(index_elements[3]) } rd['antennas'].append(ant) return rd # Use uvindex to work out the necessary parameters of this dataset. def filter_uvindex(output): # We send back a dictionary. rd = { 'index': { 'time': [], 'source': [], 'calcode': [], 'antennas': [], 'spectral_channels': [], 'wideband_channels': [], 'freq_config': [], 'record_number': [] }, 'total_time': 0, 'freq_configs': [], 'polarisations': [], 'sources': [] } outlines = output.split('\n') section = 0 freqconfig_n = 0 freqconfig_found = 0 fc = None sourcearea = 0 for i in xrange(0, len(outlines)): index_elements = outlines[i].split() if ((section == 0) and (len(outlines[i]) >= 74)): indexTime = mirtime_to_date(outlines[i][0:18]) if ((index_elements[1] != "Total") and (index_elements[2] != "number")): # This is a regular line. offset = 0 rd['index']['time'].append(indexTime) rd['index']['source'].append(index_elements[1]) # Check if we have a calibrator code. calcode = outlines[i][36:37] if (calcode == " "): # No calibrator code. offset = 1 rd['index']['calcode'].append(calcode) rd['index']['antennas'].append(int(index_elements[3 - offset])) rd['index']['spectral_channels'].append(int(index_elements[4 - offset])) rd['index']['wideband_channels'].append(int(index_elements[5 - offset])) rd['index']['freq_config'].append(int(index_elements[6 - offset])) rd['index']['record_number'].append(int(index_elements[7 - offset])) else: # We've moved to the next section section = 1 elif ((section == 1) and (len(index_elements) > 0) and (index_elements[0] == "Total") and (index_elements[1] == "observing")): # We've found the total amount of observing time. rd['total_time'] = float(index_elements[4]) section = 2 elif (section == 2): if ((len(index_elements) > 0) and (index_elements[0] == "Frequency") and (index_elements[1] == "Configuration")): freqconfig_n = int(index_elements[2]) freqconfig_found = 1 if (fc is not None): rd['freq_configs'].append(fc) fc = { 'number': freqconfig_n, 'nchannels': [], 'frequency1': [], 'frequency_increment': [], 'rest_frequency': [], 'ifchain': [] } elif (freqconfig_found == 1): freqconfig_found = 2 elif (freqconfig_found == 2): if (outlines[i] == ""): freqconfig_found = 0 else: # This is the actual line. fc['nchannels'].append(int(index_elements[0])) fc['frequency1'].append(float(index_elements[1])) fc['frequency_increment'].append(float(index_elements[2])) fc['rest_frequency'].append(float(index_elements[3])) fc['ifchain'].append(int(index_elements[5])) elif (outlines[i] == "------------------------------------------------"): if (fc is not None): rd['freq_configs'].append(fc) section = 3 elif (section == 3): if ((len(index_elements) > 0) and (index_elements[0] == "There") and (index_elements[3] == "records") and (index_elements[5] == "polarization")): rd['polarisations'].append(index_elements[6]) elif (outlines[i] == "------------------------------------------------"): section = 4 elif (section == 4): if ((len(index_elements) > 0) and (index_elements[0] == "Source")): sourcearea = 1 elif ((len(index_elements) > 2) and (sourcearea == 1)): src = { 'name': index_elements[0], 'calcode': index_elements[1], 'right_ascension': index_elements[2], 'declination': index_elements[3], 'dra': index_elements[4], 'ddec': index_elements[5] } rd['sources'].append(src) # Convert things into numpy arrays for easy where-ing later. rd['index']['time'] = np.array(rd['index']['time']) rd['index']['source'] = np.array(rd['index']['source']) rd['index']['calcode'] = np.array(rd['index']['calcode']) rd['index']['antennas'] = np.array(rd['index']['antennas']) rd['index']['spectral_channels'] = np.array(rd['index']['spectral_channels']) rd['index']['wideband_channels'] = np.array(rd['index']['wideband_channels']) rd['index']['freq_config'] = np.array(rd['index']['freq_config']) rd['index']['record_number'] = np.array(rd['index']['record_number']) return rd def split_into_segments(idx): # We go through a uvindex dictionary and return segments. # Each segment is a single source, at a single frequency, # with a start and end time. segs = [] oldsrc = "" oldconfig = -1 sseg = None for i in xrange(0, len(idx['index']['source'])): if ((idx['index']['source'][i] != oldsrc) or (idx['index']['freq_config'][i] != oldconfig)): if ((oldsrc != "") and (oldconfig != -1)): # Put the segment on the list. segs.append(sseg) oldsrc = idx['index']['source'][i] oldconfig = idx['index']['freq_config'][i] sseg = { 'source': idx['index']['source'][i], 'freq_config': idx['index']['freq_config'][i], 'start_time': ephem.Date(idx['index']['time'][i]), 'end_time': ephem.Date(idx['index']['time'][i]) } else: sseg['end_time'] = ephem.Date(idx['index']['time'][i]) # Have to push the last segment on. segs.append(sseg) return segs def dataset_find(srcname, freq=None): srcpat = "%s.*" % srcname if (freq is not None): srcpat = "%s.%d" % (srcname, freq) matches = [] for root, dirnames, filenames in os.walk('.'): for filename in fnmatch.filter(dirnames, srcpat): # Check if this has data. fname = os.path.join(root, filename) cname = "%s/visdata" % fname if ((os.path.isdir(fname)) and (os.path.isfile(cname))): matches.append(fname) return matches def filter_uvplt(output): outlines = output.split('\n') rd = { 'nvisibilities': 0 } for i in xrange(0, len(outlines)): index_elements = outlines[i].split() if (len(index_elements) < 3): continue if ((index_elements[0] == "Read") and (index_elements[2] == "visibilities")): rd['nvisibilities'] = int(index_elements[1]) return rd def filter_closure(output): outlines = output.split('\n') rd = { 'theoretical_rms': 0, 'measured_rms': 0 } for i in xrange(0, len(outlines)): index_elements = outlines[i].split() if (len(index_elements) < 1): continue if (index_elements[0] == "Actual"): rd['measured_rms'] = float(index_elements[-1]) elif (index_elements[0] == "Theoretical"): rd['theoretical_rms'] = float(index_elements[-1]) return rd def filter_uvfstats(output): outlines = output.split('\n') rd = { 'flagged_fraction': 0 } strt = 0 nchans = 0 nflagged = 0 for i in xrange(0, len(outlines)): index_elements = outlines[i].split() if (len(index_elements) < 1): continue if (strt == 1): nchans = nchans + 1 if (index_elements[1] < 15): nflagged = nflagged + 1 else: if (index_elements[0] == "-------"): strt = 1 rd['flagged_fraction'] = "%.2f" % (nflagged / nchans) return rd def calibrate(srcname, calname, fconfig, stime, etime): smtime = datetime_to_mirtime(stime) emtime = datetime_to_mirtime(etime) selstring = "time(%s,%s)" % (smtime, emtime) print " calibrating source %s with selection %s" % (srcname, selstring) # Find all the relevant datasets. dsets = dataset_find(srcname) cfreqs = [] rv = { 'code': 0, 'frequencies': [] } for i in xrange(0, len(dsets)): fname = dsets[i] # Check if this is one of the frequencies in this configuration. setf = int(fname.split(".")[-1]) for j in xrange(0, len(fconfig['nchannels'])): c = (fconfig['frequency1'][j] + (fconfig['nchannels'][j] - 1) * fconfig['frequency_increment'][j] / 2.) * 1000. fdiff = abs(c - setf) if (fdiff <= abs(fconfig['frequency_increment'][j] * 1000.)): cfreqs.append([ setf, j, fname ]) rv['frequencies'].append(setf) # Calibrate per frequency. for i in xrange(0, len(cfreqs)): dset = cfreqs[i][2] csets = dataset_find(calname, cfreqs[i][0]) cset = csets[0] # Check that we actually have data in this time range. miriad.set_filter('uvplt', filter_uvplt) uvout = miriad.uvplt(vis=dset, axis="time,amp", device="/null", options="nopol,nocal,nopass", stokes="xx,yy", select=selstring) if (uvout['nvisibilities'] > 0): # Do the calibration. print " calibrating frequency %d MHz" % cfreqs[i][0] miriad.gpcopy(vis=cset, out=dset) miriad.gpcal(vis=dset, interval="0.1", options="xyvary,nopol,qusolve", nfbin="2", refant="3", select=selstring) miriad.gpboot(vis=dset, cal=cset, select=selstring) rv['code'] = 1 else: print " Unable to find any data for this time range!" % selstring rv['code'] = 0 return rv def measure_closure_phase(srcname, freq, stime, etime): print " closure phase %.1f MHz" % freq closurelog = "closure_log.txt" selstring = "time(%s,%s)" % (datetime_to_mirtime(stime), datetime_to_mirtime(etime)) if (os.path.isfile(closurelog)): os.remove(closurelog) # Find the data set. dsets = dataset_find(srcname, freq) miriad.set_filter('closure', filter_closure) cout = miriad.closure(vis=dsets[0], stokes="i", device="/null", options="log", select=selstring) rv = { 'closure_phase': { 'theoretical_rms': cout['theoretical_rms'], 'measured_rms': cout['measured_rms'], 'average_value': -999 } } if (os.path.isfile(closurelog)): with open(closurelog, "r") as fp: loglines = fp.readlines() pvals = [] for i in xrange(0, len(loglines)): lels = loglines[i].split() if (len(lels) < 1): continue if (lels[0] == "Antennas"): continue pvals.append(float(lels[-1])) rv['closure_phase']['average_value'] = np.average(pvals) return rv def measure_flagging_statistic(srcname, freq, stime, etime): print " flagging %.1f MHz" % freq miriad.set_filter('uvfstats', filter_uvfstats) selstring = "time(%s,%s)" % (datetime_to_mirtime(stime), datetime_to_mirtime(etime)) # Find the data set. dsets = dataset_find(srcname, freq) uo = miriad.uvfstats(vis=dsets[0], mode="channel", options="absolute,unflagged", select=selstring) return uo['flagged_fraction'] def calculate_hourangle(obs, obstime, src): obs.date = obstime src.compute(obs) lst = obs.sidereal_time() * 180. / (15. * math.pi) ra = src.ra * 180. / (15. * math.pi) ha = lst - ra if (ha < -12): ha = ha + 24 elif (ha > 12): ha = ha - 24 return ha def findWholeWord(w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search def determine_array(srcname, freq): print " determining array" dsets = dataset_find(srcname, freq) # The strings for the station configurations. configs = { '6A': "W4 W45 W102 W173 W195 W392", '6B': "W2 W64 W147 W182 W196 W392", '6C': "W0 W10 W113 W140 W182 W392", '6D': "W8 W32 W84 W168 W173 W392", '1.5A': "W100 W110 W147 W168 W196 W392", '1.5B': "W111 W113 W163 W182 W195 W392", '1.5C': "W98 W128 W173 W190 W195 W392", '1.5D': "W102 W109 W140 W182 W196 W392", '750A': "W147 W163 W172 W190 W195 W392", '750B': "W98 W109 W113 W140 W148 W392", '750C': "W64 W84 W100 W110 W113 W392", '750D': "W100 W102 W128 W140 W147 W392", 'EW367': "W104 W110 W113 W124 W128 W392", 'EW352': "W102 W104 W109 W112 W125 W392", 'H214': "W98 W104 W113 N5 N14 W392", 'H168': "W100 W104 W111 N7 N11 W392", 'H75': "W104 W106 W109 N2 N5 W392", 'EW214': "W98 W102 W104 W109 W112 W392", 'NS214': "W106 N2 N7 N11 N14 W392", '122C': "W98 W100 W102 W104 W106 W392", '375': "W2 W10 W14 W16 W32 W392", '210': "W98 W100 W102 W109 W112 W392", '122B': "W8 W10 W12 W14 W16 W392", '122A': "W0 W2 W4 W6 W8 W392" } # Get the antenna positions. miriad.set_filter('uvlist', filter_uvlist_antennas) antlist = miriad.uvlist(vis=dsets[0], options="full,array") antpos = antlist['antennas'] # Adjust to make CA06 the reference. for i in xrange(0, 6): antpos[i]['coord_x'] = -1. * (antpos[i]['coord_x'] - antpos[5]['coord_x']) antpos[i]['coord_y'] = -1. * (antpos[i]['coord_y'] - antpos[5]['coord_y']) antpos[i]['coord_z'] = -1. * (antpos[i]['coord_z'] - antpos[5]['coord_z']) station_interval = 15.3 array_stations = [] for i in xrange(0, 6): ew_offset = math.floor((antpos[i]['coord_y'] / station_interval) + 0.5) + 392 ns_offset = math.floor((antpos[i]['coord_x'] / station_interval) + 0.5) + 0 if (ns_offset == 0): array_stations.append("W%d" % ew_offset) else: array_stations.append("N%d" % ns_offset) # Find the best match. max_matches = 0 match_array = "" for a in configs: curr_match_count = 0 for i in xrange(0, len(array_stations)): if (findWholeWord(array_stations[i])(configs[a]) is not None): curr_match_count = curr_match_count + 1 if (curr_match_count > max_matches): max_matches = curr_match_count match_array = a return match_array def filter_uvfmeas(output): outlines = output.split('\n') rv = { 'fitCoefficients': [], 'alphaCoefficients': [], 'alphaReference': { 'fluxDensity': 0, 'frequency': 0 }, 'fitScatter': 0, 'mode': "", 'stokes': "" } for i in xrange(0, len(outlines)): index_elements = outlines[i].split() if (len(index_elements) < 1): continue #print "UVFMEAS: %s" % outlines[i] if (index_elements[0] == "Coeff:"): for j in xrange(1, len(index_elements)): try: rv['fitCoefficients'].append(float(index_elements[j])) except ValueError as e: rv['fitCoefficients'].append(index_elements[j]) elif (index_elements[0] == "MFCAL"): comma_elements = outlines[i][11:].split(",") if (comma_elements[0] != "*******"): rv['alphaReference']['fluxDensity'] = float(comma_elements[0]) if (comma_elements[1] != "*******"): rv['alphaReference']['frequency'] = float(comma_elements[1]) elif (index_elements[0] == "Alpha:"): for j in xrange(1, len(index_elements)): if (index_elements[j] != "*******"): rv['alphaCoefficients'].append(float(index_elements[j]))
[ " elif (index_elements[0] == \"Scatter\"):" ]
1,818
lcc
python
null
ea081b4223c2863932036461c4dda5fe46df221fbaf332de
using System; using System.Collections.Generic; using Server.Targeting; using Server.Engines.Craft; namespace Server.Items { public class KeyRing : Item, IResource, IQuality { private CraftResource _Resource; private Mobile _Crafter; private ItemQuality _Quality; [CommandProperty(AccessLevel.GameMaster)] public CraftResource Resource { get { return _Resource; } set { _Resource = value; _Resource = value; Hue = CraftResources.GetHue(_Resource); InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public Mobile Crafter { get { return _Crafter; } set { _Crafter = value; InvalidateProperties(); } } [CommandProperty(AccessLevel.GameMaster)] public ItemQuality Quality { get { return _Quality; } set { _Quality = value; InvalidateProperties(); } } public bool PlayerConstructed { get { return true; } } public static readonly int MaxKeys = 20; private List<Key> m_Keys; [Constructable] public KeyRing() : base(0x1011) { Weight = 1.0; // They seem to have no weight on OSI ?! m_Keys = new List<Key>(); } public KeyRing(Serial serial) : base(serial) { } public List<Key> Keys { get { return m_Keys; } } public override bool OnDragDrop(Mobile from, Item dropped) { if (!IsChildOf(from.Backpack)) { from.SendLocalizedMessage(1060640); // The item must be in your backpack to use it. return false; } Key key = dropped as Key; if (key == null || key.KeyValue == 0) { from.SendLocalizedMessage(501689); // Only non-blank keys can be put on a keyring. return false; } else if (Keys.Count >= MaxKeys) { from.SendLocalizedMessage(1008138); // This keyring is full. return false; } else { Add(key); from.SendLocalizedMessage(501691); // You put the key on the keyring. return true; } } public override void OnDoubleClick(Mobile from) { if (!IsChildOf(from.Backpack)) { from.SendLocalizedMessage(1060640); // The item must be in your backpack to use it. return; } from.SendLocalizedMessage(501680); // What do you want to unlock? from.Target = new InternalTarget(this); } public override void OnDelete() { base.OnDelete(); foreach (Key key in m_Keys) { key.Delete(); } m_Keys.Clear(); } public void Add(Key key) { key.Internalize(); m_Keys.Add(key); UpdateItemID(); } public void Open(Mobile from) { Container cont = Parent as Container; if (cont == null) return; for (int i = m_Keys.Count - 1; i >= 0; i--) { Key key = m_Keys[i]; if (!key.Deleted && !cont.TryDropItem(from, key, true)) break; m_Keys.RemoveAt(i); } UpdateItemID(); } public void RemoveKeys(uint keyValue) { for (int i = m_Keys.Count - 1; i >= 0; i--) { Key key = m_Keys[i]; if (key.KeyValue == keyValue) { key.Delete(); m_Keys.RemoveAt(i); } } UpdateItemID(); } public bool ContainsKey(uint keyValue) { foreach (Key key in m_Keys) { if (key.KeyValue == keyValue) return true; } return false; } public override void AddCraftedProperties(ObjectPropertyList list) { if (_Crafter != null) { list.Add(1050043, _Crafter.TitleName); // crafted by ~1_NAME~ } if (_Quality == ItemQuality.Exceptional) { list.Add(1060636); // Exceptional } } public override void AddNameProperty(ObjectPropertyList list) { if (_Resource > CraftResource.Iron) { list.Add(1053099, "#{0}\t{1}", CraftResources.GetLocalizationNumber(_Resource), String.Format("#{0}", LabelNumber.ToString())); // ~1_oretype~ ~2_armortype~ } else { base.AddNameProperty(list); } } public virtual int OnCraft(int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, ITool tool, CraftItem craftItem, int resHue) { Quality = (ItemQuality)quality; if (makersMark) Crafter = from; if (!craftItem.ForceNonExceptional) { if (typeRes == null) typeRes = craftItem.Resources.GetAt(0).ItemType; Resource = CraftResources.GetFromType(typeRes); } return quality; } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(1); // version writer.Write((int)_Resource); writer.Write(_Crafter); writer.Write((int)_Quality); writer.WriteItemList<Key>(m_Keys); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); switch (version) { case 1: _Resource = (CraftResource)reader.ReadInt(); _Crafter = reader.ReadMobile(); _Quality = (ItemQuality)reader.ReadInt(); goto case 0; case 0: m_Keys = reader.ReadStrongItemList<Key>(); break; } } private void UpdateItemID() {
[ " if (Keys.Count < 1)" ]
549
lcc
csharp
null
b293cf5f342371e0bf71c2612684f816f33409393283da9c
package org.cwepg.hr; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import org.cwepg.reg.FusionRegistryEntry; import org.cwepg.reg.Registry; import org.cwepg.reg.RegistryHelperFusion; import org.cwepg.svc.HdhrCommandLine; import org.cwepg.svc.HtmlVcrDoc; public class TunerManager { Map<String, Tuner> tuners = new TreeMap<String, Tuner>(); static TunerManager tunerManager; private String lastReason = ""; Set<String> capvSet = new TreeSet<String>(); Properties externalProps; private ArrayList<Tuner> nonResponsiveTuners = new ArrayList<Tuner>(); public static String fusionInstalledLocation; private static boolean mCountingTuners = false; public static final int VIRTUAL_MATCHING = 0; public static final int NAME_MATCHING = 1; public static boolean skipFusionInit = false; public static boolean skipRegistryForTesting = false; private TunerManager(){ if (!skipFusionInit) { fusionInstalledLocation = RegistryHelperFusion.getInstalledLocation(); if (fusionInstalledLocation == null) fusionInstalledLocation = CaptureManager.cwepgPath; if ("".equals(fusionInstalledLocation)) fusionInstalledLocation = new File("test").getAbsoluteFile().getParentFile().getAbsolutePath(); } } public static TunerManager getInstance(){ if (tunerManager == null){ tunerManager = new TunerManager(); } return tunerManager; } public int countTuners(){ mCountingTuners = true; // First, read tuners from machine (no alteration of our current list of tuners) ArrayList<Tuner> refreshedTuners = new ArrayList<Tuner>(); boolean addDevice = false; List<Tuner> hdhrTunerList = countTunersHdhr(addDevice); for (Iterator<Tuner> iter = hdhrTunerList.iterator(); iter.hasNext();) {refreshedTuners.add(iter.next());} List<Tuner> myhdTunerList = countTunersMyhd(addDevice); for (Iterator<Tuner> iter = myhdTunerList.iterator(); iter.hasNext();) {refreshedTuners.add(iter.next());} List<?> fusionTunerList = countTunersFusion(addDevice, false); for (Iterator<?> iter = fusionTunerList.iterator(); iter.hasNext();) {refreshedTuners.add((Tuner)iter.next());} // DRS 20110619 - Added 2 - externalTuner List<Tuner> externalTunerList = countTunersExternal(addDevice); for (Iterator<Tuner> iter = externalTunerList.iterator(); iter.hasNext();) {refreshedTuners.add(iter.next());} // Next, loop through existing tuners looking for changed/deleted tuners ArrayList<Tuner> deletedTuners = new ArrayList<Tuner>(); for (Iterator<String> iter = tuners.keySet().iterator(); iter.hasNext();) { Tuner existingTuner = tuners.get(iter.next()); if (refreshedTuners.contains(existingTuner)){ // The two lists contain the same item. // This means we don't need to do anything. // We just remove the tuner from the refreshedTuners list // (since anything left in the list, we will be adding later). refreshedTuners.remove(existingTuner); // but the old (existing tuner) might have different lineup, so refresh that refreshLineup(existingTuner); // THIS CLEARS ANY EXISTING CHANNELS } else { // this existing tuner is changed or deleted // see if we can find it by name boolean found = false; for (Tuner tuner : refreshedTuners) { if (tuner.getFullName().equals(existingTuner.getFullName())){ // take the attributes off of the tuner we just created // and update the existing tuner. found = true; existingTuner.setAnalogFileExtension(tuner.getAnalogFileExtension()); existingTuner.setLiveDevice(tuner.getLiveDevice()); existingTuner.setRecordPath(tuner.getRecordPath()); // We just remove the tuner from the refreshedTuners list // (since anything left in the list, we will be adding later // and we don't want to add this because the existing tuner // just got updated with what we needed). refreshedTuners.remove(existingTuner); // but the old (existing tuner) might have different lineup, so refresh that refreshLineup(existingTuner); } if (found) break; } if (!found){ // The latest and best list from our recent refresh did not // include the tuner, we must conclude it's gone now, so // we will delete it shortly. deletedTuners.add(existingTuner); } } } //remove any deleted tuners for (Tuner tuner : deletedTuners) { System.out.println(new Date() + " Removing deleted tuner: " + tuner.getFullName()); this.tuners.remove(tuner.getFullName()); tuner.removeAllCaptures(true); //before deleting a tuner, delete it's captures } // DRS 20210415 - Added 'for' loop + 1 - Concurrent Modification Exception for (Tuner tuner : nonResponsiveTuners) { System.out.println(new Date() + " Removing non-responsive tuner: " + tuner.getFullName()); this.tuners.remove(tuner.getFullName()); tuner.removeAllCaptures(true); //before deleting a tuner, delete it's captures } nonResponsiveTuners.clear(); // any tuners left in the refreshed list need to be added to the tuner manager for (Tuner tuner : refreshedTuners) { System.out.println(new Date() + " Adding new or changed: " + tuner.getFullName()); // refreshed tuners are not added to the tuner manager and did not pick-up captures from file, so do both this.tuners.put(tuner.getFullName(), tuner); tuner.addCapturesFromStore(); try {refreshLineup(tuner);} catch (Throwable t) {System.out.println(new Date() + " Problem refreshing lineup on new or changed tuner " + t.getMessage());}; } mCountingTuners = false; System.out.println(new Date() + " TunerManager.countTuners returned " + this.tuners.size() + " tuners."); return this.tuners.size(); } // DRS 20190422 - Added method // DRS 20210415 - Changed non-responsive tuners to instance variable (delete later) - Concurrent Modification Exception public void removeHdhrByUrl(String url) { nonResponsiveTuners = new ArrayList<Tuner>(); for (Entry<String, Tuner> entry : this.tuners.entrySet()) { Tuner aTuner = entry.getValue(); if (aTuner instanceof TunerHdhr) { TunerHdhr hdhrTuner = (TunerHdhr)aTuner; if(url.contains(hdhrTuner.ipAddressTuner)) { nonResponsiveTuners.add(hdhrTuner); } } } // DRS 20210415 - Commented 'for' loop - Concurrent Modification Exception //for (Tuner tuner : deletedTuners) { // System.out.println(new Date() + " Removing non-responsive tuner: " + tuner.getFullName()); // this.tuners.remove(tuner.getFullName()); // tuner.removeAllCaptures(true); //before deleting a tuner, delete it's captures //} } private void refreshLineup(Tuner existingTuner) { try { existingTuner.scanRefreshLineUp(true, existingTuner.lineUp.signalType, 10000); } catch (Throwable e){ String msg = new Date() + " ERROR: Could not refresh lineup for an existing tuner " + existingTuner; System.out.println(msg); System.err.println(msg); e.printStackTrace(); } } /* This Method Only Used in Testing */ public void countTuner(int tunerType, boolean addDevice){ removeAllTuners(); switch (tunerType) { case Tuner.FUSION_TYPE: countTunersFusion(addDevice, false); break; case Tuner.MYHD_TYPE: countTunersMyhd(addDevice); break; case Tuner.HDHR_TYPE: countTunersHdhr(addDevice); break; case Tuner.EXTERNAL_TYPE: countTunersExternal(addDevice); break; } return; } public List<Tuner> countTunersFusion(boolean addDevice, boolean test){ ArrayList<Tuner> tunerList = new ArrayList<Tuner>(); if (TunerManager.skipFusionInit) return tunerList; String controlSetName = "CurrentControlSet"; if (test) controlSetName = "ControlSet0002"; Map<String, FusionRegistryEntry> entries = RegistryHelperFusion.getFusionRegistryEntries(controlSetName); try { int analogFileExtensionNumber = Registry.getIntValue("HKEY_CURRENT_USER", "Software\\Dvico\\ZuluHDTV\\Data", "AnalogRecProfile"); Map<String, Map> lookupTables = TunerManager.getLookupTables(); if (lookupTables == null) return tunerList; // DRS 20210114 - Added 1 - If we get an null here, return empty list and stop any more attempts...all hope is lost. Map<String, String> recordPathsByNumber = lookupTables.get("recordPathsByNumber"); Map<String, String> recordPathsByName = lookupTables.get("recordPathsByName"); Map<String, String> names = lookupTables.get("names"); // if the names array has a matching uinumber, then we apply the name, else we keep default for (Iterator<String> iter = entries.keySet().iterator(); iter.hasNext();) { FusionRegistryEntry entry = entries.get(iter.next()); entry.setNameUsingKey(names); entry.setRecordPathUsingKey(recordPathsByNumber, recordPathsByName); entry.setAnalogFileExtensionNumber(analogFileExtensionNumber); System.out.println(entry); tunerList.add(new TunerFusion(entry, false)); } } catch (Exception e) { System.out.println(new Date() + " ERROR: Problem with countTunersFusion: " + e.getMessage()); System.err.println(new Date() + " ERROR: Problem with countTunersFusion: " + e.getMessage()); e.printStackTrace(); } return tunerList; } public static Map<String, Map> getLookupTables() { HashMap<String, String> recordPathsByNumber = new HashMap<String, String>(); HashMap<String, String> recordPathsByName = new HashMap<String, String>(); HashMap<String, String> names = new HashMap<String, String>(); /**** Get Data from the Data or DeviceN branch(es) if they exist ****/ try { // record path for single device registry String[] registryBranchSingle = {"HKEY_CURRENT_USER", "Software\\Dvico\\ZuluHDTV\\Data", ""}; if (Registry.valueExists(registryBranchSingle[0],registryBranchSingle[1],"DeviceMainUID")){ String recordPathEntry = Registry.getStringValue(registryBranchSingle[0], registryBranchSingle[1], "RecordPath"); String deviceMainUidEntry = "" + Registry.getIntValue(registryBranchSingle[0], registryBranchSingle[1], "DeviceMainUID"); String modelNameEntry = Registry.getStringValue(registryBranchSingle[0], registryBranchSingle[1], "ModelName"); System.out.println(registryBranchSingle[1] + "\\RecordPath=" + recordPathEntry); System.out.println(registryBranchSingle[1] + "\\DeviceMainUID=" + deviceMainUidEntry); System.out.println(registryBranchSingle[1] + "\\ModelName=" + modelNameEntry); recordPathsByNumber.put (deviceMainUidEntry , recordPathEntry); recordPathsByName.put (modelNameEntry, recordPathEntry); } // record paths and names for multiple device registry for (int i = 1; i < 5; i++){ String[] registryBranch = {"HKEY_CURRENT_USER", "Software\\Dvico\\ZuluHDTV\\Data\\Device" + i,""}; if (Registry.valueExists(registryBranch[0],registryBranch[1],"UINumber")){ String recordPathEntry = Registry.getStringValue(registryBranch[0], registryBranch[1], "RecordPath"); String modelNameEntry = Registry.getStringValue(registryBranch[0], registryBranch[1], "ModelName"); String uiNumberEntry = "" + Registry.getIntValue(registryBranch[0],registryBranch[1],"UINumber"); System.out.println(registryBranch[1] + "\\RecordPath=" + recordPathEntry); System.out.println(registryBranch[1] + "\\UINumber=" + uiNumberEntry); System.out.println(registryBranch[1] + "\\ModelName=" + modelNameEntry); names.put (uiNumberEntry, modelNameEntry); recordPathsByNumber.put (uiNumberEntry, recordPathEntry); recordPathsByName.put (modelNameEntry, recordPathEntry); } else { break; } } } catch (UnsupportedEncodingException e1) { System.out.println(new Date() + " ERROR: Failed to get data from DeviceN branch:" + e1.getMessage()); System.err.println(new Date() + " ERROR: Failed to get data from DeviceN branch:" + e1.getMessage()); e1.printStackTrace(); } // Just for debugging for (Iterator<String> iterator = names.keySet().iterator(); iterator.hasNext();) { String uinumber = iterator.next(); String name = names.get(uinumber); String recordPath = recordPathsByNumber.get(uinumber); System.out.println(new Date() + " Names after DeviceN Branch(es): " + name + "." + uinumber + " RecordPath:" + recordPath); } /**** Get Possible Names from Fusion Table ****/ Connection connection = null; Statement statement = null; ResultSet rs = null; String mdbFileName = "Epg2List.Mdb"; String localPathFile = fusionInstalledLocation + "\\" + mdbFileName; String tableName = "DeviceList"; if (!(new File(localPathFile).exists()))System.out.println(new Date() + " WARNING: Fusion database file " + localPathFile + " does not exist. Fusion tuner naming might be impared."); try { //connection = DriverManager.getConnection("jdbc:odbc:Driver={M icroSoft Access Driver (*.mdb)};DBQ=" + localPathFile); connection = DriverManager.getConnection("jdbc:ucanaccess://" + localPathFile + ";singleConnection=true"); statement = connection.createStatement(); String sql = "select * from " + tableName; System.out.println(new Date() + " " + sql); rs = statement.executeQuery(sql); while (rs.next()){ int devId = rs.getInt("devId"); String devNm = rs.getString("devNm"); int parenLoc = devNm.indexOf(")"); if (parenLoc > -1 && parenLoc < devNm.length()) devNm = devNm.substring(parenLoc + 1); names.put("" + devId, devNm); } statement.close(); connection.close(); } catch (SQLException e) { System.out.println(new Date() + " ERROR: TunerManager.getLookupTables:" + e.getMessage()); //System.err.println(new Date() + " ERROR: TunerManager.countTunersFusion:" + e.getMessage()); //e.printStackTrace(); return null; // DRS 20210114 - Added 1 - If we get an error here, return null and stop any more attempts...all hope is lost. } finally { try { if (rs != null) rs.close(); } catch (Throwable t){}; try { if (statement != null) statement.close(); } catch (Throwable t){}; try { if (connection != null) connection.close(); } catch (Throwable t){}; } // Just for debugging for (Iterator<String> iterator = names.keySet().iterator(); iterator.hasNext();) { String uinumber = iterator.next(); String name = names.get(uinumber); System.out.println(new Date() + " Names after Epg2List: " + name + "." + uinumber); } /****** Save the data and return *********/ HashMap<String, Map> lookupTables = new HashMap<String, Map>(); lookupTables.put("recordPathsByNumber", recordPathsByNumber); lookupTables.put("recordPathsByName", recordPathsByName); lookupTables.put("names", names); return lookupTables; } private List<Tuner> countTunersMyhd(boolean addDevice){ ArrayList<Tuner> tunerList = new ArrayList<Tuner>(); // if registry entry exists, presume the tuner is still there String recordPath = null; try { if (TunerManager.skipRegistryForTesting) return tunerList; recordPath = Registry.getStringValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\MyHD", "HD_DIR_NAME_FOR_RESCAP"); int i = 0; while (recordPath == null && i < 12){ try {Thread.sleep(250);} catch (Exception e){}; recordPath = Registry.getStringValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\MyHD", "HD_DIR_NAME_FOR_RESCAP"); i++; } if (recordPath != null){ Tuner tuner = new TunerMyhd(recordPath, addDevice); // automatically added to TunerManager list tuner.liveDevice = true; tunerList.add(tuner); } else { System.out.println(new Date() + " No MyHD registry data found."); } } catch (Exception e){ System.out.println(new Date() + " No MyHD registry data found." + e.getMessage()); } return tunerList; } // DRS 20120315 - Altered method - if there are valid captures, then wait, try again, and set liveDevice. public List<Tuner> countTunersHdhr(boolean addDevice){ ArrayList<Tuner> tunerList = new ArrayList<Tuner>(); // To be returned from this method. Live (including retry to get live), and not disabled. if (!new File(CaptureManager.hdhrPath + File.separator + "hdhomerun_config.exe").exists()){ System.out.println("Could not find [" + new File(CaptureManager.hdhrPath + File.separator + "hdhomerun_config.exe" + "]")); return tunerList; // if no exe exists, return an empty tuner list without doing any work. } TreeSet<String> devices = new TreeSet<String>(); // Working list. May include non-live to start with, added from discover.txt. // Get file devices (from last discover.txt file) String fileDiscoverText = getFileDiscoverText(); ArrayList<String> fileDevices = findTunerDevicesFromText(fileDiscoverText, false); System.out.println(new Date() + " Got " + fileDevices.size() + " items from discover.txt"); devices.addAll(fileDevices); // Get live devices String liveDiscoverText = getLiveDiscoverText(CaptureManager.discoverRetries, CaptureManager.discoverDelay); ArrayList<String> liveDevices = findTunerDevicesFromText(liveDiscoverText, true); // devices.txt is always written out here (we read the old one already). System.out.println(new Date() + " Got " + liveDevices.size() + " items from active discover command."); devices.addAll(liveDevices); System.out.println(new Date() + " Total of " + devices.size() + " items, accounting for duplication."); // Only if we picked-up a different device from the discover.txt file do we go into this logic that eliminates devices that do not come alive on retry if (liveDevices.size() < devices.size() ) { devices = eliminateDevicesThatDoNotComeAliveOnRetry(devices, liveDevices, fileDevices); // Now "devices" contains all live devices, even ones that had to be retried to get them going. // devices.txt is written out with whatever the result was after retrying } // DRS 20181103 - Adding IP address to HDHR tuners HashMap<String, String> ipAddressMap = getIpMap(fileDiscoverText, liveDiscoverText); // DRS 20181025 - Adding model to HDHR tuners HashMap<String, Integer> liveModelMap = getLiveModelMap(liveDevices, 1, CaptureManager.discoverDelay, ipAddressMap); // Loop final list of devices
[ " for (String device : devices) {" ]
1,943
lcc
java
null
e7cf53f84107ea1aeedbca65bba9b70350df8c2b9d1a949d
package org.thoughtcrime.securesms.migrations; import android.content.Context; import androidx.annotation.NonNull; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.signal.core.util.logging.Log; import org.thoughtcrime.securesms.jobmanager.JobManager; import org.thoughtcrime.securesms.keyvalue.SignalStore; import org.thoughtcrime.securesms.stickers.BlessedPacks; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.thoughtcrime.securesms.util.VersionTracker; import java.util.LinkedHashMap; import java.util.Map; /** * Manages application-level migrations. * * Migrations can be slotted to occur based on changes in the canonical version code * (see {@link Util#getCanonicalVersionCode()}). * * Migrations are performed via {@link MigrationJob}s. These jobs are durable and are run before any * other job, allowing you to schedule safe migrations. Furthermore, you may specify that a * migration is UI-blocking, at which point we will show a spinner via * {@link ApplicationMigrationActivity} if the user opens the app while the migration is in * progress. */ public class ApplicationMigrations { private static final String TAG = Log.tag(ApplicationMigrations.class); private static final MutableLiveData<Boolean> UI_BLOCKING_MIGRATION_RUNNING = new MutableLiveData<>(); private static final int LEGACY_CANONICAL_VERSION = 455; public static final int CURRENT_VERSION = 36; private static final class Version { static final int LEGACY = 1; static final int RECIPIENT_ID = 2; static final int RECIPIENT_SEARCH = 3; static final int RECIPIENT_CLEANUP = 4; static final int AVATAR_MIGRATION = 5; static final int UUIDS = 6; static final int CACHED_ATTACHMENTS = 7; static final int STICKERS_LAUNCH = 8; //static final int TEST_ARGON2 = 9; static final int SWOON_STICKERS = 10; static final int STORAGE_SERVICE = 11; //static final int STORAGE_KEY_ROTATE = 12; static final int REMOVE_AVATAR_ID = 13; static final int STORAGE_CAPABILITY = 14; static final int PIN_REMINDER = 15; static final int VERSIONED_PROFILE = 16; static final int PIN_OPT_OUT = 17; static final int TRIM_SETTINGS = 18; static final int THUMBNAIL_CLEANUP = 19; static final int GV2 = 20; static final int GV2_2 = 21; static final int CDS = 22; static final int BACKUP_NOTIFICATION = 23; static final int GV1_MIGRATION = 24; static final int USER_NOTIFICATION = 25; static final int DAY_BY_DAY_STICKERS = 26; static final int BLOB_LOCATION = 27; static final int SYSTEM_NAME_SPLIT = 28; // Versions 29, 30 accidentally skipped static final int MUTE_SYNC = 31; static final int PROFILE_SHARING_UPDATE = 32; static final int SMS_STORAGE_SYNC = 33; static final int APPLY_UNIVERSAL_EXPIRE = 34; static final int SENDER_KEY = 35; static final int SENDER_KEY_2 = 36; } /** * This *must* be called after the {@link JobManager} has been instantiated, but *before* the call * to {@link JobManager#beginJobLoop()}. Otherwise, other non-migration jobs may have started * executing before we add the migration jobs. */ public static void onApplicationCreate(@NonNull Context context, @NonNull JobManager jobManager) { if (isLegacyUpdate(context)) { Log.i(TAG, "Detected the need for a legacy update. Last seen canonical version: " + VersionTracker.getLastSeenVersion(context)); TextSecurePreferences.setAppMigrationVersion(context, 0); } if (!isUpdate(context)) { Log.d(TAG, "Not an update. Skipping."); VersionTracker.updateLastSeenVersion(context); return; } else { Log.d(TAG, "About to update. Clearing deprecation flag."); SignalStore.misc().clearClientDeprecated(); } final int lastSeenVersion = TextSecurePreferences.getAppMigrationVersion(context); Log.d(TAG, "currentVersion: " + CURRENT_VERSION + ", lastSeenVersion: " + lastSeenVersion); LinkedHashMap<Integer, MigrationJob> migrationJobs = getMigrationJobs(context, lastSeenVersion); if (migrationJobs.size() > 0) { Log.i(TAG, "About to enqueue " + migrationJobs.size() + " migration(s)."); boolean uiBlocking = true; int uiBlockingVersion = lastSeenVersion; for (Map.Entry<Integer, MigrationJob> entry : migrationJobs.entrySet()) { int version = entry.getKey(); MigrationJob job = entry.getValue(); uiBlocking &= job.isUiBlocking(); if (uiBlocking) { uiBlockingVersion = version; } jobManager.add(job); jobManager.add(new MigrationCompleteJob(version)); } if (uiBlockingVersion > lastSeenVersion) { Log.i(TAG, "Migration set is UI-blocking through version " + uiBlockingVersion + "."); UI_BLOCKING_MIGRATION_RUNNING.setValue(true); } else { Log.i(TAG, "Migration set is non-UI-blocking."); UI_BLOCKING_MIGRATION_RUNNING.setValue(false); } final long startTime = System.currentTimeMillis(); final int uiVersion = uiBlockingVersion; EventBus.getDefault().register(new Object() { @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) public void onMigrationComplete(MigrationCompleteEvent event) { Log.i(TAG, "Received MigrationCompleteEvent for version " + event.getVersion() + ". (Current: " + CURRENT_VERSION + ")"); if (event.getVersion() > CURRENT_VERSION) { throw new AssertionError("Received a higher version than the current version? App downgrades are not supported. (received: " + event.getVersion() + ", current: " + CURRENT_VERSION + ")"); } Log.i(TAG, "Updating last migration version to " + event.getVersion()); TextSecurePreferences.setAppMigrationVersion(context, event.getVersion()); if (event.getVersion() == CURRENT_VERSION) { Log.i(TAG, "Migration complete. Took " + (System.currentTimeMillis() - startTime) + " ms."); EventBus.getDefault().unregister(this); VersionTracker.updateLastSeenVersion(context); UI_BLOCKING_MIGRATION_RUNNING.setValue(false); } else if (event.getVersion() >= uiVersion) { Log.i(TAG, "Version is >= the UI-blocking version. Posting 'false'."); UI_BLOCKING_MIGRATION_RUNNING.setValue(false); } } }); } else { Log.d(TAG, "No migrations."); TextSecurePreferences.setAppMigrationVersion(context, CURRENT_VERSION); VersionTracker.updateLastSeenVersion(context); UI_BLOCKING_MIGRATION_RUNNING.setValue(false); } } /** * @return A {@link LiveData} object that will update with whether or not a UI blocking migration * is in progress. */ public static LiveData<Boolean> getUiBlockingMigrationStatus() { return UI_BLOCKING_MIGRATION_RUNNING; } /** * @return True if a UI blocking migration is running. */ public static boolean isUiBlockingMigrationRunning() { Boolean value = UI_BLOCKING_MIGRATION_RUNNING.getValue(); return value != null && value; } /** * @return Whether or not we're in the middle of an update, as determined by the last seen and * current version. */ public static boolean isUpdate(@NonNull Context context) { return isLegacyUpdate(context) || TextSecurePreferences.getAppMigrationVersion(context) < CURRENT_VERSION; } private static LinkedHashMap<Integer, MigrationJob> getMigrationJobs(@NonNull Context context, int lastSeenVersion) { LinkedHashMap<Integer, MigrationJob> jobs = new LinkedHashMap<>(); if (lastSeenVersion < Version.LEGACY) { jobs.put(Version.LEGACY, new LegacyMigrationJob()); } if (lastSeenVersion < Version.RECIPIENT_ID) { jobs.put(Version.RECIPIENT_ID, new DatabaseMigrationJob()); } if (lastSeenVersion < Version.RECIPIENT_SEARCH) { jobs.put(Version.RECIPIENT_SEARCH, new RecipientSearchMigrationJob()); } if (lastSeenVersion < Version.RECIPIENT_CLEANUP) { jobs.put(Version.RECIPIENT_CLEANUP, new DatabaseMigrationJob()); } if (lastSeenVersion < Version.AVATAR_MIGRATION) { jobs.put(Version.AVATAR_MIGRATION, new AvatarMigrationJob()); } if (lastSeenVersion < Version.UUIDS) { jobs.put(Version.UUIDS, new UuidMigrationJob()); } if (lastSeenVersion < Version.CACHED_ATTACHMENTS) { jobs.put(Version.CACHED_ATTACHMENTS, new CachedAttachmentsMigrationJob()); } if (lastSeenVersion < Version.STICKERS_LAUNCH) { jobs.put(Version.STICKERS_LAUNCH, new StickerLaunchMigrationJob()); } // This migration only triggered a test we aren't interested in any more. // if (lastSeenVersion < Version.TEST_ARGON2) { // jobs.put(Version.TEST_ARGON2, new Argon2TestMigrationJob()); // } if (lastSeenVersion < Version.SWOON_STICKERS) { jobs.put(Version.SWOON_STICKERS, new StickerAdditionMigrationJob(BlessedPacks.SWOON_HANDS, BlessedPacks.SWOON_FACES)); } if (lastSeenVersion < Version.STORAGE_SERVICE) { jobs.put(Version.STORAGE_SERVICE, new StorageServiceMigrationJob()); } // Superceded by StorageCapabilityMigrationJob // if (lastSeenVersion < Version.STORAGE_KEY_ROTATE) { // jobs.put(Version.STORAGE_KEY_ROTATE, new StorageKeyRotationMigrationJob()); // } if (lastSeenVersion < Version.REMOVE_AVATAR_ID) { jobs.put(Version.REMOVE_AVATAR_ID, new AvatarIdRemovalMigrationJob()); } if (lastSeenVersion < Version.STORAGE_CAPABILITY) { jobs.put(Version.STORAGE_CAPABILITY, new StorageCapabilityMigrationJob()); } if (lastSeenVersion < Version.PIN_REMINDER) { jobs.put(Version.PIN_REMINDER, new PinReminderMigrationJob()); } if (lastSeenVersion < Version.VERSIONED_PROFILE) { jobs.put(Version.VERSIONED_PROFILE, new ProfileMigrationJob()); } if (lastSeenVersion < Version.PIN_OPT_OUT) { jobs.put(Version.PIN_OPT_OUT, new PinOptOutMigration()); } if (lastSeenVersion < Version.TRIM_SETTINGS) { jobs.put(Version.TRIM_SETTINGS, new TrimByLengthSettingsMigrationJob()); } if (lastSeenVersion < Version.THUMBNAIL_CLEANUP) { jobs.put(Version.THUMBNAIL_CLEANUP, new DatabaseMigrationJob()); } if (lastSeenVersion < Version.GV2) { jobs.put(Version.GV2, new AttributesMigrationJob()); } if (lastSeenVersion < Version.GV2_2) { jobs.put(Version.GV2_2, new AttributesMigrationJob()); } if (lastSeenVersion < Version.CDS) { jobs.put(Version.CDS, new DirectoryRefreshMigrationJob()); } if (lastSeenVersion < Version.BACKUP_NOTIFICATION) { jobs.put(Version.BACKUP_NOTIFICATION, new BackupNotificationMigrationJob()); } if (lastSeenVersion < Version.GV1_MIGRATION) { jobs.put(Version.GV1_MIGRATION, new AttributesMigrationJob()); }
[ " if (lastSeenVersion < Version.USER_NOTIFICATION) {" ]
1,057
lcc
java
null
98f6d04d0820f21a99dd26399514e157795b7254b994a3ab
package edu.stanford.nlp.ie.regexp; import edu.stanford.nlp.util.logging.Redwood; import java.io.BufferedReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import edu.stanford.nlp.ie.AbstractSequenceClassifier; import edu.stanford.nlp.io.IOUtils; import edu.stanford.nlp.io.RuntimeIOException; import edu.stanford.nlp.ling.CoreLabel; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.sequences.DocumentReaderAndWriter; import edu.stanford.nlp.util.CoreMap; import edu.stanford.nlp.util.Generics; /** * A sequence classifier that labels tokens with types based on a simple manual mapping from * regular expressions to the types of the entities they are meant to describe. * The user provides a file formatted as follows: * <pre> * regex1 TYPE overwritableType1,Type2... priority * regex2 TYPE overwritableType1,Type2... priority * ... * </pre> * where each argument is tab-separated, and the last two arguments are optional. Several regexes can be * associated with a single type. In the case where multiple regexes match a phrase, the priority ranking * is used to choose between the possible types. This classifier is designed to be used as part of a full * NER system to label entities that don't fall into the usual NER categories. It only records the label * if the token has not already been NER-annotated, or it has been annotated but the NER-type has been * designated overwritable (the third argument). Note that this is evaluated token-wise in this classifier, * and so it may assign a label against a token sequence that is partly background and partly overwritable. * (In contrast, RegexNERAnnotator doesn't allow this.) * It assigns labels to AnswerAnnotation, while checking for existing labels in NamedEntityTagAnnotation. * * The first column regex may be a sequence of regex, each separated by whitespace (matching "\\s+"). * The regex will match if the successive regex match a sequence of tokens in the input. * Spaces can only be used to separate regular expression tokens; within tokens \\s or similar non-space * representations need to be used instead. * Notes: Following Java regex conventions, some characters in the file need to be escaped. Only a single * backslash should be used though, as these are not String literals. The input to RegexNER will have * already been tokenized. So, for example, with our usual English tokenization, things like genitives * and commas at the end of words will be separated in the input and matched as a separate token. * * This class isn't implemented very efficiently, since every regex is evaluated at every token position. * So it can and does get quite slow if you have a lot of patterns in your NER rules. * {@code TokensRegex} is a more general framework to provide the functionality of this class. * But at present we still use this class. * * @author jtibs * @author Mihai */ public class RegexNERSequenceClassifier extends AbstractSequenceClassifier<CoreLabel> { /** A logger for this class */ private static Redwood.RedwoodChannels log = Redwood.channels(RegexNERSequenceClassifier.class); private final List<Entry> entries; private final Set<String> myLabels; private final boolean ignoreCase; // Make this a property? (But already done as a property at CoreNLP level.) // ms: but really this should be rewritten from scratch // we should have a language to specify regexes over *tokens*, where each token could be a regular Java regex (over words, POSs, etc.) private final Pattern validPosPattern; public static final String DEFAULT_VALID_POS = "^(NN|JJ)"; public RegexNERSequenceClassifier(String mapping, boolean ignoreCase, boolean overwriteMyLabels) { this(mapping, ignoreCase, overwriteMyLabels, DEFAULT_VALID_POS); } /** * Make a new instance of this classifier. The ignoreCase option allows case-insensitive * regular expression matching, allowing the idea that the provided file might just * be a manual list of the possible entities for each type. * * @param mapping A String describing a file/classpath/URI for the RegexNER patterns * @param ignoreCase The regex in the mapping file should be compiled ignoring case * @param overwriteMyLabels If true, this classifier overwrites NE labels generated through * this regex NER. This is necessary because sometimes the * RegexNERSequenceClassifier is run successively over the same * text (e.g., to overwrite some older annotations). * @param validPosRegex May be null or an empty String, in which case any (or no) POS is valid * in matching. Otherwise, this is a regex which is matched with find() * [not matches()] and which must be matched by the POS of at least one * word in the sequence for it to be labeled via any matching rules. * (Note that this is a postfilter; using this will not speed up matching.) */ public RegexNERSequenceClassifier(String mapping, boolean ignoreCase, boolean overwriteMyLabels, String validPosRegex) { super(new Properties()); if (validPosRegex != null && !validPosRegex.equals("")) { validPosPattern = Pattern.compile(validPosRegex); } else { validPosPattern = null; } BufferedReader rd = null; try { rd = IOUtils.readerFromString(mapping); entries = readEntries(rd, ignoreCase); } catch (IOException e) { throw new RuntimeIOException("Couldn't read RegexNER from " + mapping, e); } finally { IOUtils.closeIgnoringExceptions(rd); } this.ignoreCase = ignoreCase; myLabels = Generics.newHashSet(); // Can always override background or none. myLabels.add(flags.backgroundSymbol); myLabels.add(null); if (overwriteMyLabels) { for (Entry entry: entries) myLabels.add(entry.type); } // log.info("RegexNER using labels: " + myLabels); } /** * Make a new instance of this classifier. The ignoreCase option allows case-insensitive * regular expression matching, allowing the idea that the provided file might just * be a manual list of the possible entities for each type. * * @param reader A Reader for the RegexNER patterns * @param ignoreCase The regex in the mapping file should be compiled ignoring case * @param overwriteMyLabels If true, this classifier overwrites NE labels generated through * this regex NER. This is necessary because sometimes the * RegexNERSequenceClassifier is run successively over the same * text (e.g., to overwrite some older annotations). * @param validPosRegex May be null or an empty String, in which case any (or no) POS is valid * in matching. Otherwise, this is a regex, and only words with a POS that * match the regex will be labeled via any matching rules. */ public RegexNERSequenceClassifier(BufferedReader reader, boolean ignoreCase, boolean overwriteMyLabels, String validPosRegex) { super(new Properties()); if (validPosRegex != null && !validPosRegex.equals("")) { validPosPattern = Pattern.compile(validPosRegex); } else { validPosPattern = null; } try { entries = readEntries(reader, ignoreCase); } catch (IOException e) { throw new RuntimeIOException("Couldn't read RegexNER from reader", e); } this.ignoreCase = ignoreCase; myLabels = Generics.newHashSet(); // Can always override background or none. myLabels.add(flags.backgroundSymbol); myLabels.add(null); if (overwriteMyLabels) { for (Entry entry: entries) myLabels.add(entry.type); } // log.info("RegexNER using labels: " + myLabels); } private static class Entry implements Comparable<Entry> { public List<Pattern> regex; // the regex, tokenized by splitting on white space public List<String> exact = new ArrayList<>(); public String type; // the associated type public Set<String> overwritableTypes; public double priority; public Entry(List<Pattern> regex, String type, Set<String> overwritableTypes, double priority) { this.regex = regex; this.type = type.intern(); this.overwritableTypes = overwritableTypes; this.priority = priority; // Efficiency shortcut for (Pattern p : regex) { if (p.toString().matches("[a-zA-Z0-9]+")) { exact.add(p.toString()); } else { exact.add(null); } } } /** If the given priorities are equal, an entry whose regex has more tokens is assigned * a higher priority. This implementation is not fine-grained enough to be consistent with equals. */ @Override public int compareTo(Entry other) { if (this.priority > other.priority) return -1; if (this.priority < other.priority) return 1; return other.regex.size() - this.regex.size(); } public String toString() { return "Entry{" + regex + ' ' + type + ' ' + overwritableTypes + ' ' + priority + '}'; } } private boolean containsValidPos(List<CoreLabel> tokens, int start, int end) { if (validPosPattern == null) { return true; } // log.info("CHECKING " + start + " " + end); for (int i = start; i < end; i ++) { // log.info("TAG = " + tokens.get(i).tag()); if (tokens.get(i).tag() == null) { throw new IllegalArgumentException("RegexNER was asked to check for valid tags on an untagged sequence. Either tag the sequence, perhaps with the pos annotator, or create RegexNER with an empty validPosPattern, perhaps with the property regexner.validpospattern"); } Matcher m = validPosPattern.matcher(tokens.get(i).tag()); if (m.find()) return true; } return false; } @Override public List<CoreLabel> classify(List<CoreLabel> document) { // This is pretty deathly slow. It loops over each entry, and then loops over each document token for it. // We could gain by compiling into disjunctions patterns for the same class with the same priorities and restrictions? for (Entry entry : entries) { int start = 0; // the index of the token from which we begin our search each iteration while (true) { // only search the part of the document that we haven't yet considered // log.info("REGEX FIND MATCH FOR " + entry.regex.toString()); start = findStartIndex(entry, document, start, myLabels, this.ignoreCase); if (start < 0) break; // no match found // make sure we annotate only valid POS tags if (containsValidPos(document, start, start + entry.regex.size())) { // annotate each matching token for (int i = start; i < start + entry.regex.size(); i++) { CoreLabel token = document.get(i); token.set(CoreAnnotations.AnswerAnnotation.class, entry.type); } } start++; } } return document; } /** * Creates a combined list of Entries using the provided mapping file, and sorts them by * first by priority, then the number of tokens in the regex. * * @param mapping The Reader containing RegexNER mappings. It's lines are counted from 1 * @return a sorted list of Entries */ private static List<Entry> readEntries(BufferedReader mapping, boolean ignoreCase) throws IOException { List<Entry> entries = new ArrayList<>(); int lineCount = 0; for (String line; (line = mapping.readLine()) != null; ) { lineCount ++; String[] split = line.split("\t");
[ " if (split.length < 2 || split.length > 4)" ]
1,566
lcc
java
null
4bd2fd0f69e4de7c6c60f4067b514b23e77ab94af50551f3
"""SCons.Scanner.LaTeX This module implements the dependency scanner for LaTeX code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # 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. # __revision__ = "src/engine/SCons/Scanner/LaTeX.py 5134 2010/08/16 23:02:40 bdeegan" import os.path import re import SCons.Scanner import SCons.Util # list of graphics file extensions for TeX and LaTeX TexGraphics = ['.eps', '.ps'] LatexGraphics = ['.pdf', '.png', '.jpg', '.gif', '.tif'] # Used as a return value of modify_env_var if the variable is not set. class _Null(object): pass _null = _Null # The user specifies the paths in env[variable], similar to other builders. # They may be relative and must be converted to absolute, as expected # by LaTeX and Co. The environment may already have some paths in # env['ENV'][var]. These paths are honored, but the env[var] paths have # higher precedence. All changes are un-done on exit. def modify_env_var(env, var, abspath): try: save = env['ENV'][var] except KeyError: save = _null env.PrependENVPath(var, abspath) try: if SCons.Util.is_List(env[var]): env.PrependENVPath(var, [os.path.abspath(str(p)) for p in env[var]]) else: # Split at os.pathsep to convert into absolute path env.PrependENVPath(var, [os.path.abspath(p) for p in str(env[var]).split(os.pathsep)]) except KeyError: pass # Convert into a string explicitly to append ":" (without which it won't search system # paths as well). The problem is that env.AppendENVPath(var, ":") # does not work, refuses to append ":" (os.pathsep). if SCons.Util.is_List(env['ENV'][var]): env['ENV'][var] = os.pathsep.join(env['ENV'][var]) # Append the trailing os.pathsep character here to catch the case with no env[var] env['ENV'][var] = env['ENV'][var] + os.pathsep return save class FindENVPathDirs(object): """A class to bind a specific *PATH variable name to a function that will return all of the *path directories.""" def __init__(self, variable): self.variable = variable def __call__(self, env, dir=None, target=None, source=None, argument=None): import SCons.PathList try: path = env['ENV'][self.variable] except KeyError: return () dir = dir or env.fs._cwd path = SCons.PathList.PathList(path).subst_path(env, target, source) return tuple(dir.Rfindalldirs(path)) def LaTeXScanner(): """Return a prototype Scanner instance for scanning LaTeX source files when built with latex. """ ds = LaTeX(name = "LaTeXScanner", suffixes = '$LATEXSUFFIXES', # in the search order, see below in LaTeX class docstring graphics_extensions = TexGraphics, recursive = 0) return ds def PDFLaTeXScanner(): """Return a prototype Scanner instance for scanning LaTeX source files when built with pdflatex. """ ds = LaTeX(name = "PDFLaTeXScanner", suffixes = '$LATEXSUFFIXES', # in the search order, see below in LaTeX class docstring graphics_extensions = LatexGraphics, recursive = 0) return ds class LaTeX(SCons.Scanner.Base): """Class for scanning LaTeX files for included files. Unlike most scanners, which use regular expressions that just return the included file name, this returns a tuple consisting of the keyword for the inclusion ("include", "includegraphics", "input", or "bibliography"), and then the file name itself. Based on a quick look at LaTeX documentation, it seems that we should append .tex suffix for the "include" keywords, append .tex if there is no extension for the "input" keyword, and need to add .bib for the "bibliography" keyword that does not accept extensions by itself. Finally, if there is no extension for an "includegraphics" keyword latex will append .ps or .eps to find the file, while pdftex may use .pdf, .jpg, .tif, .mps, or .png. The actual subset and search order may be altered by DeclareGraphicsExtensions command. This complication is ignored. The default order corresponds to experimentation with teTeX $ latex --version pdfeTeX 3.141592-1.21a-2.2 (Web2C 7.5.4) kpathsea version 3.5.4 The order is: ['.eps', '.ps'] for latex ['.png', '.pdf', '.jpg', '.tif']. Another difference is that the search path is determined by the type of the file being searched: env['TEXINPUTS'] for "input" and "include" keywords env['TEXINPUTS'] for "includegraphics" keyword env['TEXINPUTS'] for "lstinputlisting" keyword env['BIBINPUTS'] for "bibliography" keyword env['BSTINPUTS'] for "bibliographystyle" keyword FIXME: also look for the class or style in document[class|style]{} FIXME: also look for the argument of bibliographystyle{} """ keyword_paths = {'include': 'TEXINPUTS', 'input': 'TEXINPUTS', 'includegraphics': 'TEXINPUTS', 'bibliography': 'BIBINPUTS', 'bibliographystyle': 'BSTINPUTS', 'usepackage': 'TEXINPUTS', 'lstinputlisting': 'TEXINPUTS'} env_variables = SCons.Util.unique(list(keyword_paths.values())) def __init__(self, name, suffixes, graphics_extensions, *args, **kw): # We have to include \n with the % we exclude from the first part # part of the regex because the expression is compiled with re.M. # Without the \n, the ^ could match the beginning of a *previous* # line followed by one or more newline characters (i.e. blank # lines), interfering with a match on the next line. # add option for whitespace before the '[options]' or the '{filename}' regex = r'^[^%\n]*\\(include|includegraphics(?:\s*\[[^\]]+\])?|lstinputlisting(?:\[[^\]]+\])?|input|bibliography|usepackage)\s*{([^}]*)}' self.cre = re.compile(regex, re.M) self.comment_re = re.compile(r'^((?:(?:\\%)|[^%\n])*)(.*)$', re.M) self.graphics_extensions = graphics_extensions def _scan(node, env, path=(), self=self): node = node.rfile() if not node.exists(): return [] return self.scan_recurse(node, path) class FindMultiPathDirs(object): """The stock FindPathDirs function has the wrong granularity: it is called once per target, while we need the path that depends on what kind of included files is being searched. This wrapper hides multiple instances of FindPathDirs, one per the LaTeX path variable in the environment. When invoked, the function calculates and returns all the required paths as a dictionary (converted into a tuple to become hashable). Then the scan function converts it back and uses a dictionary of tuples rather than a single tuple of paths. """ def __init__(self, dictionary): self.dictionary = {} for k,n in dictionary.items(): self.dictionary[k] = ( SCons.Scanner.FindPathDirs(n), FindENVPathDirs(n) ) def __call__(self, env, dir=None, target=None, source=None, argument=None): di = {} for k,(c,cENV) in self.dictionary.items(): di[k] = ( c(env, dir=None, target=None, source=None, argument=None) , cENV(env, dir=None, target=None, source=None, argument=None) ) # To prevent "dict is not hashable error" return tuple(di.items()) class LaTeXScanCheck(object): """Skip all but LaTeX source files, i.e., do not scan *.eps, *.pdf, *.jpg, etc. """ def __init__(self, suffixes): self.suffixes = suffixes def __call__(self, node, env): current = not node.has_builder() or node.is_up_to_date() scannable = node.get_suffix() in env.subst_list(self.suffixes)[0] # Returning false means that the file is not scanned. return scannable and current kw['function'] = _scan kw['path_function'] = FindMultiPathDirs(LaTeX.keyword_paths) kw['recursive'] = 0 kw['skeys'] = suffixes kw['scan_check'] = LaTeXScanCheck(suffixes) kw['name'] = name SCons.Scanner.Base.__init__(self, *args, **kw) def _latex_names(self, include): filename = include[1] if include[0] == 'input': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.tex'] if (include[0] == 'include'): return [filename + '.tex'] if include[0] == 'bibliography': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.bib'] if include[0] == 'usepackage': base, ext = os.path.splitext( filename ) if ext == "": return [filename + '.sty'] if include[0] == 'includegraphics': base, ext = os.path.splitext( filename ) if ext == "": #return [filename+e for e in self.graphics_extensions + TexGraphics] # use the line above to find dependencies for the PDF builder # when only an .eps figure is present. Since it will be found # if the user tells scons how to make the pdf figure, leave # it out for now. return [filename+e for e in self.graphics_extensions] return [filename] def sort_key(self, include): return SCons.Node.FS._my_normcase(str(include)) def find_include(self, include, source_dir, path): try: sub_path = path[include[0]] except (IndexError, KeyError): sub_path = () try_names = self._latex_names(include) for n in try_names: # see if we find it using the path in env[var]
[ " i = SCons.Node.FS.find_file(n, (source_dir,) + sub_path[0])" ]
1,329
lcc
python
null
51cad9bbad6cbc55c69a6d0f523dbdfc409b670b50b64d77
# # This file is part of Mapnik (C++/Python mapping toolkit) # Copyright (C) 2009 Artem Pavlenko # # Mapnik 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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # """Mapnik Python module. Boost Python bindings to the Mapnik C++ shared library. Several things happen when you do: >>> import mapnik 1) Mapnik C++ objects are imported via the '__init__.py' from the '_mapnik.so' shared object (_mapnik.pyd on win) which references libmapnik.so (linux), libmapnik.dylib (mac), or mapnik.dll (win32). 2) The paths to the input plugins and font directories are imported from the 'paths.py' file which was constructed and installed during SCons installation. 3) All available input plugins and TrueType fonts are automatically registered. 4) Boost Python metaclass injectors are used in the '__init__.py' to extend several objects adding extra convenience when accessed via Python. """ import itertools import os import sys import warnings try: import json except ImportError: import simplejson as json def bootstrap_env(): """ If an optional settings file exists, inherit its environment settings before loading the mapnik library. This feature is intended for customized packages of mapnik. The settings file should be a python file with an 'env' variable that declares a dictionary of key:value pairs to push into the global process environment, if not already set, like: env = {'ICU_DATA':'/usr/local/share/icu/'} """ if os.path.exists(os.path.join(os.path.dirname(__file__),'mapnik_settings.py')): from mapnik_settings import env process_keys = os.environ.keys() for key, value in env.items(): if key not in process_keys: os.environ[key] = value bootstrap_env() from _mapnik import * from paths import inputpluginspath from paths import fontscollectionpath import printing printing.renderer = render # The base Boost.Python class BoostPythonMetaclass = Coord.__class__ class _MapnikMetaclass(BoostPythonMetaclass): def __init__(self, name, bases, dict): for b in bases: if type(b) not in (self, type): for k,v in list(dict.items()): if hasattr(b, k): setattr(b, '_c_'+k, getattr(b, k)) setattr(b,k,v) return type.__init__(self, name, bases, dict) # metaclass injector compatible with both python 2 and 3 # http://mikewatkins.ca/2008/11/29/python-2-and-3-metaclasses/ _injector = _MapnikMetaclass('_injector', (object, ), {}) def Filter(*args,**kwargs): warnings.warn("'Filter' is deprecated and will be removed in Mapnik 3.x, use 'Expression' instead", DeprecationWarning, 2) return Expression(*args, **kwargs) class Envelope(Box2d): def __init__(self, *args, **kwargs): warnings.warn("'Envelope' is deprecated and will be removed in Mapnik 3.x, use 'Box2d' instead", DeprecationWarning, 2) Box2d.__init__(self, *args, **kwargs) class _Coord(Coord,_injector): """ Represents a point with two coordinates (either lon/lat or x/y). Following operators are defined for Coord: Addition and subtraction of Coord objects: >>> Coord(10, 10) + Coord(20, 20) Coord(30.0, 30.0) >>> Coord(10, 10) - Coord(20, 20) Coord(-10.0, -10.0) Addition, subtraction, multiplication and division between a Coord and a float: >>> Coord(10, 10) + 1 Coord(11.0, 11.0) >>> Coord(10, 10) - 1 Coord(-9.0, -9.0) >>> Coord(10, 10) * 2 Coord(20.0, 20.0) >>> Coord(10, 10) / 2 Coord(5.0, 5.0) Equality of coords (as pairwise equality of components): >>> Coord(10, 10) is Coord(10, 10) False >>> Coord(10, 10) == Coord(10, 10) True """ def __repr__(self): return 'Coord(%s,%s)' % (self.x, self.y) def forward(self, projection): """ Projects the point from the geographic coordinate space into the cartesian space. The x component is considered to be longitude, the y component the latitude. Returns the easting (x) and northing (y) as a coordinate pair. Example: Project the geographic coordinates of the city center of Stuttgart into the local map projection (GK Zone 3/DHDN, EPSG 31467) >>> p = Projection('+init=epsg:31467') >>> Coord(9.1, 48.7).forward(p) Coord(3507360.12813,5395719.2749) """ return forward_(self, projection) def inverse(self, projection): """ Projects the point from the cartesian space into the geographic space. The x component is considered to be the easting, the y component to be the northing. Returns the longitude (x) and latitude (y) as a coordinate pair. Example: Project the cartesian coordinates of the city center of Stuttgart in the local map projection (GK Zone 3/DHDN, EPSG 31467) into geographic coordinates: >>> p = Projection('+init=epsg:31467') >>> Coord(3507360.12813,5395719.2749).inverse(p) Coord(9.1, 48.7) """ return inverse_(self, projection) class _Box2d(Box2d,_injector): """ Represents a spatial envelope (i.e. bounding box). Following operators are defined for Box2d: Addition: e1 + e2 is equvalent to e1.expand_to_include(e2) but yields a new envelope instead of modifying e1 Subtraction: Currently e1 - e2 returns e1. Multiplication and division with floats: Multiplication and division change the width and height of the envelope by the given factor without modifying its center.. That is, e1 * x is equivalent to: e1.width(x * e1.width()) e1.height(x * e1.height()), except that a new envelope is created instead of modifying e1. e1 / x is equivalent to e1 * (1.0/x). Equality: two envelopes are equal if their corner points are equal. """ def __repr__(self): return 'Box2d(%s,%s,%s,%s)' % \ (self.minx,self.miny,self.maxx,self.maxy) def forward(self, projection): """ Projects the envelope from the geographic space into the cartesian space by projecting its corner points. See also: Coord.forward(self, projection) """ return forward_(self, projection) def inverse(self, projection): """ Projects the envelope from the cartesian space into the geographic space by projecting its corner points. See also: Coord.inverse(self, projection). """ return inverse_(self, projection) class _Projection(Projection,_injector): def __repr__(self): return "Projection('%s')" % self.params() def forward(self,obj): """ Projects the given object (Box2d or Coord) from the geographic space into the cartesian space. See also: Box2d.forward(self, projection), Coord.forward(self, projection). """ return forward_(obj,self) def inverse(self,obj): """ Projects the given object (Box2d or Coord) from the cartesian space into the geographic space. See also: Box2d.inverse(self, projection), Coord.inverse(self, projection). """ return inverse_(obj,self) class _Feature(Feature,_injector): __geo_interface__ = property(lambda self: json.loads(self.to_geojson())) class _Path(Path,_injector): __geo_interface__ = property(lambda self: json.loads(self.to_geojson())) class _Datasource(Datasource,_injector): def all_features(self,fields=None): query = Query(self.envelope()) attributes = fields or self.fields() for fld in attributes: query.add_property_name(fld) return self.features(query).features def featureset(self,fields=None): query = Query(self.envelope()) attributes = fields or self.fields() for fld in attributes: query.add_property_name(fld) return self.features(query) class _Color(Color,_injector): def __repr__(self): return "Color(R=%d,G=%d,B=%d,A=%d)" % (self.r,self.g,self.b,self.a) class _ProcessedText(ProcessedText, _injector): def append(self, properties, text): #More pythonic name self.push_back(properties, text) class _Symbolizers(Symbolizers,_injector): def __getitem__(self, idx): sym = Symbolizers._c___getitem__(self, idx) return sym.symbol() def _add_symbol_method_to_symbolizers(vars=globals()): def symbol_for_subcls(self): return self def symbol_for_cls(self): return getattr(self,self.type())() for name, obj in vars.items(): if name.endswith('Symbolizer') and not name.startswith('_'): if name == 'Symbolizer': symbol = symbol_for_cls else: symbol = symbol_for_subcls type('dummy', (obj,_injector), {'symbol': symbol}) _add_symbol_method_to_symbolizers() def Datasource(**keywords): """Wrapper around CreateDatasource. Create a Mapnik Datasource using a dictionary of parameters. Keywords must include: type='plugin_name' # e.g. type='gdal' See the convenience factory methods of each input plugin for details on additional required keyword arguments. """ return CreateDatasource(keywords) # convenience factory methods def Shapefile(**keywords): """Create a Shapefile Datasource. Required keyword arguments: file -- path to shapefile without extension Optional keyword arguments: base -- path prefix (default None) encoding -- file encoding (default 'utf-8') >>> from mapnik import Shapefile, Layer >>> shp = Shapefile(base='/home/mapnik/data',file='world_borders') >>> lyr = Layer('Shapefile Layer') >>> lyr.datasource = shp """ keywords['type'] = 'shape' return CreateDatasource(keywords) def CSV(**keywords): """Create a CSV Datasource. Required keyword arguments: file -- path to csv Optional keyword arguments: inline -- inline CSV string (if provided 'file' argument will be ignored and non-needed) base -- path prefix (default None) encoding -- file encoding (default 'utf-8') row_limit -- integer limit of rows to return (default: 0) strict -- throw an error if an invalid row is encountered escape -- The escape character to use for parsing data quote -- The quote character to use for parsing data separator -- The separator character to use for parsing data headers -- A comma separated list of header names that can be set to add headers to data that lacks them filesize_max -- The maximum filesize in MB that will be accepted >>> from mapnik import CSV >>> csv = CSV(file='test.csv') >>> from mapnik import CSV >>> csv = CSV(inline='''wkt,Name\n"POINT (120.15 48.47)","Winthrop, WA"''') For more information see https://github.com/mapnik/mapnik/wiki/CSV-Plugin """ keywords['type'] = 'csv' return CreateDatasource(keywords) def GeoJSON(**keywords): """Create a GeoJSON Datasource. Required keyword arguments: file -- path to json Optional keyword arguments: encoding -- file encoding (default 'utf-8') base -- path prefix (default None) >>> from mapnik import GeoJSON >>> geojson = GeoJSON(file='test.json') """ keywords['type'] = 'geojson' return CreateDatasource(keywords) def PostGIS(**keywords): """Create a PostGIS Datasource. Required keyword arguments: dbname -- database name to connect to table -- table name or subselect query *Note: if using subselects for the 'table' value consider also passing the 'geometry_field' and 'srid' and 'extent_from_subquery' options and/or specifying the 'geometry_table' option. Optional db connection keyword arguments: user -- database user to connect as (default: see postgres docs) password -- password for database user (default: see postgres docs) host -- portgres hostname (default: see postgres docs) port -- postgres port (default: see postgres docs) initial_size -- integer size of connection pool (default: 1) max_size -- integer max of connection pool (default: 10) persist_connection -- keep connection open (default: True) Optional table-level keyword arguments: extent -- manually specified data extent (comma delimited string, default: None) estimate_extent -- boolean, direct PostGIS to use the faster, less accurate `estimate_extent` over `extent` (default: False) extent_from_subquery -- boolean, direct Mapnik to query Postgis for the extent of the raw 'table' value (default: uses 'geometry_table') geometry_table -- specify geometry table to use to look up metadata (default: automatically parsed from 'table' value) geometry_field -- specify geometry field to use (default: first entry in geometry_columns) srid -- specify srid to use (default: auto-detected from geometry_field) row_limit -- integer limit of rows to return (default: 0) cursor_size -- integer size of binary cursor to use (default: 0, no binary cursor is used) >>> from mapnik import PostGIS, Layer >>> params = dict(dbname='mapnik',table='osm',user='postgres',password='gis') >>> params['estimate_extent'] = False >>> params['extent'] = '-20037508,-19929239,20037508,19929239' >>> postgis = PostGIS(**params) >>> lyr = Layer('PostGIS Layer') >>> lyr.datasource = postgis """ keywords['type'] = 'postgis' return CreateDatasource(keywords) def Raster(**keywords): """Create a Raster (Tiff) Datasource. Required keyword arguments: file -- path to stripped or tiled tiff lox -- lowest (min) x/longitude of tiff extent loy -- lowest (min) y/latitude of tiff extent hix -- highest (max) x/longitude of tiff extent hiy -- highest (max) y/latitude of tiff extent Hint: lox,loy,hix,hiy make a Mapnik Box2d Optional keyword arguments: base -- path prefix (default None) multi -- whether the image is in tiles on disk (default False) Multi-tiled keyword arguments: x_width -- virtual image number of tiles in X direction (required) y_width -- virtual image number of tiles in Y direction (required) tile_size -- if an image is in tiles, how large are the tiles (default 256) tile_stride -- if an image is in tiles, what's the increment between rows/cols (default 1) >>> from mapnik import Raster, Layer >>> raster = Raster(base='/home/mapnik/data',file='elevation.tif',lox=-122.8,loy=48.5,hix=-122.7,hiy=48.6) >>> lyr = Layer('Tiff Layer') >>> lyr.datasource = raster """ keywords['type'] = 'raster' return CreateDatasource(keywords) def Gdal(**keywords): """Create a GDAL Raster Datasource. Required keyword arguments: file -- path to GDAL supported dataset Optional keyword arguments: base -- path prefix (default None) shared -- boolean, open GdalDataset in shared mode (default: False) bbox -- tuple (minx, miny, maxx, maxy). If specified, overrides the bbox detected by GDAL. >>> from mapnik import Gdal, Layer >>> dataset = Gdal(base='/home/mapnik/data',file='elevation.tif') >>> lyr = Layer('GDAL Layer from TIFF file') >>> lyr.datasource = dataset """ keywords['type'] = 'gdal' if 'bbox' in keywords: if isinstance(keywords['bbox'], (tuple, list)): keywords['bbox'] = ','.join([str(item) for item in keywords['bbox']]) return CreateDatasource(keywords) def Occi(**keywords): """Create a Oracle Spatial (10g) Vector Datasource. Required keyword arguments: user -- database user to connect as password -- password for database user host -- oracle host to connect to (does not refer to SID in tsnames.ora) table -- table name or subselect query Optional keyword arguments: initial_size -- integer size of connection pool (default 1) max_size -- integer max of connection pool (default 10) extent -- manually specified data extent (comma delimited string, default None) estimate_extent -- boolean, direct Oracle to use the faster, less accurate estimate_extent() over extent() (default False) encoding -- file encoding (default 'utf-8') geometry_field -- specify geometry field (default 'GEOLOC') use_spatial_index -- boolean, force the use of the spatial index (default True) >>> from mapnik import Occi, Layer >>> params = dict(host='myoracle',user='scott',password='tiger',table='test') >>> params['estimate_extent'] = False >>> params['extent'] = '-20037508,-19929239,20037508,19929239' >>> oracle = Occi(**params) >>> lyr = Layer('Oracle Spatial Layer') >>> lyr.datasource = oracle """ keywords['type'] = 'occi' return CreateDatasource(keywords) def Ogr(**keywords): """Create a OGR Vector Datasource. Required keyword arguments: file -- path to OGR supported dataset layer -- name of layer to use within datasource (optional if layer_by_index or layer_by_sql is used) Optional keyword arguments: layer_by_index -- choose layer by index number instead of by layer name or sql. layer_by_sql -- choose layer by sql query number instead of by layer name or index. base -- path prefix (default None) encoding -- file encoding (default 'utf-8') >>> from mapnik import Ogr, Layer >>> datasource = Ogr(base='/home/mapnik/data',file='rivers.geojson',layer='OGRGeoJSON') >>> lyr = Layer('OGR Layer from GeoJSON file') >>> lyr.datasource = datasource """ keywords['type'] = 'ogr' return CreateDatasource(keywords) def SQLite(**keywords): """Create a SQLite Datasource. Required keyword arguments: file -- path to SQLite database file table -- table name or subselect query Optional keyword arguments: base -- path prefix (default None) encoding -- file encoding (default 'utf-8') extent -- manually specified data extent (comma delimited string, default None) metadata -- name of auxillary table containing record for table with xmin, ymin, xmax, ymax, and f_table_name geometry_field -- name of geometry field (default 'the_geom') key_field -- name of primary key field (default 'OGC_FID') row_offset -- specify a custom integer row offset (default 0) row_limit -- specify a custom integer row limit (default 0) wkb_format -- specify a wkb type of 'spatialite' (default None) use_spatial_index -- boolean, instruct sqlite plugin to use Rtree spatial index (default True) >>> from mapnik import SQLite, Layer >>> sqlite = SQLite(base='/home/mapnik/data',file='osm.db',table='osm',extent='-20037508,-19929239,20037508,19929239') >>> lyr = Layer('SQLite Layer') >>> lyr.datasource = sqlite """ keywords['type'] = 'sqlite' return CreateDatasource(keywords) def Rasterlite(**keywords): """Create a Rasterlite Datasource. Required keyword arguments: file -- path to Rasterlite database file table -- table name or subselect query Optional keyword arguments: base -- path prefix (default None) extent -- manually specified data extent (comma delimited string, default None) >>> from mapnik import Rasterlite, Layer >>> rasterlite = Rasterlite(base='/home/mapnik/data',file='osm.db',table='osm',extent='-20037508,-19929239,20037508,19929239') >>> lyr = Layer('Rasterlite Layer') >>> lyr.datasource = rasterlite """ keywords['type'] = 'rasterlite' return CreateDatasource(keywords) def Osm(**keywords): """Create a Osm Datasource. Required keyword arguments: file -- path to OSM file Optional keyword arguments: encoding -- file encoding (default 'utf-8') url -- url to fetch data (default None) bbox -- data bounding box for fetching data (default None) >>> from mapnik import Osm, Layer >>> datasource = Osm(file='test.osm') >>> lyr = Layer('Osm Layer') >>> lyr.datasource = datasource """ # note: parser only supports libxml2 so not exposing option # parser -- xml parser to use (default libxml2) keywords['type'] = 'osm' return CreateDatasource(keywords) def Python(**keywords): """Create a Python Datasource. >>> from mapnik import Python, PythonDatasource >>> datasource = Python('PythonDataSource') >>> lyr = Layer('Python datasource') >>> lyr.datasource = datasource """ keywords['type'] = 'python' return CreateDatasource(keywords) class PythonDatasource(object): """A base class for a Python data source. Optional arguments: envelope -- a mapnik.Box2d (minx, miny, maxx, maxy) envelope of the data source, default (-180,-90,180,90) geometry_type -- one of the DataGeometryType enumeration values, default Point data_type -- one of the DataType enumerations, default Vector """ def __init__(self, envelope=None, geometry_type=None, data_type=None): self.envelope = envelope or Box2d(-180, -90, 180, 90) self.geometry_type = geometry_type or DataGeometryType.Point self.data_type = data_type or DataType.Vector def features(self, query): """Return an iterable which yields instances of Feature for features within the passed query. Required arguments: query -- a Query instance specifying the region for which features should be returned """ return None def features_at_point(self, point): """Rarely uses. Return an iterable which yields instances of Feature for the specified point.""" return None @classmethod def wkb_features(cls, keys, features): """A convenience function to wrap an iterator yielding pairs of WKB format geometry and dictionaries of key-value pairs into mapnik features. Return this from PythonDatasource.features() passing it a sequence of keys to appear in the output and an iterator yielding features. For example. One might have a features() method in a derived class like the following: def features(self, query): # ... create WKB features feat1 and feat2 return mapnik.PythonDatasource.wkb_features( keys = ( 'name', 'author' ), features = [ (feat1, { 'name': 'feat1', 'author': 'alice' }), (feat2, { 'name': 'feat2', 'author': 'bob' }), ] ) """ ctx = Context() [ctx.push(x) for x in keys] def make_it(feat, idx): f = Feature(ctx, idx) geom, attrs = feat f.add_geometries_from_wkb(geom) for k, v in attrs.iteritems(): f[k] = v return f return itertools.imap(make_it, features, itertools.count(1)) @classmethod def wkt_features(cls, keys, features): """A convenience function to wrap an iterator yielding pairs of WKT format geometry and dictionaries of key-value pairs into mapnik features. Return this from PythonDatasource.features() passing it a sequence of keys to appear in the output and an iterator yielding features. For example. One might have a features() method in a derived class like the following: def features(self, query): # ... create WKT features feat1 and feat2 return mapnik.PythonDatasource.wkt_features( keys = ( 'name', 'author' ), features = [ (feat1, { 'name': 'feat1', 'author': 'alice' }), (feat2, { 'name': 'feat2', 'author': 'bob' }), ] ) """
[ " ctx = Context()" ]
2,860
lcc
python
null
992dbc69af1a3576bbb2ed62504f814872db7f713f6b9a74
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_monitor_ldap short_description: Manages BIG-IP LDAP monitors description: - Manages BIG-IP LDAP monitors. version_added: 2.8 options: name: description: - Monitor name. required: True description: description: - Specifies descriptive text that identifies the monitor. parent: description: - The parent template of this monitor template. Once this value has been set, it cannot be changed. - By default, this value is the C(ldap) parent on the C(Common) partition. default: "/Common/ldap" ip: description: - IP address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. port: description: - Port address part of the IP/port definition. If this parameter is not provided when creating a new monitor, then the default value will be '*'. - Note that if specifying an IP address, a value between 1 and 65535 must be specified. interval: description: - Specifies, in seconds, the frequency at which the system issues the monitor check when either the resource is down or the status of the resource is unknown. timeout: description: - Specifies the number of seconds the target has in which to respond to the monitor request. - If the target responds within the set time period, it is considered 'up'. If the target does not respond within the set time period, it is considered 'down'. When this value is set to 0 (zero), the system uses the interval from the parent monitor. - Note that C(timeout) and C(time_until_up) combine to control when a resource is set to up. time_until_up: description: - Specifies the number of seconds to wait after a resource first responds correctly to the monitor before setting the resource to 'up'. - During the interval, all responses from the resource must be correct. - When the interval expires, the resource is marked 'up'. - A value of 0, means that the resource is marked up immediately upon receipt of the first correct response. up_interval: description: - Specifies the interval for the system to use to perform the health check when a resource is up. - When C(0), specifies that the system uses the interval specified in C(interval) to check the health of the resource. - When any other number, enables specification of a different interval to use when checking the health of a resource that is up. manual_resume: description: - Specifies whether the system automatically changes the status of a resource to B(enabled) at the next successful monitor check. - If you set this option to C(yes), you must manually re-enable the resource before the system can use it for load balancing connections. - When C(yes), specifies that you must manually re-enable the resource after an unsuccessful monitor check. - When C(no), specifies that the system automatically changes the status of a resource to B(enabled) at the next successful monitor check. type: bool target_username: description: - Specifies the user name, if the monitored target requires authentication. target_password: description: - Specifies the password, if the monitored target requires authentication. base: description: - Specifies the location in the LDAP tree from which the monitor starts the health check. filter: description: - Specifies an LDAP key for which the monitor searches. security: description: - Specifies the secure protocol type for communications with the target. choices: - none - ssl - tls mandatory_attributes: description: - Specifies whether the target must include attributes in its response to be considered up. type: bool chase_referrals: description: - Specifies whether, upon receipt of an LDAP referral entry, the target follows (or chases) that referral. type: bool debug: description: - Specifies whether the monitor sends error messages and additional information to a log file created and labeled specifically for this monitor. type: bool update_password: description: - C(always) will update passwords if the C(target_password) is specified. - C(on_create) will only set the password for newly created monitors. default: always choices: - always - on_create partition: description: - Device partition to manage resources on. default: Common state: description: - When C(present), ensures that the monitor exists. - When C(absent), ensures the monitor is removed. default: present choices: - present - absent extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = r''' - name: Create a LDAP monitor bigip_monitor_ldap: name: foo provider: password: secret server: lb.mydomain.com user: admin delegate_to: localhost ''' RETURN = r''' parent: description: New parent template of the monitor. returned: changed type: str sample: ldap description: description: The description of the monitor. returned: changed type: str sample: Important_Monitor ip: description: The new IP of IP/port definition. returned: changed type: str sample: 10.12.13.14 interval: description: The new interval in which to run the monitor check. returned: changed type: int sample: 2 timeout: description: The new timeout in which the remote system must respond to the monitor. returned: changed type: int sample: 10 time_until_up: description: The new time in which to mark a system as up after first successful response. returned: changed type: int sample: 2 security: description: The new Security setting of the resource. returned: changed type: str sample: ssl debug: description: The new Debug setting of the resource. returned: changed type: bool sample: yes mandatory_attributes: description: The new Mandatory Attributes setting of the resource. returned: changed type: bool sample: no chase_referrals: description: The new Chase Referrals setting of the resource. returned: changed type: bool sample: yes manual_resume: description: The new Manual Resume setting of the resource. returned: changed type: bool sample: no filter: description: The new LDAP Filter setting of the resource. returned: changed type: str sample: filter1 base: description: The new LDAP Base setting of the resource. returned: changed type: str sample: base ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import env_fallback try: from library.module_utils.network.f5.bigip import F5RestClient from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import fq_name from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import exit_json from library.module_utils.network.f5.common import fail_json from library.module_utils.network.f5.common import transform_name from library.module_utils.network.f5.common import flatten_boolean from library.module_utils.network.f5.ipaddress import is_valid_ip from library.module_utils.network.f5.compare import cmp_str_with_none except ImportError: from ansible.module_utils.network.f5.bigip import F5RestClient from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import fq_name from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import exit_json from ansible.module_utils.network.f5.common import fail_json from ansible.module_utils.network.f5.common import transform_name from ansible.module_utils.network.f5.common import flatten_boolean from ansible.module_utils.network.f5.ipaddress import is_valid_ip from ansible.module_utils.network.f5.compare import cmp_str_with_none class Parameters(AnsibleF5Parameters): api_map = { 'timeUntilUp': 'time_until_up', 'defaultsFrom': 'parent', 'mandatoryAttributes': 'mandatory_attributes', 'chaseReferrals': 'chase_referrals', 'manualResume': 'manual_resume', 'username': 'target_username', 'password': 'target_password', } api_attributes = [ 'timeUntilUp', 'defaultsFrom', 'interval', 'timeout', 'destination', 'description', 'security', 'mandatoryAttributes', 'chaseReferrals', 'debug', 'manualResume', 'username', 'password', 'filter', 'base', ] returnables = [ 'parent', 'ip', 'destination', 'port', 'interval', 'timeout', 'time_until_up', 'description', 'security', 'debug', 'mandatory_attributes', 'chase_referrals', 'manual_resume', 'filter', 'base', ] updatables = [ 'destination', 'interval', 'timeout', 'time_until_up', 'description', 'security', 'debug', 'mandatory_attributes', 'chase_referrals', 'manual_resume', 'target_username', 'target_password', 'filter', 'base', ] @property def timeout(self): if self._values['timeout'] is None: return None return int(self._values['timeout']) @property def time_until_up(self): if self._values['time_until_up'] is None: return None return int(self._values['time_until_up']) @property def mandatory_attributes(self): return flatten_boolean(self._values['mandatory_attributes']) @property def chase_referrals(self): return flatten_boolean(self._values['chase_referrals']) @property def debug(self): return flatten_boolean(self._values['debug']) @property def manual_resume(self): return flatten_boolean(self._values['manual_resume']) @property def security(self): if self._values['security'] in ['none', None]: return '' return self._values['security'] class ApiParameters(Parameters): @property def ip(self): ip, port = self._values['destination'].split(':') return ip @property def port(self): ip, port = self._values['destination'].split(':') try: return int(port) except ValueError: return port @property def description(self): if self._values['description'] in [None, 'none']: return None return self._values['description'] class ModuleParameters(Parameters): @property def ip(self): if self._values['ip'] is None: return None if self._values['ip'] in ['*', '0.0.0.0']: return '*' elif is_valid_ip(self._values['ip']): return self._values['ip'] else: raise F5ModuleError( "The provided 'ip' parameter is not an IP address." ) @property def parent(self): if self._values['parent'] is None: return None result = fq_name(self.partition, self._values['parent']) return result @property def port(self): if self._values['port'] is None: return None elif self._values['port'] == '*': return '*' return int(self._values['port']) @property def destination(self): if self.ip is None and self.port is None: return None destination = '{0}:{1}'.format(self.ip, self.port) return destination @destination.setter def destination(self, value): ip, port = value.split(':') self._values['ip'] = ip self._values['port'] = port @property def interval(self): if self._values['interval'] is None: return None if 1 > int(self._values['interval']) > 86400: raise F5ModuleError( "Interval value must be between 1 and 86400" ) return int(self._values['interval']) @property def type(self): return 'ldap' @property def description(self): if self._values['description'] is None: return None elif self._values['description'] in ['none', '']: return '' return self._values['description'] class Changes(Parameters): def to_return(self): result = {} try: for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) except Exception: pass return result class UsableChanges(Changes): @property def manual_resume(self): if self._values['manual_resume'] is None: return None if self._values['manual_resume'] == 'yes': return 'enabled' return 'disabled' class ReportableChanges(Changes): @property def manual_resume(self): return flatten_boolean(self._values['manual_resume']) @property def ip(self): ip, port = self._values['destination'].split(':') return ip @property def port(self): ip, port = self._values['destination'].split(':') return int(port) class Difference(object): def __init__(self, want, have=None): self.want = want self.have = have def compare(self, param): try: result = getattr(self, param) return result except AttributeError: return self.__default(param) @property def parent(self): if self.want.parent != self.have.parent: raise F5ModuleError( "The parent monitor cannot be changed" ) @property def destination(self): if self.want.ip is None and self.want.port is None: return None if self.want.port is None: self.want.update({'port': self.have.port}) if self.want.ip is None: self.want.update({'ip': self.have.ip}) if self.want.port in [None, '*'] and self.want.ip != '*': raise F5ModuleError( "Specifying an IP address requires that a port number be specified" )
[ " if self.want.destination != self.have.destination:" ]
1,555
lcc
python
null
de56fbc358675175235c1b81f44c85afbdf421ee3d426fe4
# -*- coding: utf-8 -*- import attr from copy import copy from cached_property import cached_property from navmazing import NavigateToAttribute, NavigateToSibling from widgetastic.utils import ParametrizedLocator from widgetastic.widget import Table, Text, View, ParametrizedView, Select, ClickableMixin from widgetastic_manageiq import SummaryFormItem, ScriptBox, Input from widgetastic_patternfly import BootstrapSelect, BootstrapSwitch, Button, CandidateNotFound from cfme.exceptions import ItemNotFound from cfme.modeling.base import BaseCollection, BaseEntity from cfme.utils.appliance.implementations.ui import navigator, CFMENavigateStep, navigate_to from cfme.utils.blockers import BZ from cfme.utils.timeutil import parsetime from cfme.utils.wait import wait_for from . import AutomateExplorerView, check_tree_path from .common import Copiable, CopyViewBase from .klass import ClassDetailsView class Inputs(View, ClickableMixin): ROOT = './/button[@id="exp_collapse_img"]/i' INDIRECT = True # TODO: This appear to upset the parent lookup combined with ParView @property def is_opened(self): return 'fa-angle-up' in self.browser.classes(self) def child_widget_accessed(self, widget): if not self.is_opened: self.click() @ParametrizedView.nested class inputs(ParametrizedView): # noqa PARAMETERS = ('name', ) ROOT = ParametrizedLocator('//tr[./td[2]/input[normalize-space(@value)={name|quote}]]') ALL_FIELDS = '//div[@id="inputs_div"]/table//tr/td[2]/input' @cached_property def row_id(self): attr = self.browser.get_attribute( 'id', './/td/input[contains(@id, "fields_name_")]', parent=self) return int(attr.rsplit('_', 1)[-1]) name = Input(locator=ParametrizedLocator( './/td/input[contains(@id, "fields_name_{@row_id}")]')) data_type = Select(locator=ParametrizedLocator( './/td/select[contains(@id, "fields_datatype_{@row_id}")]')) default_value = Input(locator=ParametrizedLocator( './/td/input[contains(@id, "fields_value_{@row_id}")]')) @classmethod def all(cls, browser): results = [] for e in browser.elements(cls.ALL_FIELDS): results.append((browser.get_attribute('value', e), )) return results def delete(self): self.browser.click( './/img[@alt="Click to delete this input field from method"]', parent=self) try: del self.row_id except AttributeError: pass add_input = Text('//img[@alt="Equal green"]') name = Input(locator='.//td/input[contains(@id, "field_name")]') data_type = Select(locator='.//td/select[contains(@id, "field_datatype")]') default_value = Input(locator='.//td/input[contains(@id, "field_default_value")]') finish_add_input = Text('//img[@alt="Add this entry"]') def read(self): return self.inputs.read() def fill(self, value): keys = set(value.keys()) value = copy(value) present = {key for key, _ in self.inputs.read().items()} to_delete = present - keys changed = False # Create the new ones for key in keys: if key not in present: new_value = value.pop(key) new_value['name'] = key self.add_input.click() super(Inputs, self).fill(new_value) self.finish_add_input.click() changed = True # Fill the rest as expected if self.inputs.fill(value): changed = True # delete unneeded for key in to_delete: self.inputs(name=key).delete() changed = True return changed class MethodCopyView(AutomateExplorerView, CopyViewBase): @property def is_displayed(self): return ( self.in_explorer and self.title.text == 'Copy Automate Method' and self.datastore.is_opened and check_tree_path( self.datastore.tree.currently_selected, self.context['object'].tree_path)) class MethodDetailsView(AutomateExplorerView): title = Text('#explorer_title_text') fqdn = SummaryFormItem( 'Main Info', 'Fully Qualified Name', text_filter=lambda text: [item.strip() for item in text.strip().lstrip('/').split('/')]) name = SummaryFormItem('Main Info', 'Name') display_name = SummaryFormItem('Main Info', 'Display Name') location = SummaryFormItem('Main Info', 'Location') created_on = SummaryFormItem('Main Info', 'Created On', text_filter=parsetime.from_iso_with_utc) inputs = Table(locator='#params_grid', assoc_column='Input Name') @property def is_displayed(self): return ( self.in_explorer and self.title.text.startswith('Automate Method [{}'.format( self.context['object'].display_name or self.context['object'].name)) and self.fqdn.is_displayed and # We need to chop off the leading Domain name. self.fqdn.text == self.context['object'].tree_path_name_only[1:]) class PlaybookBootstrapSelect(BootstrapSelect): """BootstrapSelect widget for Ansible Playbook Method form. BootstrapSelect widgets don't have ``data-id`` attribute in this form, so we have to override ROOT locator. """ ROOT = ParametrizedLocator('.//select[normalize-space(@name)={@id|quote}]/..') class ActionsCell(View): edit = Button(**{"ng-click": "vm.editKeyValue(this.arr[0], this.arr[1], this.arr[2], $index)"}) delete = Button(**{"ng-click": "vm.removeKeyValue($index)"}) class PlaybookInputParameters(View): """Represents input parameters part of playbook method edit form. """ input_name = Input(name="provisioning_key") default_value = Input(name="provisioning_value") provisioning_type = PlaybookBootstrapSelect("provisioning_type") add_button = Button(**{"ng-click": "vm.addKeyValue()"}) variables_table = Table( ".//div[@id='inputs_div']//table", column_widgets={"Actions": ActionsCell()} ) def _values_to_remove(self, values): return list(set(self.all_vars) - set(values)) def _values_to_add(self, values): return list(set(values) - set(self.all_vars)) def fill(self, values): """ Args: values (list): [] to remove all vars or [("var", "value", "type"), ...] to fill the view """ if set(values) == set(self.all_vars): return False else: for value in self._values_to_remove(values): rows = list(self.variables_table) for row in rows: if row[0].text == value[0]: row["Actions"].widget.delete.click() break for value in self._values_to_add(values): self.input_name.fill(value[0]) self.default_value.fill(value[1]) self.provisioning_type.fill(value[2]) self.add_button.click() return True @property def all_vars(self): if self.variables_table.is_displayed: return [(row["Input Name"].text, row["Default value"].text, row["Data Type"].text) for row in self.variables_table] else: return [] def read(self): return self.all_vars class MethodAddView(AutomateExplorerView): title = Text('#explorer_title_text') location = BootstrapSelect('cls_method_location', can_hide_on_select=True) inline_name = Input(name='cls_method_name') inline_display_name = Input(name='cls_method_display_name') script = ScriptBox() data = Input(name='cls_method_data') validate_button = Button('Validate') inputs = View.nested(Inputs) playbook_name = Input(name='name') playbook_display_name = Input(name='display_name') repository = PlaybookBootstrapSelect('provisioning_repository_id') playbook = PlaybookBootstrapSelect('provisioning_playbook_id') machine_credential = PlaybookBootstrapSelect('provisioning_machine_credential_id') hosts = Input('provisioning_inventory') max_ttl = Input('provisioning_execution_ttl') escalate_privilege = BootstrapSwitch('provisioning_become_enabled') verbosity = PlaybookBootstrapSelect('provisioning_verbosity') playbook_input_parameters = PlaybookInputParameters() add_button = Button('Add')
[ " cancel_button = Button('Cancel')" ]
628
lcc
python
null
3149648eac16b892c2a3b92e78536acd7934268336fc2d34
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ac.factory; import elsu.events.*; import ac.core.*; import elsu.database.*; import elsu.support.*; import java.lang.reflect.*; import java.util.*; /** * * @author ss.dhaliwal */ public class ActionFactory extends AbstractEventManager implements IEventPublisher, IEventSubscriber { private ConfigLoader _config = null; private Map<String, Object> _dbManager = new HashMap<>(); public ActionFactory(ConfigLoader config) throws Exception { setConfig(config); setDbManager(); initialize(); notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", ActionFactory(), " + "contructor completed.", null); } public ActionFactory(ConfigLoader config, IEventSubscriber owner) throws Exception { addEventListener(owner); setConfig(config); setDbManager(); initialize(); notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", ActionFactory(), " + "contructor completed.", null); } public ActionFactory(ConfigLoader config, Object dbManager) throws Exception { setConfig(config); setDbManager("default", dbManager); initialize(); notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", ActionFactory(), " + "contructor completed.", null); } public ActionFactory(ConfigLoader config, Object dbManager, IEventSubscriber owner) throws Exception { addEventListener(owner); setConfig(config); setDbManager("default", dbManager); initialize(); notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", ActionFactory(), " + "contructor completed.", null); } private void initialize() throws Exception { /* String syncProvider = getSyncProvider(); boolean installed = false; if ((syncProvider != null) && (!syncProvider.isEmpty())) { java.util.Enumeration e = SyncFactory.getRegisteredProviders(); while (e.hasMoreElements()) { e.nextElement(); if (e.getClass().toString().replaceAll("class ", "").equals(syncProvider)) { installed = true; break; } } if (!installed) { SyncFactory.registerProvider(syncProvider); // log error for tracking getConfig().logInfo(getClass().toString() + ", initialize(), " + "sync provider installed."); } else { // log error for tracking getConfig().logError(getClass().toString() + ", initialize(), " + "sync provider already installed."); } } */ notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", initialize(), " + "initialization completed.", null); } public ConfigLoader getConfig() { return this._config; } private void setConfig() throws Exception { this._config = new ConfigLoader("", null); } private void setConfig(String config) throws Exception { this._config = new ConfigLoader(config, null); } private void setConfig(ConfigLoader config) { this._config = config; } private void setConfig(String config, String[] filterPath) { try { this._config = new ConfigLoader(config, filterPath); } catch (Exception ex) { } } public String getFrameworkProperty(String key) { return getConfig().getProperty("application.framework.attributes.key." + key).toString(); } public String getActionProperty(String key) { return getConfig().getProperty("application.actions.action." + key).toString(); } //public Object getDbManager() { // return getDbManager("default"); //} public Object getDbManager(String key) { Object result = null; // if key is null, then set it to default if (key == null) { key = "default"; } if (this._dbManager.containsKey(key)) { result = this._dbManager.get(key); } return result; } private void setDbManager() throws Exception { if (this._dbManager.size() == 0) { String[] connectionList = getFrameworkProperty("dbmanager.activeList").split(","); String[] propsList; for (String connection : connectionList) { String dbDriver = getFrameworkProperty("dbmanager.connection." + connection + ".driver"); String dbConnectionString = getFrameworkProperty("dbmanager.connection." + connection + ".uri"); int maxPool = 5; try { maxPool = Integer.parseInt( getFrameworkProperty("dbmanager.connection." + connection + ".poolSize")); } catch (Exception ex) { maxPool = 5; } // check if properties are defined HashMap properties = new HashMap<String, String>(); propsList = getFrameworkProperty("dbmanager.connection." + connection + ".params.list").split(","); for (String prop : propsList) { properties.put(prop, getFrameworkProperty("dbmanager.connection." + connection + ".params." + prop)); } // capture any exceptions to prevent resource leaks // create the database manager setDbManager(connection, new DatabaseManager( dbDriver, dbConnectionString, maxPool, properties)); // connect the event notifiers ((DatabaseManager) getDbManager(connection)).addEventListener(this); notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", setDbManager(), " + "dbManager initialized.", null); } } } private void setDbManager(String key, Object dbManager) { if (this._dbManager.containsKey(key)) { this._dbManager.remove(key); } this._dbManager.put(key, dbManager); } public IAction getActionObject(String className) throws Exception { IAction result = null; String classPath = getActionProperty(className); if (classPath != null) { // using reflection, load the class for the service Class<?> actionClass = Class.forName(classPath); // create service constructor discovery type parameter array // populate it with the required class types Class<?>[] argTypes = {ConfigLoader.class, DatabaseManager.class}; // retrieve the matching constructor for the service using // reflection Constructor<?> cons = actionClass.getDeclaredConstructor( argTypes); // retrieve database manager for the class (else try default) String dbName = null; try { dbName = getConfig().getProperty(getConfig().getKeyByValue(classPath).replace(".class", "") + ".connection").toString(); } catch (Exception exi) { } Object dbManager = this.getDbManager(dbName); // create parameter array and populate it with values to // pass to the service constructor Object[] arguments = {getConfig(), dbManager}; // create new instance of the service using the discovered // constructor and parameters result = (IAction) cons.newInstance(arguments); // check if the instance is typeof IEventPublisher // - if yes, then subscribe to its events if (result instanceof IEventPublisher) { ((IEventPublisher) result).addEventListener(this); } notifyListeners(new EventObject(this), EventStatusType.INFORMATION, getClass().toString() + ", getClassByName(), " + "class (" + className + "/" + classPath + ") instantiated.", null); } else {
[ " notifyListeners(new EventObject(this), EventStatusType.ERROR," ]
740
lcc
java
null
79cd419a6f2198575f4b878105dcc71a5fbd4737594a98a5