text:
var crypto = require('crypto');
var moment = require('moment');
var request = require('request');
var util = require('util');
var xml2js = require('xml2js');
var _ = require('underscore');

var assert = require('./assert');
var multivalue = require('./multivalue');

var BASE_NAMESPACES = {
  'xml': 'http://www.w3.org/XML/1998/namespace'
};

// We convert XML Schema names to namespaced ones below

var BASE_TYPES = {};

BASE_TYPES.string = BASE_TYPES.normalizedString = BASE_TYPES.token = BASE_TYPES.language = BASE_TYPES.NMTOKEN = BASE_TYPES.Name = BASE_TYPES.NCName = BASE_TYPES.ID = BASE_TYPES.IDREF = BASE_TYPES.ENTITY = {
  parse: function (value) {
    return value;
  }
};

BASE_TYPES.NMTOKENS = BASE_TYPES.IDREFS = BASE_TYPES.ENTITIES = {
  parse: function (value) {
    return value.split(/\s+/);
  }
};

BASE_TYPES.boolean = {
  parse: function (value) {
    return _.contains(['true', '1'], value.toLowerCase());
  }
};

BASE_TYPES.integer = BASE_TYPES.nonPositiveInteger = BASE_TYPES.negativeInteger = BASE_TYPES.long = BASE_TYPES.int = BASE_TYPES.short = BASE_TYPES.byte = BASE_TYPES.nonNegativeInteger = BASE_TYPES.unsignedLong = BASE_TYPES.unsignedInt = BASE_TYPES.unsignedShort = BASE_TYPES.unsignedByte = BASE_TYPES.positiveInteger = {
  parse: function (value) {
    return parseInt(value);
  }
};

BASE_TYPES.decimal = {
  parse: function (value) {
    return parseFloat(value);
  }
};

BASE_TYPES.double = BASE_TYPES.float = {
  parse: function (value) {
    if (value.toLowerCase() === 'inf') {
      value = 'Infinity';
    }
    else if (value.toLowerCase() === '-inf') {
      value = '-Infinity';
    }
    return parseFloat(value);
  }
};

BASE_TYPES.dateTime = BASE_TYPES.date = {
  parse: function (value) {
    return moment.utc(value).toDate();
  }
};

BASE_TYPES.hexBinary = {
  parse: function (value) {
    return new Buffer(value, 'hex');
  }
};

BASE_TYPES.base64Binary = {
  parse: function (value) {
    return new Buffer(value, 'base64');
  }
};

BASE_TYPES.anyURI = {
  parse: function (value) {
    return value;
  }
};

// duration, time, gYearMonth, gYear, gMonthDay, gDay, gMonth, QName, NOTATION not implemented, for now leave them as a string
// TODO: What would be the best JavaScript object to convert them to?
BASE_TYPES.duration = BASE_TYPES.time = BASE_TYPES.gYearMonth = BASE_TYPES.gYear = BASE_TYPES.gMonthDay = BASE_TYPES.gDay = BASE_TYPES.gMonth = BASE_TYPES.QName = BASE_TYPES.NOTATION = {
  parse: function (value) {
    return value;
  }
};

// We convert XML Schema names to namespaced ones
for (var baseTypeName in BASE_TYPES) {
  if (!BASE_TYPES.hasOwnProperty(baseTypeName)) {
    continue;
  }

  BASE_TYPES['{http://www.w3.org/2001/XMLSchema}' + baseTypeName] = BASE_TYPES[baseTypeName];
  delete BASE_TYPES[baseTypeName];
}

function randomString() {
  return crypto.pseudoRandomBytes(10).toString('hex');
}

function XsdSchema(parser, targetNamespace, defaultNamespace, namespaces, xsPrefix) {
  var self = this;
  self.parser = parser;
  self.targetNamespace = targetNamespace;
  self.defaultNamespace = defaultNamespace;
  self.namespaces = _.extend({}, namespaces, BASE_NAMESPACES);
  self.xsPrefix = xsPrefix;
}

// Similar to ValidatorMixin.namespacedName, just using self
XsdSchema.prototype.namespacedName = function (name) {
  var self = this;

  assert(name);
  if (/^\{.+\}/.test(name)) {
    return name;
  }

  if (/:/.test(name)) {
    var parts = name.split(':');
    assert(parts.length === 2, parts);
    assert(self.namespaces[parts[0]], name);
    return '{' + self.namespaces[parts[0]] + '}' + parts[1];
  }
  else if (self.defaultNamespace) {
    return '{' + self.defaultNamespace + '}' + name;
  }
  else {
    assert(false, name);
  }
};

XsdSchema.prototype.namespacedTargetName = function (name) {
  var self = this;

  assert(name);
  var match = /^\{(.+)\}/.exec(name);
  if (match) {
    assert(match[1] === self.targetNamespace, name);
    return name;
  }

  if (/:/.test(name)) {
    var parts = name.split(':');
    assert(parts.length === 2, parts);
    assert(self.namespaces[parts[0]] === self.targetNamespace, name);
    return '{' + self.targetNamespace + '}' + parts[1];
  }
  else {
    return '{' + self.targetNamespace + '}' + name;
  }
};

XsdSchema.prototype.parseIsArray = function (input, isArrayDefault) {
  var self = this;

  var isArray = _.isBoolean(isArrayDefault) ? isArrayDefault : null;
  if (input.$) {
    if (input.$.maxOccurs) {
      isArray = input.$.maxOccurs === 'unbounded' || parseInt(input.$.maxOccurs) > 1;
    }
    delete input.$.minOccurs;
    delete input.$.maxOccurs;
  }
  return isArray;
};

XsdSchema.prototype.parseTypesChoice = function (input, isArrayDefault) {
  var self = this;

  var children = {};
  if (input[self.xsPrefix + 'choice']) {
    assert(input[self.xsPrefix + 'choice'].length === 1, input[self.xsPrefix + 'choice']);
    var choice = input[self.xsPrefix + 'choice'][0];
    isArrayDefault = self.parseIsArray(choice, isArrayDefault);
    delete choice.$;
    _.extend(children, self.parseElements(choice, isArrayDefault));
    assert(_.isEmpty(choice), choice);
  }
  delete input[self.xsPrefix + 'choice'];
  return children;
};

XsdSchema.prototype.parseTypesSequence = function (input) {
  var self = this;

  var type = {};
  if (input[self.xsPrefix + 'sequence']) {
    assert(input[self.xsPrefix + 'sequence'].length === 1, input[self.xsPrefix + 'sequence']);
    var sequence = input[self.xsPrefix + 'sequence'][0];
    var children = {};
    var isArrayDefault = self.parseIsArray(sequence);
    delete sequence.$;
    _.extend(children, self.parseElements(sequence, isArrayDefault));
    _.extend(children, self.parseTypesChoice(sequence, isArrayDefault));
    if (sequence[self.xsPrefix + 'any']) {
      assert(sequence[self.xsPrefix + 'any'].length === 1, sequence[self.xsPrefix + 'any']);
      type.anyChildren = true;
      var isArray = self.parseIsArray(sequence[self.xsPrefix + 'any'][0], isArrayDefault);
      if (_.isBoolean(isArray)) {
        type.isArray = isArray;
      }
    }
    delete sequence[self.xsPrefix + 'any'];
    assert(_.isEmpty(sequence), sequence);
    type.children = children;
  }
  delete input[self.xsPrefix + 'sequence'];
  return type;
};

XsdSchema.prototype.parseSimpleType = function (input) {
  var self = this;

  var newTypes = {};
  _.each(input[self.xsPrefix + 'simpleType'] || [], function (simpleType) {
    var type = {};
    if (simpleType[self.xsPrefix + 'restriction']) {
      assert(simpleType[self.xsPrefix + 'restriction'].length === 1, simpleType[self.xsPrefix + 'restriction']);
      var restriction = simpleType[self.xsPrefix + 'restriction'][0];
      if (restriction.$.base !== 'anySimpleType') {
        type.base = self.namespacedName(restriction.$.base);
      }
      delete restriction.$;
      // We ignore the rest of the restriction because we do not care about restrictions on values, only elements and attributes
    }
    delete simpleType[self.xsPrefix + 'restriction'];
    if (simpleType[self.xsPrefix + 'union']) {
      assert(simpleType[self.xsPrefix + 'union'].length === 1, simpleType[self.xsPrefix + 'union']);
      var union = simpleType[self.xsPrefix + 'union'][0];
      type.base = _.map(union.$.memberTypes.split(/\s+/), function (base) {
        return self.namespacedName(base);
      });
      delete union.$.memberTypes;
      assert(_.isEmpty(union.$), union.$);
      delete union.$;
      assert(_.isEmpty(union), union);
    }
    delete simpleType[self.xsPrefix + 'union'];
    // TODO: Support other simple types
    assert(simpleType.$.name, simpleType.$);
    var typeName = self.namespacedTargetName(simpleType.$.name);
    delete simpleType.$.name;
    assert(_.isEmpty(simpleType.$), simpleType.$);
    newTypes[typeName] = type;
  });
  delete input[self.xsPrefix + 'simpleType'];
  return newTypes;
};

XsdSchema.prototype.parseTypes = function (input) {
  var self = this;

  var newTypes = {};
  _.each(input[self.xsPrefix + 'complexType'] || [], function (complexType) {
    var type = {};
    _.extend(type, self.parseTypesSequence(complexType));
    if (complexType[self.xsPrefix + 'choice']) {
      type.children = self.parseTypesChoice(complexType);
    }
    assert(!(complexType[self.xsPrefix + 'simpleContent'] && complexType[self.xsPrefix + 'complexContent']), complexType);
    _.each(['simpleContent', 'complexContent'], function (anyContent) {
      if (complexType[self.xsPrefix + anyContent]) {
        assert(complexType[self.xsPrefix + anyContent].length === 1, complexType[self.xsPrefix + anyContent]);
        var content = complexType[self.xsPrefix + anyContent][0];
        _.each(['restriction', 'extension'], function (anyDerivation) {
          if (content[self.xsPrefix + anyDerivation]) {
            assert(content[self.xsPrefix + anyDerivation].length === 1, content[self.xsPrefix + anyDerivation]);
            var derivation = content[self.xsPrefix + anyDerivation][0];
            if (derivation.$.base !== 'anyType') {
              type.base = self.namespacedName(derivation.$.base);
              if (anyDerivation === 'restriction') {
                type.restriction = true;
              }
            }
            delete derivation.$.base;
            assert(_.isEmpty(derivation.$), derivation.$);
            delete derivation.$;
            if (derivation[self.xsPrefix + 'attribute']) {
              type.attributes = self.parseAttributes(derivation);
            }
            if (derivation[self.xsPrefix + 'sequence']) {
              _.extend(type, self.parseTypesSequence(derivation));
            }
            assert(_.isEmpty(derivation), derivation);
            delete content[self.xsPrefix + anyDerivation];
          }
        });
        assert(_.isEmpty(content), content);
      }
      delete complexType[self.xsPrefix + anyContent];
    });
    if (complexType[self.xsPrefix + 'attribute']) {
      type.attributes = self.parseAttributes(complexType);
    }

    assert(complexType.$.name, complexType.$);
    var typeName = self.namespacedTargetName(complexType.$.name);
    delete complexType.$.name;
    if (complexType.$.mixed && BASE_TYPES['{http://www.w3.org/2001/XMLSchema}boolean'].parse(complexType.$.mixed)) {
      // Can be mixed content, both text and elements
      type.mixed = true;
    }
    delete complexType.$.mixed;
    assert(_.isEmpty(complexType.$), complexType.$);
    delete complexType.$;
    newTypes[typeName] = type;

    // We ignore annotations
    delete complexType[self.xsPrefix + 'annotation'];
  });
  delete input[self.xsPrefix + 'complexType'];

  _.extend(newTypes, self.parseSimpleType(input));

  // We ignore annotations and top-level attributes
  delete input[self.xsPrefix + 'annotation'];
  delete input.$;

  return newTypes;
};

XsdSchema.prototype.parseElements = function (input, isArrayDefault) {
  var self = this;

  var newElements = {};
  _.each(input[self.xsPrefix + 'element'] || [], function (element) {
    if (element.$.ref) {
      var elementReference = self.namespacedName(element.$.ref);
      newElements[elementReference] = {
        ref: elementReference
      };
      if (_.isBoolean(isArrayDefault)) {
        newElements[elementReference].isArrayDefault = isArrayDefault;
      }
    }
    else {
      assert(element.$.name, element.$);
      var elementName = self.namespacedTargetName(element.$.name);
      var isArray = self.parseIsArray(element, isArrayDefault);
      if (element.$.type) {
        newElements[elementName] = {
          type: self.namespacedName(element.$.type)
        };
      }
      else {
        assert(element[self.xsPrefix + 'complexType'] || element[self.xsPrefix + 'simpleType'], element);
        assert(!(element[self.xsPrefix + 'complexType'] && element[self.xsPrefix + 'simpleType']), element);

        // Type is nested inside the element, so we create out own name for it
        var typeName = elementName + '-type-' + randomString();

        // Then we pretend that it is defined with out own name
        _.each(element[self.xsPrefix + 'complexType'] || [], function (complexType) {
          if (!complexType.$) complexType.$ = {};
          complexType.$.name = typeName;
        });
        _.each(element[self.xsPrefix + 'simpleType'] || [], function (simpleType) {
          if (!simpleType.$) simpleType.$ = {};
          simpleType.$.name = typeName;
        });

        // Parse it and store it
        var newTypes = self.parseTypes(element);
        _.extend(self.parser.types, newTypes);

        newElements[elementName] = {
          type: typeName
        };
      }
      if (_.isBoolean(isArray)) {
        newElements[elementName].isArray = isArray;
      }
      delete element.$;
      // We ignore annotations
      delete element[self.xsPrefix + 'annotation'];
    }
  });
  delete input[self.xsPrefix + 'element'];
  return newElements;
};

XsdSchema.prototype.parseAttributes = function (input) {
  var self = this;

  var newAttributes = {};
  _.each(input[self.xsPrefix + 'attribute'] || [], function (attribute) {
    if (attribute.$.ref) {
      var attributeReference = self.namespacedName(attribute.$.ref);
      newAttributes[attributeReference] = {
        ref: attributeReference
      };
    }
    else {
      assert(attribute.$.name, attribute.$);
      var attributeName = self.namespacedTargetName(attribute.$.name);
      if (attribute.$.type) {
        newAttributes[attributeName] = self.namespacedName(attribute.$.type);
      }
      else if (attribute[self.xsPrefix + 'simpleType']) {
        // Type is nested inside the attribute, so we create out own name for it
        var typeName = attributeName + '-type-' + randomString();

        _.each(attribute[self.xsPrefix + 'simpleType'] || [], function (simpleType) {
          if (!simpleType.$) simpleType.$ = {};
          simpleType.$.name = typeName;
        });

        // Parse it and store it
        var newTypes = self.parseSimpleType(attribute);
        _.extend(self.parser.types, newTypes);

        newAttributes[attributeName] = typeName;
      }
      else {
        // Only simple types are allowed for attributes
        assert(false, attribute);
      }
      delete attribute.$;
      // We ignore annotations
      delete attribute[self.xsPrefix + 'annotation'];
    }
  });
  delete input[self.xsPrefix + 'attribute'];
  return newAttributes;
};

XsdSchema.prototype.parseImportsAndIncludes = function (currentNamespace, schema) {
  var self = this;

  var imports = {};
  _.each(schema[self.xsPrefix + 'import'] || [], function (schemaImport) {
    multivalue.addValue(imports, schemaImport.$.namespace, schemaImport.$.schemaLocation);
  });
  delete schema[self.xsPrefix + 'import'];
  _.each(schema[self.xsPrefix + 'include'] || [], function (schemaInclude) {
    multivalue.addValue(imports, currentNamespace, schemaInclude.$.schemaLocation);
  });
  delete schema[self.xsPrefix + 'include'];
  return imports;
};

// We pretend that everything is a 2001 XML Schema, hopefully we are compatibile enough
function upgradeXmlSchemaVersion(namespace) {
  if (namespace === 'http://www.w3.org/1999/XMLSchema' || namespace === 'http://www.w3.org/2000/10/XMLSchema') {
    return 'http://www.w3.org/2001/XMLSchema';
  }
  else {
    return namespace;
  }
}

function parseNamespacePrefixes(input, cb) {
  var defaultNamespace = '';
  var namespaces = {};
  var xsPrefix = '';

  for (var element in input) {
    if (!input.hasOwnProperty(element)) {
      continue;
    }

    var schema = input[element];
    if (!schema.$) {
      continue;
    }

    for (var attr in schema.$) {
      if (!schema.$.hasOwnProperty(attr)) {
        continue;
      }

      var value = upgradeXmlSchemaVersion(schema.$[attr]);
      if (attr === 'xmlns') {
        assert(defaultNamespace === '', defaultNamespace);
        defaultNamespace = value;
      }
      else if (attr.slice(0, 6) === 'xmlns:') {
        var prefix = attr.slice(6);
        if (!prefix) {
          cb("Invalid namespace declaration: " + attr + ", for schema: " + util.inspect(schema, false, null));
          return;
        }

        if (value === 'http://www.w3.org/2001/XMLSchema') {
          assert(xsPrefix === '', xsPrefix);
          // We add : and call it "prefix" so that we can use it by simple string concatenation
          xsPrefix = prefix + ':';
        }

        namespaces[prefix] = value;
      }
    }
  }

  cb(null, defaultNamespace, namespaces, xsPrefix);
}

function traverseFindSchemas(obj) {
  var foundSchemas = {};
  _.each(obj, function (o, tag) {
    if (tag !== '$') {
      if (_.isObject(o)) {
        _.extend(foundSchemas, traverseFindSchemas(o));
      }
    }
    else {
      // TODO: xsi prefix should probably not be hard-coded
      if (o['xsi:schemaLocation']) {
        var schemaLocation = o['xsi:schemaLocation'].split(/\s+/);
        assert(schemaLocation.length === 2, schemaLocation);
        multivalue.addValue(foundSchemas, schemaLocation[0], schemaLocation[1]);
      }
    }
  });
  return foundSchemas;
}

var XsdMixin = {
  // Returns imports (and includes) object in a callback. You have assure that
  // all those schemas are added as well for all necessary types to be satisfied.
  addSchema: function (namespace, schemaContent, cb) {
    var self = this;

    if (multivalue.hasValue(self.parsedSchemas, namespace, schemaContent)) {
      cb(null, {});
      return;
    }

    xml2js.parseString(schemaContent, function (err, result) {
      if (err) {
        cb(err);
        return;
      }

      // Only one root element expected
      if (!result || _.size(result) !== 1) {
        cb("Invalid schema for " + namespace + ": " + util.inspect(result, false, null));
        return;
      }

      parseNamespacePrefixes(result, function (err, defaultNamespace, namespaces, xsPrefix) {
        if (err) {
          cb(err);
          return;
        }

        assert(result[xsPrefix + 'schema'], result);

        var schema = result[xsPrefix + 'schema'];

        if (schema.$ && schema.$.targetNamespace && schema.$.targetNamespace !== namespace) {
          cb("Schema does not have expected target namespace " + namespace + ": " + util.inspect(result, false, null));
          return;
        }

        var schemaParser = new XsdSchema(self, namespace, defaultNamespace, namespaces, xsPrefix);

        var importsAndIncludes = schemaParser.parseImportsAndIncludes(namespace, schema);

        var newElements = schemaParser.parseElements(schema, null);
        // TODO: Check if we are overriding anything
        _.extend(self.elements, newElements);

        var newAttributes = schemaParser.parseAttributes(schema);
        // TODO: Check if we are overriding anything
        _.extend(self.attributes, newAttributes);

        var newTypes = schemaParser.parseTypes(schema);
        // TODO: Check if we are overriding anything
        _.extend(self.types, newTypes);

        // TODO: Add support for element and attribute groups
        delete schema[xsPrefix + 'group'];
        delete schema[xsPrefix + 'attributeGroup'];

        // Previous parsing calls are destructive and should consume schema so that it is empty now
        assert(_.isEmpty(schema), schema);

        multivalue.addValue(self.parsedSchemas, namespace, schemaContent);

        cb(null, importsAndIncludes);
      });
    });
  },

  // Returns imports (and includes) object in a callback. You have assure that
  // all those schemas are added as well for all necessary types to be satisfied.
  downloadAndAddSchema: function (namespace, schemaUrl, cb) {
    var self = this;

    if (multivalue.hasValue(self.downloadedSchemas, namespace, schemaUrl)) {
      cb(null, {});
      return;
    }

    request(schemaUrl, function (err, response, body) {
      if (err) {
        cb("Error downloading " + namespace + " schema (" + schemaUrl + "): " + err);
        return;
      }
      else if (response.statusCode !== 200) {
        cb("Error downloading " + namespace + " schema (" + schemaUrl + "): HTTP status code " + response.statusCode);
        return;
      }

      self.addSchema(namespace, body, function (err, importsAndIncludes) {
        if (err) {
          cb(err);
          return;
        }

        multivalue.addValue(self.downloadedSchemas, namespace, schemaUrl);

        cb(null, importsAndIncludes);
      });
    });
  },

  // Does not search recursively inside schemas for imported other
  // schemas, so there might still be types missing when parsing,
  // even if you satisfy all found schemas. You have to inspect
  // pending imports returned in a callback of addSchema (or
  // downloadAndAddSchema) and satisfy those schemas as well.
  findSchemas: function (str, cb) {
    var self = this;

    xml2js.parseString(str, function (err, result) {
      if (err) {
        cb(err);
        return;
      }

      var foundSchemas = traverseFindSchemas(result);
      cb(null, foundSchemas);
    });
  },

  knownSchemas: function () {
    var self = this;

    return _.clone(self.parsedSchemas);
  }
};

exports.BASE_TYPES = BASE_TYPES;
exports.XsdMixin = XsdMixin;


text:
(api_references)=

# `references`

```{toctree}
:maxdepth: 1

intersphinx/index
rst/index
```

```{eval-rst}
.. automodule:: django_docutils.references
```

redpajama_set_name: RedPajamaGithub


text:
#include "../include/csl.h"

/*
 * csl namespaces basic understandings :
 * 0. to allow for ordered search thru lists in use ...
 * 1. Namespaces are also linked on the _Context->System0->Namespaces list with status of USING or NOT_USING
 *      and are moved the front or back of that list if status is set to USING with the 'Symbol node'
 *      This list is ordered so we can set an order to our search thru the namespaces in use.
 *      The first word found within the ordered USING list will be used.
 */

void
Do_Namespace_WithStatus_2 ( dlnode * node, MapFunction2 nsf, int64 nsStateFlag, int64 one, int64 two )
{
    Namespace * ns = ( Namespace * ) node ;
    if ( ns->State == nsStateFlag )
    {
        nsf ( node, one, two ) ;
    }
}

void
_CSL_TreeMap ( MapSymbolFunction2 msf2, uint64 state, int64 one, int64 two )
{
    Tree_Map_Namespaces_State_2Args ( _CSL_->Namespaces->Lo_List, state, msf2, one, two ) ;
}

void
_CSL_NamespacesMap ( MapSymbolFunction2 msf2, uint64 state, int64 one, int64 two )
{
    Tree_Map_Namespaces_State_2Args ( _CSL_->Namespaces->Lo_List, state, msf2, one, two ) ;
}

// list/print namespaces

void
_CSL_ForAllNamespaces ( MapSymbolFunction2 msf2 )
{
    _Printf ( ( byte* ) "\nusing :" ) ;
    _CSL_NamespacesMap ( msf2, USING, 1, 1 ) ;
    _Printf ( ( byte* ) "\nnotUsing :" ) ;
    int64 usingWords = _CSL_->FindWordCount ;
    _CSL_NamespacesMap ( msf2, NOT_USING, 1, 1 ) ;
    int64 notUsingWords = _CSL_->FindWordCount ;
    _CSL_->FindWordCount = usingWords + notUsingWords ;
    CSL_WordAccounting ( ( byte* ) "_CSL_ForAllNamespaces" ) ;
}

void
Namespace_PrettyPrint ( Namespace* ns, int64 indentFlag, int64 indentLevel )
{
    if ( indentFlag )
    {
        _Printf ( ( byte* ) "\n" ) ;
        while ( indentLevel -- ) _Printf ( ( byte* ) "\t" ) ;
    }
    if ( ns->State & NOT_USING ) _Printf ( ( byte* ) " - %s", c_gd ( ns->Name ) ) ;
    else _Printf ( ( byte* ) " - %s", ns->Name ) ;
    _Context_->NsCount ++ ;
}

void
CSL_Namespace_New ( )
{
    Namespace * ns = Namespace_FindOrNew_SetUsing ( ( byte* ) DataStack_Pop ( ), _CSL_Namespace_InNamespaceGet ( ), 1 ) ;
    Namespace_Do_Namespace ( ns, 0 ) ;

}

void
_CSL_Namespace_NotUsing ( byte * name )
{
    Namespace * ns = Namespace_Find ( name ) ;
    if ( ns )
    {
        _Namespace_RemoveFromUsingList ( ns ) ;
        _Namespace_ResetFromInNamespace ( ns ) ;
    }
}

void
CSL_Namespace_NotUsing ( )
{
    byte * name = ( byte* ) DataStack_Pop ( ) ;
    _CSL_Namespace_NotUsing ( name ) ;
}

void
CSL_Namespace_UsingFirst ( )
{
    Namespace * ns = Namespace_Find ( ( byte* ) DataStack_Pop ( ) ) ;
    if ( ns ) _Namespace_AddToUsingList ( ns ) ;
}

void
CSL_Namespace_UsingLast ( )
{
    _Namespace_SetAs_UsingLast ( ( byte* ) DataStack_Pop ( ) ) ;
}

void
CSL_Namespace_SetStateAs_Using ( )
{
    byte * token = ( byte* ) DataStack_Pop ( ) ;
    Namespace * ns = Namespace_Find ( token ) ;
    _Namespace_SetState_AsUsing ( ns ) ;
}

void
CSL_Namespace_SetStateAs_NotUsing ( )
{
    byte * token = ( byte* ) DataStack_Pop ( ) ;
    Namespace * ns = Namespace_Find ( token ) ;
    _Namespace_SetStateAs_NotUsing ( ns ) ;
}

// "in"

void
CSL_PrintInNamespace ( )
{
    _Printf ( ( byte* ) "\nCurrent Namespace Being Compiled : %s\n",
        _CSL_Namespace_InNamespaceGet ( )->Name ) ;
}

// list/print namespaces

void
CSL_Namespaces ( )
{
    _Printf ( ( byte* ) "\nAll Namespaces : \n<list> ':' '-' <namespace>" ) ;
    _CSL_ForAllNamespaces ( ( MapSymbolFunction2 ) Symbol_NamespacePrettyPrint ) ;
    _Printf ( ( byte* ) "\n" ) ;
}

int64
Word_RemoveIfStringContainsName ( Symbol * symbol, byte * name )
{
    if ( symbol && symbol->Name && strstr ( ( CString ) symbol->Name, ( CString ) name ) )
    {
        dlnode_Remove ( (dlnode*) symbol ) ;
        Word_Recycle ( (Word *) symbol ) ;
    }
    return 0 ;
}

void
_CSL_Namespaces_PurgeWordIfContainsName ( byte * name )
{
    Tree_Map_State_OneArg ( USING | NOT_USING, ( MapFunction_1 ) Word_RemoveIfStringContainsName, ( int64 ) name ) ;
}

void
CSL_Namespaces_PurgeWordIfContainsName ( )
{
   byte * name = ( byte* ) DataStack_Pop ( ) ;
   _CSL_Namespaces_PurgeWordIfContainsName ( name ) ;
}

int64
Word_RemoveIfStringEqualExactName ( Symbol * symbol, byte * name )
{
    if ( String_Equal ( symbol->Name, name ) )
    {
        dlnode_Remove ( (dlnode*) symbol ) ;
        Word_Recycle ( (Word *) symbol ) ;
    }
    return 0 ;
}

void
_CSL_Namespaces_PurgeWordExactName ( byte * name )
{
    Tree_Map_State_OneArg ( USING | NOT_USING, ( MapFunction_1 ) Word_RemoveIfStringEqualExactName, ( int64 ) name ) ;
}

void
CSL_Namespaces_PurgeWordExactName ( )
{
   byte * name = ( byte* ) DataStack_Pop ( ) ;
   _CSL_Namespaces_PurgeWordExactName ( name ) ;
}

void
Symbol_SetNonTREED ( Symbol * symbol, int64 one, int64 two )
{
    Namespace * ns = ( Namespace * ) symbol ;
    ns->State &= ~ TREED ;
}

void
Symbol_Namespaces_PrintTraverse ( Symbol * symbol, int64 containingNamespace, int64 indentLevel )
{
    Namespace * ns = ( Namespace * ) symbol ;
    if ( ns->ContainingNamespace == ( Namespace* ) containingNamespace )
    {
        if ( ! ( ns->State & TREED ) )
        {
            ns->State |= TREED ;
            Namespace_PrettyPrint ( ns, 1, indentLevel ) ;
            _Namespace_MapAny_2Args ( ( MapSymbolFunction2 ) Symbol_Namespaces_PrintTraverse, ( int64 ) ns, indentLevel + 1 ) ;
        }
    }
}

void
Symbol_Namespaces_PrintTraverseWithWords ( Symbol * symbol, int64 containingNamespace, int64 indentLevel )
{
    Namespace * ns = ( Namespace * ) symbol ;
    if ( ns->ContainingNamespace == ( Namespace* ) containingNamespace )
    {
        if ( ! ( ns->State & TREED ) )
        {
            ns->State |= TREED ;
            Namespace_PrettyPrint ( ns, 1, indentLevel ) ;
            dllist_Map1 ( ns->Lo_List, ( MapFunction1 ) _Word_Print, 0 ) ;
            _Namespace_MapAny_2Args ( ( MapSymbolFunction2 ) Symbol_Namespaces_PrintTraverseWithWords, ( int64 ) ns, indentLevel + 1 ) ;
        }
    }
}

void
CSL_Namespaces_PrettyPrintTree ( )
{
    _Context_->NsCount = 0 ;
    _Context_->WordCount = 0 ;
    //SetState ( _O_->psi_PrintStateInfo, PSI_PROMPT, false ) ;
    _Printf ( ( byte* ) "\nNamespaceTree - All Namespaces : %s%s%s", c_ud ( "using" ), " : ", c_gd ( "not using" ) ) ;
    _Namespace_MapAny_2Args ( ( MapSymbolFunction2 ) Symbol_SetNonTREED, 0, 0 ) ;
    _Namespace_MapAny_2Args ( ( MapSymbolFunction2 ) Symbol_Namespaces_PrintTraverse, ( int64 ) _CSL_->Namespaces, 1 ) ;
    _Printf ( ( byte* ) "\nTotal namespaces = %d :: Total words = %d\n", _Context_->NsCount, _Context_->WordCount ) ;
}

void
CSL_Namespaces_PrettyPrintTreeWithWords ( )
{
    _Context_->NsCount = 0 ;
    _Context_->WordCount = 0 ;
    //SetState ( _O_->psi_PrintStateInfo, PSI_PROMPT, false ) ;
    _Printf ( ( byte* ) "%s%s%s%s%s%s%s", "\nNamespaceTree - All Namespaces : ", "using", " : ", c_gd ( "not using" ), " :: ", "with", c_ud ( " : words" ) ) ;
    _Namespace_MapAny_2Args ( ( MapSymbolFunction2 ) Symbol_SetNonTREED, 0, 0 ) ;
    _Namespace_MapAny_2Args ( ( MapSymbolFunction2 ) Symbol_Namespaces_PrintTraverseWithWords, ( int64 ) _CSL_->Namespaces, 1 ) ;
    _Printf ( ( byte* ) "\nTotal namespaces = %d :: Total words = %d\n", _Context_->NsCount, _Context_->WordCount ) ;
}

void
_Namespace_Symbol_Print ( Symbol * symbol, int64 printFlag, int64 str )
{
    char buffer [128] ;
    Namespace * ns = ( Namespace * ) symbol ;
    sprintf ( buffer, "%s ", ns->Name ) ;
    if ( printFlag )
    {
        _Printf ( ( byte* ) "%s", buffer ) ;
    }
    else strcat ( ( char* ) str, buffer ) ;
}

// prints all the namespaces on the SearchList
// 'using'

byte *
_CSL_UsingToString ( )
{
    byte * b = Buffer_Data ( _CSL_->ScratchB1 ) ;
    strcpy ( ( char* ) b, "" ) ;
    Tree_Map_Namespaces_State_2Args ( _CSL_->Namespaces->Lo_List, USING, ( MapSymbolFunction2 ) _Namespace_Symbol_Print, 0, ( int64 ) b ) ;
    b = String_New ( ( byte* ) b, TEMPORARY ) ;
    return b ;
}

void
CSL_Using ( )
{
    _Printf ( ( byte* ) "\nUsing Namespaces :> " ) ;
    Tree_Map_Namespaces_State_2Args ( _CSL_->Namespaces->Lo_List, USING, ( MapSymbolFunction2 ) _Namespace_Symbol_Print, 1, 0 ) ;
    _Printf ( ( byte* ) "\n" ) ;
}

// this namespace is will be taken out of the system

void
CSL_NonCompilingNs_Clear ( Compiler * compiler )
{
    if ( compiler->NonCompilingNs )
    {
        _Namespace_RemoveFromUsingListAndClear (compiler->NonCompilingNs) ;
        compiler->NonCompilingNs = 0 ;
    }
}

Word *
_CSL_VariableGet ( Namespace * ns, byte * name )
{
    ns = Word_UnAlias ( ns ) ;
    Word * word = _Finder_FindWord_InOneNamespace ( _Finder_, ns, name ) ;
    return word ;
}

int64
_CSL_VariableValueGet ( byte* nameSpace, byte * name )
{
    return _Namespace_VariableValueGet ( Namespace_Find ( nameSpace ), name ) ;
}

void
_CSL_RemoveNamespaceFromUsingListAndClear ( byte * name )
{
    _Namespace_RemoveFromUsingListAndClear ( Namespace_Find ( name ) ) ;
}

//keep the stack intack just remove the namespace from the Namespaces list and set them as not using

void
Namespace_RemoveNamespacesStack ( Stack * stack )
{
    if ( stack )
    {
        int64 n = Stack_Depth ( stack ) ;
        while ( n > 0 )
        {
            Namespace * ns = ( Namespace* ) _Stack_Pop ( stack ) ;
            if ( ns )
            {
                if ( ns == _CSL_->InNamespace ) _CSL_->InNamespace = 0 ;
                if ( _Finder_ && ( ns == _Finder_->QualifyingNamespace ) ) Finder_SetQualifyingNamespace ( _Context_->Finder0, 0 ) ;
                _Namespace_SetState ( ns, NOT_USING ) ;
                dlnode_Remove ( ( dlnode* ) ns ) ;
            }
            n -- ;
        }
    }
}

void
Namespace_RemoveAndClearNamespacesStack ( Stack * stack )
{
    if ( stack )
    {
        int64 n ;
        for ( n = Stack_Depth ( stack ) ; n ; n -- )
        {
            Namespace * ns = ( Namespace* ) Stack_Pop ( stack ) ;
            if ( ns ) _Namespace_RemoveFromUsingListAndClear ( ns ) ;
        }
        Stack_Init ( stack ) ;
    }
}

#if 0
void
Namespace_NamespacesStack_PrintWords ( Stack * stack )
{
    if ( stack )
    {
        int64 n ;
        for ( n = Stack_Depth ( stack ) ; n > 0 ; n -- )
        {
            Namespace * ns = stack->StackPointer [n] ; //( Namespace* ) Stack_Pop ( stack ) ;
            //if ( ns ) _Namespace_RemoveFromUsingListAndClear ( ns ) ;
            n -- ;
        }
    }
}
#endif


text:
#ifndef SimTK_SIMBODY_CABLE_SPRING_H_
#define SimTK_SIMBODY_CABLE_SPRING_H_

#include "SimTKcommon.h"
#include "simbody/internal/common.h"
#include "simbody/internal/Force.h"
#include "simbody/internal/CablePath.h"

/** @file
This contains the user-visible API ("handle" class) for the SimTK::Force
subclass CableSpring, providing an elastic band force element that follows a
given CablePath. **/

namespace SimTK {

/** This force element implements a passive elastic element (like a
rubber band) that follows a frictionless CablePath across a set of "obstacles".
The element calculates a uniform nonnegative tension that is used to apply
forces at the end points of the CablePath and to each intermediate obstacle.
The model provides stiffness and dissipation, and has a slack length below
which the tension is zero and no forces are generated. Dissipated power is
calculated and integrated so that work lost to dissipation is available for
conservation of energy calculations.

\par Theory:

Given current CablePath length L with time derivative Ldot, and slack length
L0 for this force element, define stretch x=max(0,L-L0) and xdot=Ldot. Then
calculate the nonnegative tension f(x,xdot), the potential energy pe(x) stored
in this force element, and dissipating power powerLoss(x,xdot) due to
rate-dependent resistance to length change, as follows:

    f_stretch   = k*x
    f_rate      = max(-f_stretch, f_stretch*c*xdot)
    f           = f_stretch + f_rate
    pe          = k*x^2/2
    powerLoss   = f_rate * xdot
    dissipation = integ(powerLoss, dt)

where \c k >= 0 is the stiffness coefficient (force per unit length) and
\c c >= 0 is the dissipation coefficient (1/velocity) for this force element.

Note that in this model the tension component \c f_rate, due to rate-dependent
dissipation in the elastic element, is calculated as a fraction of the
stretch-dependent tension component \c f_stretch, similar to a Hunt and Crossley
contact model. That is why the dissipation coefficient \c c has units of
1/velocity, rather than force/velocity. This makes the generated tension grow
smoothly from zero as the slack length is exceeded, but even so this is not
necessarily a good model for any particular physically-realizable elastic
element. A ligament, for example, while perhaps qualitatively similar to this
element, is likely to require a more complicated relationship between
\c x, \c xdot, and \c f to yield quantitative agreement with experimental data.

While the total tension \c f must be nonnegative, the tension \c f_rate due to
stretch rate can be positive (resists stretching) or negative (resists
shortening) but can never be less than \c -f_stretch since \c f can't be
negative. When a stretched cable spring is shortening so rapidly that force due
to dissipation cancels the force due to stiffness, there will be no tension
generated but we will still dissipate power at a rate that exactly accounts for
the continuing loss of potential energy in the spring (k*x*xdot)
as it shortens to its slack length. In that way total energy
E=pe+ke+dissipation is conserved, where \c dissipation is the
time integral of \c powerLoss calculated above (note that \c powerLoss >= 0
as defined).

@see CablePath, CableTrackerSubsystem **/
class SimTK_SIMBODY_EXPORT CableSpring : public Force {
public:

/** Create an elastic force element that follows a given CablePath and add it
to a GeneralForceSubsystem. Default values for the cable spring properties
are given here; you can override them in the State. See the %CableSpring class
description for a detailed explanation of these parameters.

@param[in,out]      forces
    The subsystem to which this force element should be added.
@param[in]          path
    The CablePath that defines the routing of this elastic element over
    geometric obstacles.
@param[in]          defaultStiffness
    A nonnegative spring constant representing the stiffness of this element,
    in units of force/length, where the force represents a uniform tension along
    the element that results from stretching it beyond its slack length.
@param[in]          defaultSlackLength
    The maximum length this elastic element can have before it begins to
    generate force. At or below this length the element is slack and has zero
    tension and zero power dissipation.
@param[in]          defaultDissipationCoef
    A nonnegative dissipation coefficient for this elastic element in units of
    1/velocity.
**/
CableSpring(GeneralForceSubsystem&  forces,
            const CablePath&        path,
            Real                    defaultStiffness,
            Real                    defaultSlackLength,
            Real                    defaultDissipationCoef);

/** Default constructor creates an empty handle. **/
CableSpring() {}

//------------------------------------------------------------------------------
/** @name                      Default Parameters

These refer to Topology-stage parameters normally set in the constructor; these
determine the initial values assigned to the corresponding Instance-stage state
variables.

\par Notes
- Changing one of these parameters invalidates the containing System's
  topology, meaning that realizeTopology() will have to be called
  before subsequent use.
- The set...() methods return a reference to "this" CableSpring (in
  the manner of an assignment operator) so they can be chained in a
  single expression. **/
/**@{**/

/** Set the stiffness (spring constant) k that will be used by default
for this cable spring; must be nonnegative.
@param[in]  stiffness       The spring constant k to be used by default.
@return A writable reference to "this" %CableSpring which will now have the new
default stiffness. **/
CableSpring& setDefaultStiffness(Real stiffness);
/** Set the slack length L0 that will be used by default for this cable spring;
must be nonnegative.
@param[in]  slackLength     The slack length L0 to be used by default.
@return A writable reference to "this" %CableSpring which will now have the new
default slack length. **/
CableSpring& setDefaultSlackLength(Real slackLength);
/** Set the dissipation coefficient c that will be used by default for this
cable spring; must be nonnegative.
@param[in]  dissipation     The dissipation coefficient c to be used by default.
@return A writable reference to "this" %CableSpring which will now have the new
default dissipation coefficient. **/
CableSpring& setDefaultDissipationCoef(Real dissipation);

/** Return the stiffnesses k that will be used by default for this cable spring.
@return The default spring constant. **/
Real getDefaultStiffness() const;
/** Return the slack length L0 that will be used by default for this cable spring.
@return The default slack length. **/
Real getDefaultSlackLength() const;
/** Return the dissipation coefficient c that will be used by default for this
cable spring.
@return The default dissipation coefficient. **/
Real getDefaultDissipationCoef() const;
/**@}**/

//------------------------------------------------------------------------------
/**@name                     Instance Parameters

These refer to the Instance-stage state variables that determine the geometry
and material properties that will be used in computations involving this cable
spring when performed with the given State. If these are not set explicitly,
the default values are set to those provided in the constructor or via the
corresponding setDefault...() methods.

\par Notes
- Changing one of these parameters invalidates the given State's Instance stage,
  meaning that realize(Instance) will have to be called (explicitly or
  implicitly by realizing a higher stage) before subsequent use.
- The set...() methods here return a const reference to "this" %CableSpring (in
  the manner of an assignment operator, except read-only) so they can be chained
  in a single expression.
**/
/**@{**/
/** Set the stiffness (spring constant) k that will be used for this cable
spring when evaluated using this State.
@pre \a state realized to Stage::Topology
@param[in,out]  state       The State object to be modified by this method.
@param[in]      stiffness   The spring constant k.
@return A const reference to "this" %CableSpring for convenient chaining of
set...() methods in a single expression. **/
const CableSpring& setStiffness(State&      state,
                                Real        stiffness) const;
/** Set the slack length L0 that will be used for this cable spring when
evaluated using this State.
@pre \a state realized to Stage::Topology
@param[in,out]  state       The State object to be modified by this method.
@param[in]      slackLength The slack length L0.
@return A const reference to "this" %CableSpring for convenient chaining of
set...() methods in a single expression. **/
const CableSpring& setSlackLength(State&    state,
                                  Real      slackLength) const;
/** Set the dissipation coefficient c that will be used for this cable spring
when evaluated using this State.
@pre \a state realized to Stage::Topology
@param[in,out]  state       The State object that is modified by this method.
@param[in]      dissipationCoef The dissipation coefficient c.
@return A const reference to "this" %CableSpring for convenient chaining of
set...() methods in a single expression. **/
const CableSpring& setDissipationCoef(State&    state,
                                      Real      dissipationCoef) const;

/** Return the stiffness (spring constant) k currently being used for this cable
spring by this State.
@pre \a state realized to Stage::Topology
@param[in]  state   The State object from which to obtain the stiffness.
@return The current value in the given state of the spring constant k. **/
Real getStiffness(const State& state) const;
/** Return the slack length L0 currently being used for this cable spring by
this State.
@pre \a state realized to Stage::Topology
@param[in]  state   The State object from which to obtain the slack length.
@return The current value in the given state of the slack length L0. **/
Real getSlackLength(const State& state) const;
/** Return the dissipation coefficient c currently being used for this cable
spring by this State.
@pre \a state realized to Stage::Topology
@param[in]  state   The State object from which to obtain the dissipation
                    coefficient.
@return The current value in the given state of the dissipation
coefficient c. **/
Real getDissipationCoef(const State& state)   const;
/**@}**/

//------------------------------------------------------------------------------
/** @name               Position-related Quantities

These methods return position-dependent quantities that are calculated
by the cable spring as part of its force calculations and stored in the
State cache. These can be obtained at no cost, although the first call
after a position change may initiate computation if forces haven't
already been computed.

@pre These methods may be called only after the supplied state has
     been realized to Stage::Position. **/
/**@{**/
/** Return the current length of the CablePath that underlies this cable spring
element. Note that this may return a value less than the spring's slack length.
@pre \a state realized to Stage::Position
@param  state   The State from which the path length is retrieved.
@return The current length of the underlying CablePath (nonnegative).
@see getLengthDot() **/
Real getLength(const State& state) const;
/**@}**/

//------------------------------------------------------------------------------
/** @name                 Velocity-related Quantities

These methods return velocity-dependent quantities that are calculated
by the cable spring as part of its force calculations and stored in the
State cache. These can be obtained at no cost, although the first call
after a velocity change may initiate computation if forces haven't
already been computed.

@pre These methods may be called only after the supplied state has
     been realized to Stage::Velocity. **/
/**@{**/
/** Return the current rate of length change (time derivative of length) of the
CablePath that underlies this cable spring element.
@pre \a state realized to Stage::Velocity
@param  state   The State from which the path length rate of change is
                retrieved.
@return The current length change rate of the underlying CablePath.
@see getLength() **/
Real getLengthDot(const State& state) const;

/**@}**/

//------------------------------------------------------------------------------
/** @name                          Forces

These methods return the forces being applied by this cable spring in the
configuration and velocities contained in the supplied State. These are
evaluated during force calculation and available at no computational cost
afterwards, although the first call after a velocity change may initiate
computation if forces haven't already been computed.

@pre These methods may be called only after the supplied state has been
     realized to Stage::Velocity. **/
/**@{**/
/** Return the current level of tension in the cable spring.
@pre \a state realized to Stage::Velocity
@param[in]          state
    The State from which the current tension is retrieved.
@return
    The current tension in the cable spring in the configuration and velocity
    contained in \a state (a nonnegative scalar). **/
Real getTension(const State& state) const;
/**@}**/

//------------------------------------------------------------------------------
/** @name                   Energy, Power, and Work

These methods return the energy, power, and work-related quantities associated
with this %CableSpring element for the values in the supplied State. **/
/**@{**/
/** Obtain the potential energy stored in this cable spring in the current
configuration.
@pre \a state realized to Stage::Position
@param[in]          state
    The State from whose cache the potential energy is retrieved.
@return
    The potential energy currently contained in the cable spring in the
    configuration contained in \a state (a nonnegative scalar). **/
Real getPotentialEnergy(const State& state) const;

/** Obtain the rate at which energy is being dissipated by this cable spring,
that is, the power being lost (presumably due to heat). This is in units of
energy/time which is watts in MKS.
@pre \a state realized to Stage::Velocity
@param[in]          state
    The State from which to obtain the current value of the power
    dissipation.
@return
    The instantaneous power dissipation (a nonnegative scalar).
@see getDissipatedEnergy() for the time-integrated power loss **/
Real getPowerDissipation(const State& state) const;

/** Obtain the total amount of energy dissipated by this cable spring since some
arbitrary starting point. This is the time integral of the power dissipation.
For a system whose only non-conservative forces are cable springs, the sum of
potential, kinetic, and dissipated energies should be conserved. This is a
State variable so you can obtain its value any time after it is allocated.
@pre \a state realized to Stage::Model
@param[in]          state
    The State from which to obtain the current value of the dissipated
    energy.
@return
    The total dissipated energy (a nonnegative scalar).
@see getPowerDissipation() for the instantaneous power loss **/
Real getDissipatedEnergy(const State& state) const;

/** Set the accumulated dissipated energy to an arbitrary value. Typically
this is used only to reset the dissipated energy to zero, but non-zero values
can be useful if you are trying to match some existing data or continuing a
simulation. This is a State variable so you can set its value any time after it
is allocated.
@pre \a state realized to Stage::Model
@param[in,out]      state
    The State whose dissipated energy variable for this cable spring is to
    be modified.
@param[in]          energy
    The new value for the accumulated dissipated energy (must be a nonnegative
    scalar). **/
void setDissipatedEnergy(State& state, Real energy) const;
/**@}**/

/**@name                Advanced/obscure/debugging
Miscellaneous methods that you probably aren't going to need. **/
/**@{**/
/** Get a reference to the CablePath that is used to determine the routing of
this cable spring force element. This is set during %CableSpring construction
and cannot be changed subsequently. **/
const CablePath& getCablePath() const;
/**@}**/

/** @cond **/ // Don't show this in Doxygen.
class Impl;
SimTK_INSERT_DERIVED_HANDLE_DECLARATIONS
    (CableSpring, CableSpring::Impl, Force);
/** @endcond **/
};

} // namespace SimTK

#endif // SimTK_SIMBODY_CABLE_SPRING_H_


text:
{% extends "projector/project/detail.html" %}

{% load i18n %}
{% load markup %}
{% load native %}
{% load projector_tags %}
{% load richtemplates_tags %}

{% block col-single-extra %}

{% trans "Project's repository browser" %}

    {% block repository-menu %}

            {% trans "Sources" %}
            {% trans "Changesets" %}

    {% endblock %}

    {% block browse-content %}

        {% block browse-content-info %}
        {% load breadcrumber %}

            {% path_breadcrumbs request.META.PATH_INFO 3 %}

        {% block changeset-message %}
        {% if changeset %}

                {% trans "Committed by" %} {{ changeset.author|hide_email }}
                {{ changeset.date|timesince }}
                {% trans "ago" %}

                {{ changeset.message }}

        {% endif %}
        {% endblock %}

                    {% trans "Path" %}
                    {{ root.path|default:"/"|slice:"20" }}{% if root.path|length > 20 %}...{% endif %}

                    {% trans "Revision" %}
                    {{ root.changeset }}

                {% if root.is_file %}

                    {% trans "Last committer" %}
                    {{ root.last_changeset.author|hide_email|tooltip:"80" }}

                    {% trans "Last modified" %}
                    {{ root.last_changeset.date|timesince }}

                    {% trans "Size" %}
                    {% if root.is_file %}{{ root.size|filesizeformat }}{% endif %}

                    {% trans "Mimetype" %}
                    {{ root.mimetype }}

                    {% trans "Download" %}
                    {% trans "raw file" %}

                    {% trans "Annotate" %}
                    {% trans "annotate" %}

                {% endif %}

        {# history #}
        {% if root.is_file %}

{% trans "History" %}

            {% for changeset in root.history %}

                {{ changeset }}
            {% if root.changeset.id != changeset.id %}
            ({% trans "diff" %})
            {% endif %}

            {% endfor %}

        {% endif %}
        {# end history #}

        {% endblock %}

        {% if root.is_dir %}

                    {% trans "Name" %}
                    {% trans "Size" %}
                    {% trans "Revision" %}
                    {% trans "Last modified" %}
                    {% trans "Last committer" %}

                {% if root.parent %}

                        ..

                {% endif %}

                {% for node in root.nodes %}

                        {{ node.name }}

                    {% if node.is_dir %}

                    {% else %}
                    {% if node.is_file %}{{ node.size|filesizeformat }}{% endif %}

                        {{ node.last_changeset.revision }}

                        {{ node.last_changeset.date|timesince }} {% trans "ago" %}

                    {{ node.last_changeset.author|hide_email|tooltip:"20" }}
                    {% endif %}

                {% endfor %}

        {% endif %}
        {% if root.is_file %}

            {% if root.is_binary %}

{% trans "This is binary file" %}

            {% else %}

                {% highlight root.content root.lexer_alias linenos=true anchorlinenos=true lineanchors=line cssclass="code-highlight" %}

            {% endif %}
        {% endif %}

    {% endblock %}

{% if readme_node and readme_node.content %}

{{ readme_node }}

            {% highlight readme_node.content readme_node.lexer_alias linenos=true anchorlinenos=true lineanchors=line cssclass="code-highlight" %}

{% endif %}

{% endblock %}


text:
namespace Xamarin.Forms.Internals
{
	public interface IDynamicResourceHandler
	{
		void SetDynamicResource(BindableProperty property, string key);
	}
}


text:
#include "Tag.hpp"
#include <sstream>
#include <boost/algorithm/string.hpp>

namespace bmrk {

Tags parseTags(const String& str) {
  Tags tags;
  boost::split(tags, str, boost::is_any_of(","));
  return tags;
}

String formatTags(const Tags& tags) {
  std::stringstream stream;
  for (unsigned i = 0; i < tags.size(); ++i) {
    stream << (i ? "," : "") << tags[i];
  }
  return stream.str();
}

} /* bmrk  */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Opegrapha durieui Mont.

### Remarks
null


text:
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { FormattedHTMLMessage } from 'react-intl';
import BigNumber from 'bignumber.js';
import globalMessages from '../../i18n/global-messages';
import LoadingSpinner from '../widgets/LoadingSpinner';
import styles from './StakingUnavailable.scss';

type Props = {
  syncPercentage: number;
};

@observer
class StakingUnavailable extends Component<Props> {
  render() {
    const { syncPercentage } = this.props;
    return (

        <LoadingSpinner big />

          <FormattedHTMLMessage
            {...globalMessages.featureUnavailableWhileSyncing}
            values={{
              syncPercentage: new BigNumber(syncPercentage).toFormat(2),
            }}
          />

    );
  }
}

export default StakingUnavailable;


text:
It's a terminal read-only Meatspace Chat client. That's it. I didn't want to keep the Meatspace window open all the time, but I also wanted to keep an eye on what's happening in the chatroom. I have a problem.

## Usage

```bash
npm install -g meatspace-cleaver
meatcleaver
```

`ctrl+c` to exit and embrace FOMO.

## Channels

You can specify which subdomain you're connecting to by passing it as an argument.

```bash
meatcleaver -c fr
meatcleaver -c es
meatcleaver -c chat
```

This does not work for the staging server because I am lazy.


text:
package com.aliyun.oss.internal;

import static com.aliyun.oss.common.utils.CodingUtils.assertTrue;
import static com.aliyun.oss.internal.RequestParameters.PART_NUMBER;
import static com.aliyun.oss.internal.RequestParameters.POSITION;
import static com.aliyun.oss.internal.RequestParameters.SECURITY_TOKEN;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_ACL;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_APPEND;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_CORS;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_DELETE;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_LIFECYCLE;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_LOCATION;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_LOGGING;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_REFERER;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_UPLOADS;
import static com.aliyun.oss.internal.RequestParameters.SUBRESOURCE_WEBSITE;
import static com.aliyun.oss.internal.RequestParameters.UPLOAD_ID;
import static com.aliyun.oss.model.ResponseHeaderOverrides.RESPONSE_HEADER_CACHE_CONTROL;
import static com.aliyun.oss.model.ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_DISPOSITION;
import static com.aliyun.oss.model.ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_ENCODING;
import static com.aliyun.oss.model.ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_LANGUAGE;
import static com.aliyun.oss.model.ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_TYPE;
import static com.aliyun.oss.model.ResponseHeaderOverrides.RESPONSE_HEADER_EXPIRES;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.aliyun.oss.common.comm.RequestMessage;
import com.aliyun.oss.common.utils.HttpHeaders;

public class SignUtils {

	private static final String NEW_LINE = "\n";

    private static final List<String> SIGNED_PARAMTERS = Arrays.asList(new String[] {
    		SUBRESOURCE_ACL, SUBRESOURCE_UPLOADS, SUBRESOURCE_LOCATION,
    		SUBRESOURCE_CORS, SUBRESOURCE_LOGGING, SUBRESOURCE_WEBSITE,
    		SUBRESOURCE_REFERER, SUBRESOURCE_LIFECYCLE, SUBRESOURCE_DELETE,
    		SUBRESOURCE_APPEND, UPLOAD_ID, PART_NUMBER, SECURITY_TOKEN, POSITION,
            RESPONSE_HEADER_CACHE_CONTROL, RESPONSE_HEADER_CONTENT_DISPOSITION,
            RESPONSE_HEADER_CONTENT_ENCODING, RESPONSE_HEADER_CONTENT_LANGUAGE,
            RESPONSE_HEADER_CONTENT_TYPE, RESPONSE_HEADER_EXPIRES
    });

    public static String buildCanonicalString(String method, String resourcePath,
            RequestMessage request, String expires) {

    	StringBuilder canonicalString = new StringBuilder();
        canonicalString.append(method + NEW_LINE);

        Map<String, String> headers = request.getHeaders();
        TreeMap<String, String> headersToSign = new TreeMap<String, String>();

        if (headers != null) {
            for(Entry<String, String> header : headers.entrySet()) {
                if (header.getKey() == null) {
                    continue;
                }

                String lowerKey = header.getKey().toLowerCase();

                if (lowerKey.equals(HttpHeaders.CONTENT_TYPE.toLowerCase())
                        || lowerKey.equals(HttpHeaders.CONTENT_MD5.toLowerCase())
                        || lowerKey.equals(HttpHeaders.DATE.toLowerCase())
                        || lowerKey.startsWith(OSSHeaders.OSS_PREFIX)) {
                    headersToSign.put(lowerKey, header.getValue());
                }
            }
        }

        if (!headersToSign.containsKey(HttpHeaders.CONTENT_TYPE.toLowerCase())) {
            headersToSign.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), "");
        }
        if (!headersToSign.containsKey(HttpHeaders.CONTENT_MD5.toLowerCase())) {
            headersToSign.put(HttpHeaders.CONTENT_MD5.toLowerCase(), "");
        }

        // Add all parameters that prefixed with "x-oss-" into headers to sign
        if (request.getParameters() != null) {
            for(Map.Entry<String, String> p : request.getParameters().entrySet()) {
                if (p.getKey().startsWith(OSSHeaders.OSS_PREFIX)) {
                    headersToSign.put(p.getKey(), p.getValue());
                }
            }
        }

        // Append all headers to sign to canonical string
        for(Map.Entry<String, String> entry : headersToSign.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();

            if (key.startsWith(OSSHeaders.OSS_PREFIX)) {
                canonicalString.append(key).append(':').append(value);
            } else {
                canonicalString.append(value);
            }

            canonicalString.append(NEW_LINE);
        }

        // Append canonical resource to canonical string
        canonicalString.append(buildCanonicalizedResource(resourcePath, request.getParameters()));

        return canonicalString.toString();
    }

    private static String buildCanonicalizedResource(String resourcePath, Map<String, String> parameters) {

    	assertTrue(resourcePath.startsWith("/"), "Resource path should start with slash character");

        StringBuilder builder = new StringBuilder();
        builder.append(resourcePath);

        if (parameters != null) {
            String[] parameterNames = parameters.keySet().toArray(
                    new String[parameters.size()]);
            Arrays.sort(parameterNames);

            char separater = '?';
            for(String paramName : parameterNames) {
                if (!SIGNED_PARAMTERS.contains(paramName)) {
                    continue;
                }

                builder.append(separater);
                builder.append(paramName);
                String paramValue = parameters.get(paramName);
                if (paramValue != null) {
                    builder.append("=").append(paramValue);
                }

                separater = '&';
            }
        }

        return builder.toString();
    }
}


text:
define(['js/lib/promise'], function(Promise) {

    function Online() {

    }

    Online.checkInternet = function() {
        var deferred = Promise.defer();

        $.ajax({
            url: "http://query.yahooapis.com/v1/public/yql",

            // the name of the callback parameter, as specified by the YQL service
            jsonp: "callback",

            // tell jQuery we're expecting JSONP
            dataType: "jsonp",

            data: {
                q: "select title,abstract,url from search.news where query=\"cat\"",
                format: "json"
            },
            // work with the response
            success: function() {
                deferred.resolve();
            },

            error: function () {
                deferred.reject();
            }

        });

        return deferred;
    }

    return Online;

});


text:
AVR
===

Code used for ATMega, ATXMega, and Arduino development projects


text:
package graph;

import java.io.Serializable;
import java.util.List;

public interface DirectedNetwork<T> extends Serializable {

    int addNode(T content, int...incidentNodes) throws GraphException;

    T removeNode(int node) throws GraphException;

    void makeIncident(int node1, int node2) throws GraphException;

    void makeNotIncident(int node1, int node2);

    boolean areIncident(int node1, int node2);

    int getMaxAllowedNodeInDegree();

    int getMaxAllowedNodeOutDegree();

    int getOrder();

    int getSize();

    List<Integer> findNodesWithValue(T value);

    List<Integer> getIncidentNodes(int nodeId);

    List<Integer> getReachableNodes(int nodeId);

    T getNodeContent(int nodeId);

    List<Integer> getAllNodeIds();
}


text:
@class DailyDoBase;

@interface DailyDoDateView : KMViewBase

@property (nonatomic) DailyDoBase *dailyDo;

@property (nonatomic) IBOutlet UILabel *dayLabel;
@property (nonatomic) IBOutlet UILabel *monthAndYearLabel;
@property (nonatomic) IBOutlet UILabel *titleLabel;
@property (nonatomic) IBOutlet UIImageView *bubbleImage;

+ (CGFloat)heightForDailyDo:(DailyDoBase *)dailyDo fixWidth:(CGFloat)width;
@end


text:
<?php

namespace Imerir\ProduitBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ReceptionCommandeController extends Controller
{
    public function ajoutReceptionAction()
    {
        $soap = $this->get('noyau_soap');
        $query = $this->get('request');
        //PARTIE RECHERCHE
        /*
        Nom fournisseur :
        <input type="text" name="recherche_fournisseur_nom_fournisseur">
        Article :
        <input type="text" name="recherche_fournisseur_article">
        Numéro de commande :
        <input type="text" name="recherche_commande_fournisseur_id">
        */
        $recherche_nom = $query->query->get('recherche_fournisseur_nom_fournisseur');
        $recherche_article = $query->query->get('recherche_fournisseur_article');
        $recherche_commande = $query->query->get('recherche_commande_fournisseur_id');

        $erreur = '';

        if(!empty($recherche_nom))
            $nom = $recherche_nom;
        else
            $nom = '';
        if(!empty($recherche_article))
            $article = $recherche_article;
        else
            $article = '';
        if(!empty($recherche_commande))
            $commande = $recherche_commande;
        else
            $commande = '';
        //////////////////

        try {
        	//on recupere le menu et sous menu
        	$return_menu = $soap->call('getMenu', array());
        	$menu_sous_menu = json_decode($return_menu);
        }
        catch(\SoapFault $e) {
        	$erreur.=$e->getMessage();
        }

        try {
            $return = $soap->call('getFournisseurs', array('count' => 0, 'offset' => 0, 'nom' => '', 'email' => '',
                'telephone_portable' => '', 'reference_client' => '', 'notes' => ''));
            $liste_fournisseurs = json_decode($return);
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        try {
            //($count, $offset, $fournisseur_id, $fournisseur_nom, $commande_id, $article_code)
            $return_commandes = $soap->call('getCommandesFournisseurs', array('count' => 0, 'offset' => 0, 'fournisseur_id' => '',
                'fournisseur_nom' => $nom, 'commande_id' => $commande, 'article_code' => $article));
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        $liste_commandes = json_decode($return_commandes);
        return $this->render('ImerirProduitBundle::ajoutReceptionCommande.html.twig',array('result_menu' => $menu_sous_menu,
            'liste_fournisseurs'=>$liste_fournisseurs,'liste_commandes'=>$liste_commandes,'nbLignes'=>0,'erreur'=>$erreur,
            'flag_no_commande'=>''));
    }

    public function saisieReceptionAction(){
        //PARTIE COMMUNE////////
        $soap = $this->get('noyau_soap');
        $query = $this->get('request');
        ///////////////////////

        $modif_fournisseur_id = $query->request->get('modif_fournisseur_id');
        $modif_date_commande = $query->request->get('modif_commande_date_commande');
        $modif_commande_id = $query->request->get('modif_commande_id');
        $modif_code_barre = $query->request->get('modif_code_barre');
        $modif_quantite_souhaite = $query->request->get('modif_quantite_souhaite');
        $modif_quantite_recu = $query->request->get('modif_quantite_recu');

        $erreur = '';

        $liste_lignes_commandes = '';

        if($modif_commande_id != null){
        	try {
        		$return_liste_lignes_commandes = $soap->call('getLignesCommandesFournisseurs', array('count' => 0, 'offset' => 0, 'fournisseur_id' => '',
        				'fournisseur_nom' => '', 'commande_id' => $modif_commande_id, 'article_code' => ''));
        	}
        	catch(\SoapFault $e) {
        		$erreur .=$e->getMessage();
        	}
        	$liste_lignes_commandes = json_decode($return_liste_lignes_commandes);
        }

        //PARTIE COMMUNE//////////////////////////////////////////
        try {
        	$return_menu = $soap->call('getMenu', array());
        	$menu_sous_menu = json_decode($return_menu);
        }
        catch(\SoapFault $e) {
        	$erreur.=$e->getMessage();
        }

        try {
            $return = $soap->call('getFournisseurs', array('count' => 0, 'offset' => 0, 'nom' => '', 'email' => '',
                'telephone_portable' => '', 'reference_client' => '', 'notes' => ''));
            $liste_fournisseurs = json_decode($return);
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        try {
            $return_commandes = $soap->call('getCommandesFournisseurs', array('count' => 0, 'offset' => 0, 'fournisseur_id' => '',
                'fournisseur_nom' => '', 'commande_id' => '', 'article_code' => ''));

        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }
        $liste_commandes = json_decode($return_commandes);
        return $this->render('ImerirProduitBundle::ajoutReceptionCommande.html.twig',array('result_menu' => $menu_sous_menu,
            'liste_fournisseurs'=>$liste_fournisseurs,'liste_commandes'=>$liste_commandes,'nbLignes'=>0,
            'liste_lignes_commandes'=>$liste_lignes_commandes,'modif_date_commande'=>$modif_date_commande,'erreur'=>$erreur));
        ////////////////////////////////////////////////////////////

    }

    public function execSaisieReceptionAction(){

        /*
         * <input type="hidden" name="modif_commande_id_{{ i.commande_id }}" value="{{ i.commande_id }}"/>
                            <input type="hidden" name="modif_ligne_commande_id_{{ i.ligne_commande_id }}" value="{{ i.ligne_commande_id }}"/>
                            <input class="est_visible" type="hidden" name="modif_est_visible_{{ i.commande_id }}" value="1"/>
                            <input type="hidden" name="modif_article_{{ i.commande_id }}" value="{{ i.code_barre }}"/>
                                {{ i.code_barre }}
                            <input type="hidden" name="modif_quantite_souhaite_{{ i.commande_id }}" value="{{ i.quantite_souhaite }}"/>
                                {{ i.quantite_souhaite}}

                                <input type="number" name="quantite_recu">
         */
        //ajoutReceptionCommandeAction($commande_id, $article_code, $quantite, $date_reception)
        //PARTIE COMMUNE////////
        $soap = $this->get('noyau_soap');
        $query = $this->get('request');
        ///////////////////////
        $modif_commande_id = array();
        $modif_ligne_commande_id = array();
        $modif_article = array();
        $modif_quantite = array();
        $modif_date_reception = array();

        $erreur = '';

        foreach ($query->request as $key => $value) {
            if (substr($key, 0, strlen('modif_ligne_commande_id')) === 'modif_ligne_commande_id') {
                array_push($modif_ligne_commande_id, $value);
            }
            if (substr($key, 0, strlen('modif_commande_id')) === 'modif_commande_id') {
                array_push($modif_commande_id, $value);
            }
            if (substr($key, 0, strlen('modif_article')) === 'modif_article') {
                array_push($modif_article, $value);
            }
            if (substr($key, 0, strlen('quantite_ajoute')) === 'quantite_ajoute') {
                array_push($modif_quantite, $value);
            }
            if (substr($key, 0, strlen('date_reception')) === 'date_reception') {
                array_push($modif_date_reception, $value);
            }

        }

        //on teste si il y a des valeurs à ajouter
        if(!empty($modif_quantite) && !empty($modif_article) && !empty($modif_commande_id)){
            try {
                //ajoutReceptionCommandeAction($commande_id,$ligne_commande_id, $article_code, $quantite, $date_reception)
                $soap->call('ajoutReceptionCommande',array('commande_id'=>json_encode($modif_commande_id),
                    'ligne_commande_id'=>json_encode($modif_ligne_commande_id),
                    'article_code'=>json_encode($modif_article),'quantite'=>json_encode($modif_quantite),
                    'date_reception'=>json_encode($modif_date_reception)
                    ));
            }
            catch(\SoapFault $e){
                $erreur .=$e->getMessage();
            }
        }

        //PARTIE COMMUNE//////////////////////////////////////////
        try {
            $return_menu = $soap->call('getMenu', array());
            $menu_sous_menu = json_decode($return_menu);
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        try {
            $return = $soap->call('getFournisseurs', array('count' => 0, 'offset' => 0, 'nom' => '', 'email' => '',
                'telephone_portable' => '', 'reference_client' => '', 'notes' => ''));
            $liste_fournisseurs = json_decode($return);
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        try {
            $return_commandes = $soap->call('getCommandesFournisseurs', array('count' => 0, 'offset' => 0, 'fournisseur_id' => '',
                'fournisseur_nom' => '', 'commande_id' => '', 'article_code' => ''));
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        $liste_commandes = json_decode($return_commandes);
        return $this->render('ImerirProduitBundle::ajoutReceptionCommande.html.twig',array('result_menu' => $menu_sous_menu,
            'liste_fournisseurs'=>$liste_fournisseurs,'liste_commandes'=>$liste_commandes,'nbLignes'=>0,
            'commande_id'=>$modif_commande_id[0],'erreur'=>$erreur));
        ////////////////////////////////////////////////////////////

    }

    public function historiqueCommandeAction()
    {
        $soap = $this->get('noyau_soap');
        $query = $this->get('request');
        //PARTIE RECHERCHE
        /*
        Nom fournisseur :
        <input type="text" name="recherche_fournisseur_nom_fournisseur">
        Article :
        <input type="text" name="recherche_fournisseur_article">
        Numéro de commande :
        <input type="text" name="recherche_commande_fournisseur_id">
        */
        $recherche_nom = $query->request->get('recherche_commande_fournisseur_nom_fournisseur');
        $recherche_article = $query->request->get('recherche_fournisseur_article');
        $recherche_commande = $query->request->get('recherche_commande_fournisseur_id');
        $recherche_date_deb = $query->request->get('recherche_date_deb');
        $recherche_date_fin = $query->request->get('recherche_date_fin');

        $erreur = '';

        if(!empty($recherche_nom))
            $nom = $recherche_nom;
        else
            $nom = '';
        if(!empty($recherche_article))
            $article = $recherche_article;
        else
            $article = '';
        if(!empty($recherche_commande))
            $commande = $recherche_commande;
        else
            $commande = '';
        if(!empty($recherche_date_deb))
            $date_deb = $recherche_date_deb;
        else
            $date_deb = '';
        if(!empty($recherche_date_fin))
            $date_fin = $recherche_date_fin;
        else
            $date_fin = '';
        //////////////////

        try {
        	//on recupere le menu et sous menu
        	$return_menu = $soap->call('getMenu', array());
        	$menu_sous_menu = json_decode($return_menu);
        }
        catch(\SoapFault $e) {
        	$erreur.=$e->getMessage();
        }

        try {
            $return = $soap->call('getFournisseurs', array('count' => 0, 'offset' => 0, 'nom' => '', 'email' => '',
                'telephone_portable' => '', 'reference_client' => '', 'notes' => ''));
            $liste_fournisseurs = json_decode($return);
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        try {
            $return_commandes = $soap->call('getAllCommandesFournisseurs', array('count' => 0, 'offset' => 0, 'fournisseur_id' => '',
                'fournisseur_nom' => $nom, 'commande_id' => $commande, 'article_code' => $article,'date_deb'=>$date_deb,
                'date_fin'=>$date_fin));
        }
        catch(\SoapFault $e) {
            $erreur .=$e->getMessage();
        }

        $liste_commandes = json_decode($return_commandes);
        return $this->render('ImerirFournisseurBundle::historiqueCommandeFournisseur.html.twig',array('result_menu' => $menu_sous_menu,
            'liste_fournisseurs'=>$liste_fournisseurs,'liste_commandes'=>$liste_commandes,'nbLignes'=>0,'erreur'=>$erreur));
    }

}


text:
import copy
import json
import os

import pytest

from anchore_engine.analyzers.manager import apply_hints

# Used to determine which path in findings should be accessed
hint_file_pkg_type_map = {
    "alpine_hints.json": "pkgs.allinfo",
    "debian_hints.json": "pkgs.allinfo",
    "rpm_hints.json": "pkgs.allinfo",
    "gem_hints.json": "pkgs.gems",
    "java_hints.json": "pkgs.java",
    "npm_hints.json": "pkgs.npms",
    "python_hints.json": "pkgs.python",
}
distro_hint_files = ["alpine_hints.json", "debian_hints.json", "rpm_hints.json"]

class TestApplyHints:
    @pytest.fixture
    def log_to_stdout(self, monkeypatch):
        monkeypatch.setattr("anchore_engine.subsys.logger._log_to_stdout", True)

    @pytest.fixture
    def module_path(self, request):
        """
        Gets the path for current file
        """
        return os.path.dirname(request.module.__file__)

    @pytest.fixture
    def analyzer_report(self, module_path):
        """
        Reads and returns the analyzer report in this directory. Has every type of package in it
        """
        f = open(os.path.join(module_path, "analyzer_report.json"))
        return json.load(f)

    @pytest.fixture
    def hints_dirpath(self, module_path):
        """
        Directory path of hints files
        """
        return os.path.join(module_path, "mock_hints_files")

    @pytest.fixture
    def patch_hints_read(self, monkeypatch):
        """
        Factory that patches the function that reads from the hints file.
        Will change it to return the object passed to the factory
        """

        def _patch_read(hints):
            def _hints(**kwargs):
                return hints

            monkeypatch.setattr("anchore_engine.analyzers.utils.get_hintsfile", _hints)

        return _patch_read

    @pytest.fixture
    def get_hints(self, hints_dirpath):
        """
        Reads the hints file with name passed to function. Handles path to directory. All it needs is filename
        """

        def _get_hints(filename):
            f = open(os.path.join(hints_dirpath, filename))
            return json.load(f)

        return _get_hints

    @pytest.mark.parametrize("hints_filename", hint_file_pkg_type_map.keys())
    def test_hints_defines_path(self, hints_filename, patch_hints_read, get_hints):
        # There was a bug that was causing issues when syft did not process a certain type of artifact that was then
        # processed as a hint. Certain paths of nested attributes were being accessed without being defined
        # This test is designed to ensure that each handler can set the attributes it needs when hints are applied
        analyzer_report = {}
        pkg_type = hint_file_pkg_type_map[hints_filename]
        hints = get_hints(hints_filename)
        patch_hints_read(hints)

        apply_hints(analyzer_report, "")

        applied_hints = analyzer_report["package_list"][pkg_type]["base"]
        assert len(applied_hints) == len(hints["packages"])

        # if distro hints verify the package. Non distro types have more complicated key verification
        for pkg in hints["packages"]:
            if hints_filename in distro_hint_files:
                assert pkg["name"] in analyzer_report["package_list"][pkg_type]["base"]
            else:
                assert (
                    pkg["location"] in analyzer_report["package_list"][pkg_type]["base"]
                )

    def test_no_override_existing_entry(self, patch_hints_read, get_hints, caplog):
        # Hints should not overwrite any existing entries. This tests that it logs the issue and does not change it
        hints = get_hints("debian_hints.json")
        patch_hints_read(hints)

        analyzer_report = {
            "package_list": {
                "pkgs.allinfo": {
                    "base": {
                        "tzdata": {
                            "type": "dpkg",
                            "name": "tzdata",
                            "version": "test-no-override",
                            "origin": "",
                            "license": "",
                            "arch": "noarch",
                            "release": "N/A",
                            "sourcepkg": "tzdata-2021a-1.fc34",
                            "size": "0",
                        },
                    }
                }
            }
        }

        apply_hints(analyzer_report, "")

        assert "tzdata package already present under pkgs.allinfo" in caplog.text
        assert (
            analyzer_report["package_list"]["pkgs.allinfo"]["base"]["tzdata"]["version"]
            == "test-no-override"
        )

    @pytest.mark.parametrize("hints_filename", hint_file_pkg_type_map.keys())
    def test_merge(self, hints_filename, get_hints, analyzer_report, patch_hints_read):
        # Verifies that the merge works as intended and does not overwrite or remove existing entries in the report
        # Does this by using an analysis report with a single entry for each pkg type
        # Gets the before state, applies hints, and verifies that new data is present along with old
        hints = get_hints(hints_filename)
        patch_hints_read(hints)
        hints_pkg_type = hint_file_pkg_type_map[hints_filename]
        report_pre_hints = copy.deepcopy(analyzer_report)

        apply_hints(analyzer_report, "")

        # verify identical pkg types
        assert set(report_pre_hints["package_list"].keys()) == set(
            analyzer_report["package_list"].keys()
        )

        # loop over each package type to verify the content is as expected
        for pkg_type in report_pre_hints["package_list"].keys():
            pre_hints = report_pre_hints["package_list"][pkg_type]["base"]
            post_hints = analyzer_report["package_list"][pkg_type]["base"]

            # If the same type as the hints applied verify original data is present along with new
            if pkg_type == hints_pkg_type:
                assert len(post_hints) == len(pre_hints) + len(hints["packages"])
                for pkg_key in pre_hints.keys():
                    assert post_hints[pkg_key] == pre_hints[pkg_key]
            # else it should not have changed and should be an exact match
            else:
                assert pre_hints == post_hints


text:
 Improve this Doc

   View Source

$httpBackend

      - service in module ng

HTTP backend used by the service that delegates to
XMLHttpRequest object or JSONP and deals with browser incompatibilities.

You should never need to use this service directly, instead use the higher-level abstractions:
$http or $resource.

During testing this implementation is swapped with mock
$httpBackend which can be trained with responses.

Dependencies

$window

$document


text:
package org.apereo.cas.config;

import org.apereo.cas.authentication.surrogate.SurrogateLdapAuthenticationService;
import org.apereo.cas.authentication.surrogate.SurrogateAuthenticationService;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.configuration.model.support.surrogate.SurrogateAuthenticationProperties;

import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.util.LdapUtils;
import org.ldaptive.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link SurrogateLdapAuthenticationConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Configuration("surrogateLdapAuthenticationConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
public class SurrogateLdapAuthenticationConfiguration {
    private static final Logger LOGGER = LoggerFactory.getLogger(SurrogateLdapAuthenticationConfiguration.class);

    @Autowired
    @Qualifier("servicesManager")
    private ServicesManager servicesManager;

    @Autowired
    private CasConfigurationProperties casProperties;

    @RefreshScope
    @Bean
    public SurrogateAuthenticationService surrogateAuthenticationService() {
        final SurrogateAuthenticationProperties su = casProperties.getAuthn().getSurrogate();
        LOGGER.debug("Using LDAP [{}] with baseDn [{}] to locate surrogate accounts",
                su.getLdap().getLdapUrl(), su.getLdap().getBaseDn());
        final ConnectionFactory factory = LdapUtils.newLdaptivePooledConnectionFactory(su.getLdap());
        return new SurrogateLdapAuthenticationService(factory, su.getLdap(), servicesManager);
    }
}


text:
Before("@quicksight") do
  @service = Aws::QuickSight::Resource.new
  @client = @service.client
end

After("@quicksight") do
  # shared cleanup logic
end


text:
var _ = require('underscore');
var async = require('async');
var crypto = require('crypto');
var nodemailer = require('nodemailer');

var s = function(req, res) {
    return function(err, inst) {
        if (err) {
            res.send(err.message, 500);
        } else if (inst) {
            res.send(inst);
        } else {
            res.send(404);
        }
    };
};

module.exports = function(app) {

    var User = app.schema.models.User;
    var Authorship = app.schema.models.Authorship;
    var Readership = app.schema.models.Readership;

    function regUser (User) {
        return function(email, password, first, last, author, callback) {

            if (typeof password !== 'string' || ! password.trim().length) {
                return callback(new Error('you must specify a password'));
            }

            if (typeof email !== 'string' || ! email.trim().length) {
                return callback(new Error('you must specify an email'));
            }

            if (typeof first !== 'string' || ! first.trim().length) {
                return callback(new Error('you must specify an first name'));
            }

            if (typeof last !== 'string' || ! last.trim().length) {
                return callback(new Error('you must specify an last name'));
            }

            if (!email.match(/^[_a-z0-9\-]+(\.[_a-z0-9\-]+)*@[a-z0-9\-]+(\.[a-z0-9\-]+)*(\.[a-z]{2,4})$/)) {
                return callback(new Error('you must specify a proper email'));
            }

            var pass = crypto.createHash('sha256').update(password).digest('hex');

            async.waterfall([
                function getUser (callback) {
                    User.findOne({where: {email:email}}, callback);
                },
                function checkExistence (user, callback) {
                    if (user) {
                        callback(new Error('That account already exists!'));
                    } else {
                        User.create({email: email, password: pass, first: first, last: last, author: author}, callback);
                    }
                },
                function sendConfirmationEmail (user, callback) {

                    var verify = crypto.createHash('sha256').update(pass + email).digest('hex');
                    var Handlebars = require('handlebars');
                    var fs = require('fs');
                    var f = fs.readFileSync('server/views/emails/verify.html').toString();
                    var template = Handlebars.compile( f );
                    var message = template( {verify: verify, email: email} );
                    var htmlMessage = message;

                    // Prepare nodemailer transport object
                    var transport = nodemailer.createTransport("SMTP", {
                        service: "Gmail",
                        auth: {
                            user: "youremail@gmail.com",
                            pass: "youmustlovemath"
                        }
                    });

                    transport.sendMail({
                        from: 'Dan Lynch <mathapedia@gmail.com>',
                        to: email,
                        replyTo: ['noreply@mathapedia.com'],
                        subject: 'Activate your Mathapedia account!',
                        html: message,
                        text: message
                    }, function(err, responseStatus) {
                        if (err) {
                            console.log(err);
                            callback(new Error('badness'));
                        } else {
                            callback(null, 200);
                        }
                    });

                }
            ], callback);

        };
    }

    var Controller = {

        users: {

            LOGOUT: function (req, res) {

                delete req.session.user;
                res.send(200);

            },

            LOGIN: function(req, res) {

                var authenticateUser = function(email, password, callback) {

                    if (typeof password !== 'string' || ! password.trim().length) {
                        return callback(new Error('you must specify a password'));
                    }

                    if (typeof email !== 'string' || ! email.trim().length) {
                        return callback(new Error('you must specify an email'));
                    }

                    var pass = crypto.createHash('sha256').update(password).digest('hex');

                    async.waterfall([
                        function getUser (callback) {
                            User.findOne({where: {email:email}}, callback);
                        },
                        function checkExistence (user, callback) {
                            if (user) {
                                if (user.password === pass) {
                                    callback(null, user);
                                } else {
                                    callback(new Error('That password is incorrect.'));
                                }
                            } else {
                                callback(new Error('That account does not exist.'));
                            }
                        },
                        function verifiedOnly (user, callback) {
                            if (user.verified) {
                                user.updateAttribute('last_login', Date.now(), callback);
                            } else {
                                callback(new Error('That account is not activated.'));
                            }
                        }
                    ], callback);

                };

                authenticateUser(req.body.email, req.body.password, function (error, user) {
                    if (error) return res.send(404);

                    async.series({
                        write: function (callback) {
                            Authorship.all({where: {user_id: user.id}}, callback);
                        },
                        read: function (callback) {
                            Readership.all({where: {user_id: user.id}}, callback);
                        }

                    }, function(e,r) {

                        user.read = _.pluck(r.read, 'book_id');
                        user.write = _.pluck(r.write, 'book_id');

                        req.session.user = user;
                        res.send({status: 200});

                    });

                });

            },

            SIGNUP: function (req, res) {

                var registerUser = regUser(User);
                try {
                    if (req.body.author.match(/1/)) {
                        registerUser(req.body.email, req.body.password, req.body.first, req.body.last, 1, s(req, res));
                    } else {
                        registerUser(req.body.email, req.body.password, req.body.first, req.body.last, 0, s(req, res));
                    }
                } catch(e) {
                    res.send(400);
                }
            },

            ACTIVATE: function (req, res) {

                var verifyUser = function (email, key, callback) {

                    var opts = {
                        where: {
                            email: email
                        }
                    };

                    async.waterfall([

                        function queryUser (callback) {
                            User.findOne(opts, callback);
                        },
                        function checkUserExists (user, callback) {
                            if (user) {
                                if (user.verified) {
                                    callback(new Error('this user is already activated'));
                                } else {
                                    callback(null, user);
                                }
                            } else {
                                callback(new Error('no such user exists.'));
                            }
                        },
                        function verifyUser (user, callback) {
                            var verify = crypto.createHash('sha256').update(user.password + email).digest('hex');

                            var check = new RegExp('^' + verify + '$');
                            if (key.match(check)) {
                                user.updateAttribute('verified', true, callback);
                            } else {
                                callback(new Error('not verified'));
                            }
                        },
                        function sendOK (user, callback) {
                            callback(null, 'you have been verified');
                        }

                    ], callback);
                };

                verifyUser(req.params.email, req.params.key, s(req, res));

            }

        }
    };

    app.get('/logout', Controller.users.LOGOUT); // read
    app.post('/login', Controller.users.LOGIN); // read
    app.post('/signup', Controller.users.SIGNUP); // read
    app.get('/verify/:key/:email', Controller.users.ACTIVATE); // read

}


text:
module ChatbotHelper
  module Telegram
    # The document resource which represents a Telegram bot API document
    class Document < ChatbotHelper::Telegram::BaseResource
      class << self
        def required_fields
          %w[file_id]
        end

        def optional_fields
          %w[file_name mime_type file_size]
        end

        def optional_objects
          [
            { name: 'thumb', type: ChatbotHelper::Telegram::PhotoSize }
          ]
        end
      end
    end
  end
end