Converts an OpenEngSBForeignKey annotation to the fitting format which will be added to an EDBObject.
485188
public static String getEOReferenceStringFromAnnotation(OpenEngSBForeignKey key) {
        return String.format("%s%s:%s", REFERENCE_PREFIX, key.modelType(), key.modelVersion().toString());
    }
1228459
@Override
    public final String format(String key, ClassAnnotation primaryClass) {
        if ("class.givenClass".equals(key)) {
            return shorten(primaryClass.getPackageName(), className);
        }
        if ("simpleClass".equals(key)) {
            return ClassName.extractSimpleName(className);
        }
        if ("class".equals(key)) {
            return className;
        }
        if ("package".equals(key)) {
            return getPackageName();
        }
        if ("".equals(key) && FindBugsDisplayFeatures.isAbridgedMessages() && primaryClass != null) {
            return formatPackageMember("givenClass", primaryClass);
        }
        return formatPackageMember(key, primaryClass);
    }
1030873
private ModelDescription getDescriptionFromObject(EDBObject obj) {
        String modelName = obj.getString(EDBConstants.MODEL_TYPE);
        String modelVersion = obj.getString(EDBConstants.MODEL_TYPE_VERSION);
        if (modelName == null || modelVersion == null) {
            throw new IllegalArgumentException("The object " + obj.getOID() + " contains no model information");
        }
        return new ModelDescription(modelName, modelVersion);
    }
524773
def convert(cls, style_dict, num_format_str=None):
        

        # Create a XlsxWriter format object.
        props = {}

        if num_format_str is not None:
            props['num_format'] = num_format_str

        if style_dict is None:
            return props

        if 'borders' in style_dict:
            style_dict = style_dict.copy()
            style_dict['border'] = style_dict.pop('borders')

        for style_group_key, style_group in style_dict.items():
            for src, dst in cls.STYLE_MAPPING.get(style_group_key, []):
                # src is a sequence of keys into a nested dict
                # dst is a flat key
                if dst in props:
                    continue
                v = style_group
                for k in src:
                    try:
                        v = v[k]
                    except (KeyError, TypeError):
                        break
                else:
                    props[dst] = v

        if isinstance(props.get('pattern'), str):
            # TODO: support other fill patterns
            props['pattern'] = 0 if props['pattern'] == 'none' else 1

        for k in ['border', 'top', 'right', 'bottom', 'left']:
            if isinstance(props.get(k), str):
                try:
                    props[k] = ['none', 'thin', 'medium', 'dashed', 'dotted',
                                'thick', 'double', 'hair', 'mediumDashed',
                                'dashDot', 'mediumDashDot', 'dashDotDot',
                                'mediumDashDotDot',
                                'slantDashDot'].index(props[k])
                except ValueError:
                    props[k] = 2

        if isinstance(props.get('font_script'), str):
            props['font_script'] = ['baseline', 'superscript',
                                    'subscript'].index(props['font_script'])

        if isinstance(props.get('underline'), str):
            props['underline'] = {'none': 0, 'single': 1, 'double': 2,
                                  'singleAccounting': 33,
                                  'doubleAccounting': 34}[props['underline']]

        return props
1218651
private static void addSetOpenEngSBModelTail(CtClass clazz) throws CannotCompileException, NotFoundException {
        CtClass[] params = generateClassField(List.class);
        CtMethod method = new CtMethod(CtClass.voidType, "setOpenEngSBModelTail", params, clazz);
        StringBuilder builder = new StringBuilder();
        builder.append(createTrace("Called setOpenEngSBModelTail"))
            .append("if($1 != null) {for(int i = 0; i < $1.size(); i++) {")
            .append("OpenEngSBModelEntry entry = (OpenEngSBModelEntry) $1.get(i);")
            .append(String.format("%s.put(entry.getKey(), entry); } }", TAIL_FIELD));
        method.setBody(createMethodBody(builder.toString()));
        clazz.addMethod(method);
    }
362105
public static Map<String, Object> convert(Object pojo,
                                              Class<? extends Annotation> annotationType) {
        return convert(pojo, annotationType, true);
    }
839801
def encode_osgi_props(ed):
    # type: (EndpointDescription) -> Dict[str, str]
    
    result_props = {}
    intfs = ed.get_interfaces()
    result_props[OBJECTCLASS] = " ".join(intfs)
    for intf in intfs:
        pkg_name = package_name(intf)
        ver = ed.get_package_version(pkg_name)
        if ver and not ver == (0, 0, 0):
            result_props[ENDPOINT_PACKAGE_VERSION_] = ".".join(
                str(v) for v in ver
            )

    result_props[ENDPOINT_ID] = ed.get_id()
    result_props[ENDPOINT_SERVICE_ID] = "{0}".format(ed.get_service_id())
    result_props[ENDPOINT_FRAMEWORK_UUID] = ed.get_framework_uuid()
    imp_configs = ed.get_imported_configs()
    if imp_configs:
        result_props[SERVICE_IMPORTED_CONFIGS] = " ".join(
            ed.get_imported_configs()
        )
    intents = ed.get_intents()
    if intents:
        result_props[SERVICE_INTENTS] = " ".join(intents)
    remote_configs = ed.get_remote_configs_supported()
    if remote_configs:
        result_props[REMOTE_CONFIGS_SUPPORTED] = " ".join(remote_configs)
    remote_intents = ed.get_remote_intents_supported()
    if remote_intents:
        result_props[REMOTE_INTENTS_SUPPORTED] = " ".join(remote_intents)
    return result_props
433124
public static final void convertAnnotations(Tree config, Annotation[] annotations)
			throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		for (Annotation annotation : annotations) {

			// Create entry for annotation
			String annotationName = annotation.toString();
			int i = annotationName.lastIndexOf('.');
			if (i > -1) {
				annotationName = annotationName.substring(i + 1);
			}
			i = annotationName.indexOf('(');
			if (i > -1) {
				annotationName = annotationName.substring(0, i);
			}
			if (annotationName.length() > 1) {
				annotationName = Character.toLowerCase(annotationName.charAt(0)) + annotationName.substring(1);
			} else {
				annotationName = annotationName.toLowerCase();
			}
			if ("name".equals(annotationName) || "override".equals(annotationName)) {
				continue;
			}
			Tree annotationMap = config.putMap(annotationName);

			// Add annotation values
			Class<? extends Annotation> type = annotation.annotationType();
			Method[] members = type.getDeclaredMethods();
			for (Method member : members) {
				member.setAccessible(true);
				String propName = member.getName();
				Object propValue = member.invoke(annotation);
				annotationMap.putObject(propName, propValue);
				Tree newChild = annotationMap.get(propName);
				if (newChild.size() < 1) {
					newChild.remove();
				}
			}
			int size = annotationMap.size();
			if (size == 0) {
				annotationMap.remove();
			} else if (size == 1) {
				Tree value = annotationMap.getFirstChild();
				if (value != null && "value".equals(value.getName())) {
					annotationMap.setObject(value.asObject());
				}
			}
		}
	}
730763
def bencode(obj):
    """"""
    if isinstance(obj, int):
        return "i" + str(obj) + "e"

    if isinstance(obj, str):
        if not obj:
            return None
        return str(len(obj)) + ":" + obj

    if isinstance(obj, list):
        res = "l"
        for elem in obj:
            elem = bencode(elem)
            if elem:
                res += elem
        return res + "e"

    if isinstance(obj, dict):
        res = "d"
        for key in sorted(obj.keys()):
            if key in obj:
                value = bencode(obj[key])
                key = bencode(key)
                if key and value:
                    res += key + value

        return res + "e"

    if isinstance(obj, unicode):
        return bencode(obj.encode('utf-8'))

    if isinstance(obj, collections.OrderedDict):
        return bencode(dict(obj))
    raise Exception("Unknown object: %s (%s)" % (repr(obj), repr(type(obj))))
528161
function encodeGetMarketProfitAndLoss(doc, result) {
    // annotations
    if (!result.annotations) {
        // bets
        doc.startElement('annotations').writeAttribute('xsi:null', '1');
        doc.endElement();
    } else {
        doc.startElement('annotations').writeAttribute('xsi:type',
                'n2:ArrayOfProfitAndLoss');
        for ( var i = 0; i < result.annotations.length; ++i) {
            var ann = result.annotations[i];
            doc.startElement('n2:ProfitAndLoss').writeAttribute('xsi:type',
                    'n2:ProfitAndLoss');
            // futureIfWin
            doc.startElement('futureIfWin').writeAttribute('xsi:type', 'xsd:double');
            doc.text(ann.futureIfWin + '');
            doc.endElement();
            // ifWin
            doc.startElement('ifWin').writeAttribute('xsi:type', 'xsd:double');
            doc.text((1 * ann.ifWin).toFixed(2));
            doc.endElement();
            // selectionID
            doc.startElement('selectionId').writeAttribute('xsi:type', 'xsd:integer');
            doc.text(ann.selectionId);
            doc.endElement();
            // selectionName
            doc.startElement('selectionName').writeAttribute('xsi:type', 'xsd:string');
            doc.text(ann.selectionName);
            doc.endElement();
            // worstCaseIfWin
            doc.startElement('worstCaseIfWin').writeAttribute('xsi:type', 'xsd:double');
            doc.text(ann.worstCaseIfWin + '');
            doc.endElement();
            // ifLoss
            doc.startElement('ifLoss').writeAttribute('xsi:type', 'xsd:double');
            doc.text((1 * ann.ifLoss).toFixed(2));
            doc.endElement();

            doc.endElement();
        }
        doc.endElement();
    }
    // commissionApplied
    doc.startElement('commissionApplied').writeAttribute('xsi:type', 'xsd:double');
    doc.text(result.commissionApplied + '');
    doc.endElement();
    // currencyCode
    doc.startElement('currencyCode').writeAttribute('xsi:type', 'xsd:string');
    doc.text(result.currencyCode);
    doc.endElement();
    // includesSettledBets
    doc.startElement('includesSettledBets').writeAttribute('xsi:type', 'xsd:booleang');
    doc.text(result.includesSettledBets ? "true" : "false");
    doc.endElement();
    // includesBspBets
    doc.startElement('includesBspBets').writeAttribute('xsi:type', 'xsd:booleang');
    doc.text(result.includesBspBets ? "true" : "false");
    doc.endElement();
    // marketId
    doc.startElement('marketId').writeAttribute('xsi:type', 'xsd:integer');
    doc.text(result.marketId);
    doc.endElement();
    // marketName
    doc.startElement('marketName').writeAttribute('xsi:type', 'xsd:string');
    doc.text(result.marketName);
    doc.endElement();
    // marketStatus
    doc.startElement('marketStatus').writeAttribute('xsi:type', 'n2:MarketStatusEnum');
    doc.text(result.marketStatus);
    doc.endElement();
    // unit
    doc.startElement('unit').writeAttribute('xsi:type', 'xsd:string');
    doc.text(result.unit || 'N/A');
    doc.endElement();
}
1243419
def to_bson(buffer = ByteBuffer.new, validating_keys = Config.validating_keys?)
      to_time.to_bson(buffer)
    end
1056487
def apply_annotation(self, bo, annotation):
        

        # Currently we only support RegionAnnotation

        if not isinstance(annotation, RegionAnnotation):
            return bo

        if not isinstance(bo, ValueSet):
            # Convert it to a ValueSet first
            # Note that the original value is not kept at all. If you want to convert a StridedInterval to a ValueSet,
            # you gotta do the conversion by calling AST.annotate() from outside.
            bo = ValueSet.empty(bo.bits)

        return bo.apply_annotation(annotation)
731470
def from_es(self, hit):
        """"""
        doc = hit.copy()
        klass = shallow_class_factory(self.model)

        # We can pass in the entire source, except when we have a non-indexable many-to-many
        for field in self.model._meta.get_fields():

            if not field.auto_created and field.many_to_many:
                if not issubclass(field.rel.to, Indexable):
                    if field.name in doc["_source"]:
                        del doc["_source"][field.name]

            # if field.one_to_many:
            #     if field.name in doc["_source"]:
            #         del doc["_source"][field.name]

        # Now let's go ahead and parse all the fields
        fields = self.mapping.properties.properties
        for key in fields:
            # TODO: What if we've mapped the property to a different name? Will we allow that?
            field = fields[key]

            # if isinstance(field, InnerObject):
            #     import pdb; pdb.set_trace()
            #     continue

            if doc["_source"].get(key):
                attribute_value = doc["_source"][key]

                doc["_source"][key] = field.to_python(attribute_value)

        return klass(**doc["_source"])
1330615
public void toStringRep(String indent, Map<String, String> nss, 
            XNAppender out, Consumer<? super XRepresentationRecord> callback) {
        
        Map<String, String> nss0 = new HashMap<>(nss);
        
        out.append(indent);
        
        if (callback != null) {
            callback.accept(new XRepresentationRecord(XRepresentationState.START_ELEMENT, this, 
                    out.length()));
        }
        out.append("<");
        
        Pair<String, String> pf = createPrefix(nss0, namespace, prefix);
        
        String prefix = pf.first;
        if (prefix != null && prefix.length() > 0) {
            out.append(prefix).append(":");
        }
        out.append(name);

        if (pf.second != null) {
            out.append(pf.second);
        }
        
        if (attributes.size() > 0) {
            for (XAttributeName an : attributes.keySet()) {
                Pair<String, String> pfa = createPrefix(nss0, an.namespace, an.prefix);
                out.append(" ");
                if (pfa.first != null && pfa.first.length() > 0) {
                    out.append(pfa.first).append(":");
                }
                out.append(an.name).append("='").append(sanitize(attributes.get(an))).append("'");
                
                if (pfa.second != null) {
                    out.append(pfa.second);
                }
                
            }
        }
        
        if (children.size() == 0) {
            if (content == null || content.isEmpty()) {
                out.append("/>");
            } else {
                out.append(">");
                if (callback != null) {
                    callback.accept(new XRepresentationRecord(XRepresentationState.START_TEXT, this, out.length()));
                }
                String s = sanitize(content);
                out.append(s);
                if (callback != null) {
                    callback.accept(new XRepresentationRecord(XRepresentationState.END_TEXT, this, out.length()));
                }
                if (s.endsWith("\n")) {
                    out.append(indent);
                }
                out.append("</");
                if (prefix != null && prefix.length() > 0) {
                    out.append(prefix).append(":");
                }
                out.append(name);
                out.append(">");
            }
        } else {
            if (content == null || content.isEmpty()) {
                out.append(String.format(">%n"));
            } else {
                out.append(">");
                if (callback != null) {
                    callback.accept(new XRepresentationRecord(XRepresentationState.START_TEXT, this, out.length()));
                }
                out.append(sanitize(content));
                if (callback != null) {
                    callback.accept(new XRepresentationRecord(XRepresentationState.END_TEXT, this, out.length()));
                }

                out.append(String.format("%n"));
            }
            for (XNElement e : children) {
                e.toStringRep(indent + "  ", nss0, out, callback);
            }
            out.append(indent).append("</");
            if (prefix != null && prefix.length() > 0) {
                out.append(prefix).append(":");
            }
            out.append(name);
            out.append(">");
        }
        if (callback != null) {
            callback.accept(new XRepresentationRecord(XRepresentationState.END_ELEMENT, this, out.length()));
        }
        out.append(String.format("%n"));
    }
430955
def _message_to_entity(msg, modelclass):
  
  ent = modelclass()
  for prop_name, prop in modelclass._properties.iteritems():
    if prop._code_name == 'blob_':  # TODO: Devise a cleaner test.
      continue  # That's taken care of later.
    value = getattr(msg, prop_name)
    if value is not None and isinstance(prop, model.StructuredProperty):
      if prop._repeated:
        value = [_message_to_entity(v, prop._modelclass) for v in value]
      else:
        value = _message_to_entity(value, prop._modelclass)
    setattr(ent, prop_name, value)
  return ent
1133243
def get_annotation(self, key, result_format='list'):
        
        value = self.get('_annotations_by_key', {}).get(key)
        if not value:
            return value

        if result_format == 'one':
            return value[0]

        return value
449693
private String makeConverterKey(Class<?> fromClass, String syntax, Class<?> toClass) {
        StringBuilder key = new StringBuilder();
        if (syntax==null) {
            syntax="";
        }
        key.append(fromClass.getName()).append(KEY_SEP).append(syntax).append(KEY_SEP).append(toClass.getName());
        return key.toString();
    }