accesses mongodb and return a cart spec stored there
176844
def download_cart(cart_name, env):
    
    cart_con = cart_db()
    carts = cart_con[env]

    return carts.find_one({'_id': cart_name})
1274594
function specs() {
    var routes = {};

    // Reducing the app's recursive stack
    function reduceStack(path, items, item) {
      var nextPath;

      if (item.handle && item.handle.stack) {
        nextPath = join(path, (item.path || helpers.unescapeRegex(item.regexp) || ''));
        return items.concat(item.handle.stack.reduce(reduceStack.bind(null, nextPath), []));
      }

      if (item.route) {
        nextPath = join(path, (item.route.path || ''));
        return items.concat(item.route.stack.reduce(reduceStack.bind(null, nextPath), []));
      }

      return items.concat({
        handle: item.handle,
        path: path
      });
    }

    // Filtering the actions coming from dolman
    app._router.stack
      .reduce(reduceStack.bind(null, ''), [])
      .map(function(item) {
        return {
          route: routesMap.get(item.handle),
          path: item.path
        };
      })
      .filter(function(item) {
        return item.route && item.route.name;
      })
      .forEach(function(item) {
        var route = item.route,
            method = [].concat(route.method || route.methods)[0];

        var routeData = {
          path: item.path,
          name: route.name,
          method: !method || method === 'ALL' ? 'GET' : method
        };

        ['description'].forEach(function(k) {
          if (route[k])
            routeData[k] = route[k];
        });

        routes[route.name] = routeData;
      });

    return {
      formats: ['json'],
      methods: routes
    };
  }
804138
def fetch_or_load(spec_path):
    

    headers = {}

    try:
        modified = datetime.utcfromtimestamp(os.path.getmtime(spec_path))
        date = modified.strftime("%a, %d %b %Y %I:%M:%S UTC")
        headers["If-Modified-Since"] = date
    except OSError as error:
        if error.errno != errno.ENOENT:
            raise

    request = urllib.Request(VALIDATION_SPEC, headers=headers)
    response = urllib.urlopen(request, cafile=certifi.where())

    if response.code == 200:
        with open(spec_path, "w+b") as spec:
            spec.writelines(response)
            spec.seek(0)
            return html.parse(spec)

    with open(spec_path) as spec:
        return html.parse(spec)
704699
def lookup
      request_params = {
        'customerID' => customer_id,
        'cartID' => cart_id,
        'cartItems' => { 'CartItem' => cart_items.map(&:to_hash) },
        'origin' => origin.to_hash,
        'destination' => destination.to_hash
      }

      response = TaxCloud.client.request :lookup, request_params
      TaxCloud::Responses::Lookup.parse response
    end
431658
def fetch(self, spec=None, *args, **kwargs):
        
        if spec is None:
            spec = {}
        for key in self.structure:
            if key in spec:
                if isinstance(spec[key], dict):
                    spec[key].update({'$exists': True})
            else:
                spec[key] = {'$exists': True}
        return self.find(spec, *args, **kwargs)
583847
function map(d) {
      if (isModel(d)) return pluck(d.attributes);

      for (var key in d) {
        if (isCollection(d[key])) {
          d[key] = pluck(d[key].models);
        }

        if (isModel(d[key])) {
          //
          // Delete MongoDB ObjectIDs. The stored state of the model is ambigious
          // as the referenced model could have different values in its own
          // collection. Hence doing recursive storage should be limited as much
          // as possible, since duplicate data will be stored.
          //
          d[key] = pluck(d[key].attributes);
          delete d[key]._id;
        }
      }

      return d;
    }
1265338
def get_collection(self, collection_id):
        """"""
        sql = """SELECT collection.collection_id, collection.type,
                        collection.name, collection.path,
                        collection.doc,
                        collection.version, collection.scope,
                        collection.namedargs,
                        collection.doc_format
                 FROM collection_table as collection
                 WHERE collection_id == ? OR collection.name like ?
        """
        cursor = self._execute(sql, (collection_id, collection_id))
        # need to handle the case where we get more than one result...
        sql_result = cursor.fetchone()
        return {
            "collection_id": sql_result[0],
            "type": sql_result[1],
            "name": sql_result[2],
            "path": sql_result[3],
            "doc":  sql_result[4],
            "version": sql_result[5],
            "scope":   sql_result[6],
            "namedargs": sql_result[7],
            "doc_format": sql_result[8]
        }
        return sql_result
1127516
def params_to_mongo(query_params):
    
    if not query_params:
        return {}
    for key, value in query_params.items():
        if isinstance(value, list):
            query_params[key] = {'$in': value}
    return query_params
697641
function Inspection(schema, custom) {
		var _stack = ['@'];

		this._schema = schema;
		this._custom = {};
		if (custom != null) {
			for (var key in custom) {
				if (custom.hasOwnProperty(key)){
					this._custom['$' + key] = custom[key];
				}
			}
		}

		this._getDepth = function () {
			return _stack.length;
		};

		this._dumpStack = function () {
			return _stack.map(function (i) {return i.replace(/^\[/g, '\u001b\u001c\u001d\u001e');})
			.join('.').replace(/\.\u001b\u001c\u001d\u001e/g, '[');
		};

		this._deeperObject = function (name) {
			_stack.push((/^[a-z$_][a-z0-9$_]*$/i).test(name) ? name : '["' + name + '"]');
			return this;
		};

		this._deeperArray = function (i) {
			_stack.push('[' + i + ']');
			return this;
		};

		this._back = function () {
			_stack.pop();
			return this;
		};
	}
672691
def create_mongo_db(database_name, collection_name, initial_document):
    """"""
    response_dict = {}
    try:
        mongodb_client_url = getattr(settings, 'MONGODB_CLIENT',
                                 'mongodb://localhost:27017/')
        mc = MongoClient(mongodb_client_url,document_class=OrderedDict)

        db = mc[str(database_name)]
        collection = db[str(collection_name)]

        d = json.loads(initial_document, object_pairs_hook=OrderedDict)

        collection.save(d)

    except:
        # error connecting to mongodb
        response_dict['error'] = str(sys.exc_info())

    return response_dict
549308
function readDB(path)
{
    return fetch(path)
        .then((data) => data.json())
        .catch((err) =>
        {
            const error = new Error(`Failed to fetch '${ path }'.`);
            error.innerException = err;
            error.code = 'ERR_FETCH';

            console.error(err);
            throw error;
        });
}
1219979
def cart_get(self, CartId=None, HMAC=None, **kwargs):
        
        if not CartId or not HMAC:
            raise CartException('CartId required for CartGet call')
        response = self.api.CartGet(CartId=CartId, HMAC=HMAC, **kwargs)
        root = objectify.fromstring(response)

        cart = AmazonCart(root)
        self._check_for_cart_error(cart)

        return cart
903550
def _get_mapreduce_spec(cls, mr_id):
    """"""
    key = 'GAE-MR-spec: %s' % mr_id
    spec_json = memcache.get(key)
    if spec_json:
      return cls.from_json(spec_json)
    state = MapreduceState.get_by_job_id(mr_id)
    spec = state.mapreduce_spec
    spec_json = spec.to_json()
    memcache.set(key, spec_json)
    return spec
1187429
function getHasManyName(hasMany) {
    var as, tableName;

    if (hasMany.through() !== undefined) {
        as = getBelongsToManyName(hasMany); //inflection.pluralize(getBelongsToName(hasMany.throughForeignKeyConstraint()));
    } else {
        as          = inflection.pluralize(hasMany.name());                  // cart_cart_line_items
        tableName   = hasMany.table().name();
        if (getSpecificConfig(tableName, 'generate.stripFirstTableFromHasMany')) {
            as = as.replace(new RegExp('^' + tableName + '[_-]?', 'i'), '');     // cart_cart_line_items -> cart_line_items
        }
        if (getSpecificConfig(tableName, 'generate.relationAccessorCamelCase')) {
            as = inflection.camelize(inflection.underscore(as), true);           // cart_line_items -> cartLineItems
        }
    }

    return as;
}
153891
function retrieveEJSON() {
  let EJSON = null;
  try {
    EJSON = requireOptional('mongodb-extjson');
  } catch (error) {} // eslint-disable-line
  if (!EJSON) {
    EJSON = {
      parse: noEJSONError,
      deserialize: noEJSONError,
      serialize: noEJSONError,
      stringify: noEJSONError,
      setBSONModule: noEJSONError,
      BSON: noEJSONError
    };
  }

  return EJSON;
}
602122
def get_mongo_query_from_arguments(self, reserved_attributes=[]):
        

        query = {}
        for arg in self.request.arguments:
            if arg not in reserved_attributes:
                if len(self.request.arguments.get(arg)) > 1:
                    query["$or"] = []
                    for val in self.request.arguments.get(arg):
                        query["$or"].append({arg: self.get_arg_value_as_type(val)})
                else:
                    query[arg] = self.get_arg_value_as_type(self.request.arguments.get(arg)[0])

        return query
603703
def get_registry(entry, runtime):
    """"""
    try:
        records_location_param_id = Id('parameter:recordsRegistry@mongo')
        registry = runtime.get_configuration().get_value_by_parameter(
            records_location_param_id).get_string_value()
        return import_module(registry).__dict__.get(entry, {})
    except (ImportError, AttributeError, KeyError, NotFound):
        return {}