Map from a Google document to a Search Document

@param GoogleDocument $obj_source
@param Field[] $arr_expressions
@return Document
421921
public function fromGoogle(GoogleDocument $obj_source, array $arr_expressions = null)
    {
        $obj_schema = new Schema();
        $obj_doc = new Document($obj_schema);
        $obj_doc->setId($obj_source->getId());
        foreach($obj_source->getFieldList() as $obj_field) {
            /** @var Field $obj_field */
            $str_field_name = $obj_field->getName();
            $obj_value = $obj_field->getValue();
            if(ContentType::GEO === $obj_value->getType()) {
                $obj_schema->addGeopoint($str_field_name);
                $obj_geo = $obj_value->getGeo();
                $obj_doc->{$str_field_name} = [$obj_geo->getLat(), $obj_geo->getLng()];
            } else {
                if(isset(self::$arr_types_rev[$obj_value->getType()])) {
                    $obj_schema->addField($str_field_name, self::$arr_types_rev[$obj_value->getType()]);
                    $obj_doc->{$str_field_name} = $obj_value->getStringValue();
                } else {
                    throw new \InvalidArgumentException('Unknown type mapping from Google Document');
                }
            }
        }
        if(null !== $arr_expressions) {
            $this->mapExpressions($arr_expressions, $obj_doc);
        }
        return $obj_doc;
    }
1230601
public static function arrayToObjectDeeply($array,$obj,$classMap=[],$fieldAccess=true)
    {
        return self::_arrayToObjectDeeply($array, $obj,$classMap,$fieldAccess,"");
    }
909051
public function mapOneFromResult($obj_result)
    {
        // Key & Ancestry
        list($obj_gds_entity, $bol_schema_match) = $this->createEntityWithKey($obj_result);
        /** @var Entity $obj_gds_entity */

        // Properties
        if(isset($obj_result->entity->properties)) {
            $arr_property_definitions = $this->obj_schema->getProperties();
            foreach ($obj_result->entity->properties as $str_field => $obj_property) {
                if ($bol_schema_match && isset($arr_property_definitions[$str_field])) {
                    $obj_gds_entity->__set($str_field, $this->extractPropertyValue($arr_property_definitions[$str_field]['type'], $obj_property));
                } else {
                    $obj_gds_entity->__set($str_field, $this->extractPropertyValue(Schema::PROPERTY_DETECT, $obj_property));
                }
            }
        }

        // Done
        return $obj_gds_entity;
    }
741240
public static Collection map(Mapper mapper, Object[] arr) {
        return map(mapper, arr, false);
    }
264899
public static function map(array $arr, \Closure $callback){
		
		$ret = array();
		
		foreach($arr as $k => $v){
			$ret[$k] = $callback($v, $k);
		}
		
		return $ret;
		
	}
689070
public function match($document, $field, $operator, $value)
    {
        $d_value = $document->{$field};
        switch (true)
        {
            case ($operator === '=' && $d_value == $value):
                return true;
            case ($operator === '==' && $d_value == $value):
                return true;
            case ($operator === '===' && $d_value === $value):
                return true;
            case ($operator === '!=' && $d_value != $value):
                return true;
            case ($operator === '!==' && $d_value !== $value):
                return true;
            case (strtoupper($operator) === 'NOT' && $d_value != $value):
                return true;
            case ($operator === '>'  && $d_value >  $value):
                return true;
            case ($operator === '>=' && $d_value >= $value):
                return true;
            case ($operator === '<'  && $d_value <  $value):
                return true;
            case ($operator === '<=' && $d_value <= $value):
                return true;
            case (strtoupper($operator) === 'LIKE' && preg_match('/'.$value.'/is',$d_value)):
                return true;
            case (strtoupper($operator) === 'NOT LIKE' && !preg_match('/'.$value.'/is',$d_value)):
                return true;
            case (strtoupper($operator) === 'IN' && in_array($d_value, (array) $value)):
                return true;
            case (strtoupper($operator) === 'IN' && in_array($value, (array) $d_value)):
                return true;
            case (strtoupper($operator) === 'REGEX' && preg_match($value, $d_value)):
                return true;
            default:
                return false;
        }
    }
1240014
def parse(source, **kwargs):
    # type: (Union[Source, str], **Any) -> Document
    """"""
    options = {"no_location": False, "no_source": False}
    options.update(kwargs)

    if isinstance(source, string_types):
        source_obj = Source(source)  # type: Source
    else:
        source_obj = source  # type: ignore

    parser = Parser(source_obj, options)
    return parse_document(parser)
785625
function SourceMap(options) {
    options = defaults(options, {
        file : null,
        root : null,
        orig : null,

        orig_line_diff : 0,
        dest_line_diff : 0,
    });
    var generator = new MOZ_SourceMap.SourceMapGenerator({
        file       : options.file,
        sourceRoot : options.root
    });
    var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);

    if (orig_map && Array.isArray(options.orig.sources)) {
        orig_map._sources.toArray().forEach(function(source) {
            var sourceContent = orig_map.sourceContentFor(source, true);
            if (sourceContent) {
                generator.setSourceContent(source, sourceContent);
            }
        });
    }

    function add(source, gen_line, gen_col, orig_line, orig_col, name) {
        if (orig_map) {
            var info = orig_map.originalPositionFor({
                line: orig_line,
                column: orig_col
            });
            if (info.source === null) {
                return;
            }
            source = info.source;
            orig_line = info.line;
            orig_col = info.column;
            name = info.name || name;
        }
        generator.addMapping({
            generated : { line: gen_line + options.dest_line_diff, column: gen_col },
            original  : { line: orig_line + options.orig_line_diff, column: orig_col },
            source    : source,
            name      : name
        });
    };
    return {
        add        : add,
        get        : function() { return generator },
        toString   : function() { return JSON.stringify(generator.toJSON()); }
    };
}
592999
@Override
	public Object parse(String source) throws Exception {
		DocumentBuilder builder = builderFactory.newDocumentBuilder();
		InputSource is = new InputSource(new StringReader(source));
		Node node = builder.parse(is).getFirstChild();
		LinkedHashMap<String, Object> map = new LinkedHashMap<>();
		return copyChildren("xml", node, map);
	}
1333357
private function formatArrayField($arr, $pk = null)
    {
        $ret = [];
        foreach ($arr as $k => $v) {
            if ($pk !== null) {
                $k = $pk . $k;
            }
            if (is_array($v)) {
                $ret = array_merge($ret, $this->formatArrayField($v, $k . ']['));
            } else {
                $ret[$k] = $v;
            }
        }
        return $ret;
    }
1109262
private PBXObjectRef addDocumentationGroup(final Map objects, final String sourceTree) {
    final List productsList = new ArrayList();
    final PBXObjectRef products = createPBXGroup("Documentation", sourceTree, productsList);
    objects.put(products.getID(), products.getProperties());
    return products;
  }
690860
function(db) {

		function get_documents(data, config, plv8, ERROR, WARNING) {

			function get_document(id, fields) {
				fields = (fields || [{'query':'*'}]);

				var map = {};

				var obj = plv8.execute("SELECT "+fields.map(function(f, i) {
					var k;
					if(f.key) {
						k = 'p__' + i;
						map[k] = f;
						return f.query + ' AS ' + k;
					} else {
						return f.query;
					}
				}).join(', ')+" FROM documents WHERE id = $1 LIMIT 1", [id])[0];

				if(!obj) {
					return obj;
				}

				Object.keys(obj).forEach(function(key) {
					if(!map.hasOwnProperty(key)) {
						return;
					}

					var spec = map[key];
					if(!is_object(spec)) {
						return error('mapped resource missing');
					}
					if(!is_string(spec.key)) {
						return error('key missing');
					}
					var value = obj[key];
					delete obj[key];

					if(is_string(spec.datakey)) {
						if(!obj[spec.datakey]) {
							obj[spec.datakey] = {};
						}
						obj[spec.datakey][spec.key] = value;
					} else {
						obj[spec.key] = value;
					}
				});

				return obj;
			}

			//function get_type(id) {
			//	return plv8.execute("SELECT * FROM types WHERE id = $1 LIMIT 1", [id])[0];
			//}

			function error(msg) {
				plv8.elog(ERROR, msg);
			}

			function warn(msg) {
				plv8.elog(WARNING, msg);
			}

			function is_object(a) {
				return a && (typeof a === 'object');
			}

			function is_array(a) {
				return a && (a instanceof Array);
			}

			function is_string(a) {
				return a && (typeof a === 'string');
			}

			function is_uuid(obj) {
				return /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/.test(obj);
			}

			function get_property_step(last, current) {
				return is_object(last) ? last[current] : undefined;
			}

			/** Get value of property from provided object using a path.
			 * @param obj {object} The object from where to find the value.
			 * @param path {string} The path to the value in object.
			 * @returns {mixed} The value from the object at the end of path or `undefined` if any part is missing.
			 */
			function get_property(obj, path) {
				if(!is_object(obj)) { return error('get_property(obj, ...) not object: '+ obj); }
				if(!is_string(path)) { return error('get_property(..., path) not string: '+ path); }
				return path.split('.').reduce(get_property_step, obj);
			}

			/** Get document by UUID */
			function fetch_object_by_uuid(data, prop, fields, uuid) {
				if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
				if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
				if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); }
				if(data.documents[uuid] === undefined) {
					data.documents[uuid] = get_document(uuid, fields);
				} else {
					return warn('Document already fetched: ' + uuid);
				}
			}

			/* */
			function fetch_object(data, config) {
				var prop, fields;

				if(is_object(config)) {
					prop = config.prop;
					fields = config.fields;
				} else if(is_string(config)) {
					prop = config;
				}

				if(!is_string(prop)) {
					return error('property is not valid: ' + prop);
				}

				fields = fields ? fields : [{'query':'*'}];

				if(!is_array(fields)) {
					return error('fields are not valid: ' + fields);
				}

				var uuid = get_property(data, prop);

				if(is_array(uuid)) {
					// FIXME: This could be implemented with one query
					return uuid.forEach(fetch_object_by_uuid.bind(undefined, data, prop, fields));
				}
				return fetch_object_by_uuid(data, prop, fields, uuid);
			}

			// Check for bad input

			if(!is_object(data)) { return error("get_documents(data, ...) not object"); }
			if(!is_array(config)) { return error("get_documents(..., config) not array"); }

			//var types_id = data.types_id;
			//if(!is_uuid(types_id)) { return error("data.types_id not valid UUID: " + types_id); }

			// Get document type
			//var type = get_type(types_id);
			//if(!is_object(type)) { return error("type not valid object: " + type); }

			//var relations = type.relations || {};
			//if(!is_object(relations)) { return error("type.relations not valid object: " + relations); }

			// Populate documents from `config`
			data.documents = {};
			config.forEach( fetch_object.bind(undefined, data) );
			return data.documents;
		}

		return db.query('CREATE OR REPLACE FUNCTION get_documents(data json, config json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(get_documents, ["data", "config", "plv8", "ERROR", "WARNING"]));
	}
122361
private String[] getSourceLines(Method obj) {

        if (srcInited) {
            return sourceLines;
        }

        try {
            srcLineAnnotation = SourceLineAnnotation.forEntireMethod(getClassContext().getJavaClass(), obj);
            if (srcLineAnnotation != null) {
                SourceFinder sourceFinder = AnalysisContext.currentAnalysisContext().getSourceFinder();
                SourceFile sourceFile = sourceFinder.findSourceFile(srcLineAnnotation.getPackageName(), srcLineAnnotation.getSourceFile());
                try (BufferedReader sourceReader = new BufferedReader(new InputStreamReader(sourceFile.getInputStream(), StandardCharsets.UTF_8))) {

                    List<String> lines = new ArrayList<>(100);
                    String line;
                    while ((line = sourceReader.readLine()) != null) {
                        lines.add(line);
                    }
                    sourceLines = lines.toArray(new String[0]);
                }
            }
        } catch (IOException ioe) {
            // noop
        }

        srcInited = true;
        return sourceLines;
    }
294484
function findDataSources(connections, dataSources, cb) {
  //Just Want The Data Source IDs.
  logger.debug("findDataSources", {dataSources: dataSources});
  var dataSourceIDsToUpdate = _.map(dataSources, function(dataSourceUpdateData) {
    return dataSourceUpdateData.error ? null : dataSourceUpdateData._id;
  });

  dataSourceIDsToUpdate = _.compact(dataSourceIDsToUpdate);

  //No Valid Data Sources To Update. No Need To Search For Data Sources
  if (dataSourceIDsToUpdate.length === 0) {
    return cb(undefined, dataSourceIDsToUpdate);
  }

  var query = {

  };

  //Searching By ID. Just one mongo call to get them all. More Efficient
  query[CONSTANTS.DATA_SOURCE_ID] = {
    "$in": dataSourceIDsToUpdate
  };

  lookUpDataSources(connections, {
    query: query
  }, function(err, foundDataSources) {
    if (err) {
      logger.error("Error Finding Data Sources ", {error: err});
      return cb(buildErrorResponse({
        error: err,
        userDetail: "Unexpected Error When Searching For A Data Source",
        code: ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR
      }));
    }

    //Map Found Data Source Documents
    var dsWithDocuments = _.map(dataSources, function(validDataSource) {
      var matchingDocument = _.find(foundDataSources, function(dataSourceDocument) {
        return _.isEqual(dataSourceDocument._id.toString(), validDataSource._id.toString());
      });

      //If the document is found, assign it to the object, if not, set an error
      if (matchingDocument) {
        validDataSource.document = matchingDocument;
      } else {
        validDataSource.error = buildErrorResponse({
          error: new Error("Data Source Not Found"),
          userDetail: "Data Source Not Found",
          code: ERROR_CODES.FH_FORMS_NOT_FOUND
        });
      }

      return validDataSource;
    });

    var validInvalidDataSources = updateValidAndInvalidDataSources(dsWithDocuments, []);

    logger.debug("findDataSources", {validInvalidDataSources: validInvalidDataSources});

    cb(undefined, validInvalidDataSources.valid, validInvalidDataSources.invalid);
  });
}
1300482
public static Object[] appendArray(Object[] arr, Object obj) {
		Object[] newArr = new Object[arr.length + 1];
		System.arraycopy(arr, 0, newArr, 0, arr.length);
		newArr[arr.length] = obj;
		return newArr;
	}
985156
public function fromArray($arr)
    {
        $class = $this->getFullyQualifiedModel();
        foreach ($arr as $element) {
            /** @var $obj ActiveRecordInterface */
            $obj = new $class();
            $obj->fromArray($element);
            $this->append($obj);
        }
    }
823343
public function search(Query $obj_query)
    {
        $obj_request = new SearchRequest();
        $obj_params = $this->prepareRequestParams($obj_request);

        // Basics
        $obj_params
            ->setQuery($obj_query->getQuery())
            ->setLimit($obj_query->getLimit())
            ->setOffset($obj_query->getOffset())
        ;

        // Sorting
        $arr_sorts = $obj_query->getSorts();
        if(null !== $arr_sorts && count($arr_sorts) > 0) {
            foreach ($arr_sorts as $arr_sort) {
                $obj_sort = $obj_params->addSortSpec();
                $obj_sort->setSortExpression($arr_sort[0]);
                $obj_sort->setSortDescending(Query::DESC === $arr_sort[1]);
            }
        }

        // Match Scoring
        if(Query::SCORE_REGULAR === $obj_query->getScorer()) {
            $obj_params->mutableScorerSpec()->setScorer(Scorer::MATCH_SCORER)->setLimit($obj_query->getLimit());
        } elseif (Query::SCORE_RESCORING === $obj_query->getScorer()) {
            $obj_params->mutableScorerSpec()->setScorer(Scorer::RESCORING_MATCH_SCORER)->setLimit($obj_query->getLimit());
        }

        // Return Fields
        $arr_return_fields = $obj_query->getReturnFields();
        if(null !== $arr_return_fields && count($arr_return_fields) > 0) {
            $obj_fields = $obj_params->mutableFieldSpec();
            foreach ($arr_return_fields as $str_field) {
                $obj_fields->addName($str_field);
            }
        }

        // Return Expressions
        $arr_return_exps = $obj_query->getReturnExpressions();
        if(null !== $arr_return_exps && count($arr_return_exps) > 0) {
            $obj_fields = $obj_params->mutableFieldSpec();
            foreach ($arr_return_exps as $arr_exp) {
                $obj_fields->addExpression()->setName($arr_exp[0])->setExpression($arr_exp[1]);
            }
        }

        // Facets
        $arr_facets = $obj_query->getFacets();
        if(null !== $arr_facets) {
            if(count($arr_facets) > 0) {
                // We want a specific set of facets in the response
                foreach($arr_facets as $str_facet) {
                    $obj_params->addIncludeFacet()->setName($str_facet);
                }
            } else {
                // We want all facets back...
                $obj_params->setAutoDiscoverFacetCount(100);
            }
        }

        $this->execute('Search', $obj_request, new SearchResponse());
        return $this->processSearchResponse();
    }