text:
/**
 * --------------------------------------------------------------------------
 * Bootstrap (v5.2.3): index.umd.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 * --------------------------------------------------------------------------
 */

import Alert from './src/alert.js'
import Button from './src/button.js'
import Carousel from './src/carousel.js'
import Collapse from './src/collapse.js'
import Dropdown from './src/dropdown.js'
import Modal from './src/modal.js'
import Offcanvas from './src/offcanvas.js'
import Popover from './src/popover.js'
import ScrollSpy from './src/scrollspy.js'
import Tab from './src/tab.js'
import Toast from './src/toast.js'
import Tooltip from './src/tooltip.js'

export default {
  Alert,
  Button,
  Carousel,
  Collapse,
  Dropdown,
  Modal,
  Offcanvas,
  Popover,
  ScrollSpy,
  Tab,
  Toast,
  Tooltip
}


text:
function calculate(){
    var age = 26;
    var oldAge = 96;
    var perDay = 2;

    var days = (oldAge - age) * 356;
    var total = perDay * days;
    if(total > 40000){
        alert("You will need " + total + " to last you until the ripe old age of " + oldAge + ". Wow! That's a lot!");
    }else{
        alert("You will need " + total + " to last you until the ripe old age of " + oldAge + ". You seem pretty reasonable");
    }
}

redpajama_set_name: RedPajamaGithub


text:
**Namespace:** [OfficeDevPnP.Core.UPAWebService](OfficeDevPnP.Core.UPAWebService.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public virtual void EndInvoke(IAsyncResult result)
```
### Parameters
#### result
  Type: System.IAsyncResult

### Return Value
Type: void

## See also
- [GetUserColleaguesCompletedEventHandler](OfficeDevPnP.Core.UPAWebService.GetUserColleaguesCompletedEventHandler.md)
- [OfficeDevPnP.Core.UPAWebService](OfficeDevPnP.Core.UPAWebService.md)


text:
WITH RECURSIVE fc(food_code) AS (
    SELECT code FROM foods AS food_code
), t(food_code, code, level) AS (
  (SELECT food_code, category_code as code, 0 as level FROM foods_categories WHERE food_code IN (SELECT food_code FROM fc) ORDER BY code)
  UNION
  (SELECT food_code, category_code as code, level + 1 as level FROM t JOIN categories_categories ON subcategory_code = code ORDER BY code)
), u AS (
  (SELECT food_code, same_as_before_option, ready_meal_option, reasonable_amount, use_in_recipes, food_code as code FROM foods_attributes WHERE food_code IN (SELECT food_code FROM fc))
  UNION ALL
  (SELECT food_code, same_as_before_option, ready_meal_option, reasonable_amount, use_in_recipes, category_code as code FROM categories_attributes JOIN t ON code = category_code ORDER BY level)
  UNION ALL
  (SELECT food_code, same_as_before_option, ready_meal_option, reasonable_amount, use_in_recipes, NULL as code FROM attribute_defaults CROSS JOIN fc)
)
SELECT food_code,
  (array_agg(same_as_before_option ORDER BY same_as_before_option IS NULL))[1] AS same_as_before_option,
  (array_agg(ready_meal_option ORDER BY ready_meal_option IS NULL))[1] AS ready_meal_option,
  (array_agg(reasonable_amount ORDER BY reasonable_amount IS NULL))[1] AS reasonable_amount,
  (array_agg(use_in_recipes ORDER BY use_in_recipes IS NULL))[1] AS use_in_recipes
FROM u
GROUP BY food_code
ORDER BY food_code


text:
package ru.spoddubnyak.model;

import java.util.Set;
import java.util.TreeSet;

/**
 * Class BookOrder to store the all orders after removal.
 *
 * @author Sergei Poddubnyak (forvvard09@gmail.com)
 * @version 1.0
 * @since 03.02.2018
 */
public class BookOrder {
    /**
     * property save order with operation buy.
     */
    private Set<Order> buyTree;
    /**
     * property save order with operation sell.
     */
    private Set<Order> sellTree;

    /**
     * Constructor it creates a new object BookOrder container with the specified values and sorting by comporator compUp.
     */
    public BookOrder() {
        CompPriceUp compUp = new CompPriceUp();
        this.buyTree = new TreeSet(compUp);
        this.sellTree = new TreeSet(compUp).descendingSet();
    }

    /**
     * Getter for property BueTree.
     *
     * @return link property BueTree
     */
    public Set<Order> getBuyTree() {
        return this.buyTree;
    }

    /**
     * getter for property SellTree.
     *
     * @return link property SellTree
     */
    public Set<Order> getSellTree() {
        return this.sellTree;
    }

    /**
     * Method add order in object BookOrder, depending on the operation of Order operation.
     *
     * @param order order for adding
     */
    public void addOrder(Order order) {
        if (order.getOperation().equals(XMLAttributes.OPERATION_SELL.getAtributes())) {
            this.sellTree.add(generationNewOrder(order));
        } else if (order.getOperation().equals(XMLAttributes.OPERATION_BUY.getAtributes())) {
            this.buyTree.add(generationNewOrder(order));
        }
    }

    /**
     * Method generate new Order.
     *
     * @param order for create new order's
     * @return new order by specification
     */
    private Order generationNewOrder(Order order) {
        int orderId = order.getOrderId();
        double price = order.getPrice();
        int volume = order.getVolume();
        Order newOrder = new Order(orderId, price, volume);
        return newOrder;
    }
}


text:
  <ng-container *ngSwitchCase="'number'" [ngSwitch]="!!(iconOverrides && iconOverrides.number)">
    <ng-container
      *ngSwitchCase="true"
      [ngTemplateOutlet]="iconOverrides.number"
      [ngTemplateOutletContext]="_getIconContext()"></ng-container>
    {{index + 1}}
  </ng-container>

  <ng-container *ngSwitchCase="'edit'" [ngSwitch]="!!(iconOverrides && iconOverrides.edit)">
    <ng-container
      *ngSwitchCase="true"
      [ngTemplateOutlet]="iconOverrides.edit"
      [ngTemplateOutletContext]="_getIconContext()"></ng-container>
    <mat-icon *ngSwitchDefault>create</mat-icon>
  </ng-container>

  <ng-container *ngSwitchCase="'done'" [ngSwitch]="!!(iconOverrides && iconOverrides.done)">
    <ng-container
      *ngSwitchCase="true"
      [ngTemplateOutlet]="iconOverrides.done"
      [ngTemplateOutletContext]="_getIconContext()"></ng-container>
    <mat-icon *ngSwitchDefault>done</mat-icon>
  </ng-container>

  <ng-container *ngIf="_templateLabel()" [ngTemplateOutlet]="_templateLabel()!.template">
  </ng-container>

{{label}}

{{_intl.optionalLabel}}


text:
from __future__ import absolute_import, unicode_literals

import os

from django.core.urlresolvers import NoReverseMatch, reverse
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.translation import ugettext as _
from django.views.decorators.vary import vary_on_headers

from wagtail.utils.pagination import paginate
from wagtail.wagtailadmin import messages
from wagtail.wagtailadmin.forms import SearchForm
from wagtail.wagtailadmin.utils import (
    PermissionPolicyChecker, permission_denied, popular_tags_for_model)
from wagtail.wagtailcore.models import Collection, Site
from wagtail.wagtailimages import get_image_model
from wagtail.wagtailimages.exceptions import InvalidFilterSpecError
from wagtail.wagtailimages.forms import URLGeneratorForm, get_image_form
from wagtail.wagtailimages.models import Filter
from wagtail.wagtailimages.permissions import permission_policy
from wagtail.wagtailimages.views.serve import generate_signature
from wagtail.wagtailsearch import index as search_index

permission_checker = PermissionPolicyChecker(permission_policy)

@permission_checker.require_any('add', 'change', 'delete')
@vary_on_headers('X-Requested-With')
def index(request):
    Image = get_image_model()

    # Get images (filtered by user permission)
    images = permission_policy.instances_user_has_any_permission_for(
        request.user, ['change', 'delete']
    ).order_by('-created_at')

    # Search
    query_string = None
    if 'q' in request.GET:
        form = SearchForm(request.GET, placeholder=_("Search images"))
        if form.is_valid():
            query_string = form.cleaned_data['q']

            images = images.search(query_string)
    else:
        form = SearchForm(placeholder=_("Search images"))

    # Filter by collection
    current_collection = None
    collection_id = request.GET.get('collection_id')
    if collection_id:
        try:
            current_collection = Collection.objects.get(id=collection_id)
            images = images.filter(collection=current_collection)
        except (ValueError, Collection.DoesNotExist):
            pass

    paginator, images = paginate(request, images)

    collections = permission_policy.collections_user_has_any_permission_for(
        request.user, ['add', 'change']
    )
    if len(collections) < 2:
        collections = None

    # Create response
    if request.is_ajax():
        return render(request, 'wagtailimages/images/results.html', {
            'images': images,
            'query_string': query_string,
            'is_searching': bool(query_string),
        })
    else:
        return render(request, 'wagtailimages/images/index.html', {
            'images': images,
            'query_string': query_string,
            'is_searching': bool(query_string),

            'search_form': form,
            'popular_tags': popular_tags_for_model(Image),
            'collections': collections,
            'current_collection': current_collection,
            'user_can_add': permission_policy.user_has_permission(request.user, 'add'),
        })

@permission_checker.require('change')
def edit(request, image_id):
    Image = get_image_model()
    ImageForm = get_image_form(Image)

    image = get_object_or_404(Image, id=image_id)

    if not permission_policy.user_has_permission_for_instance(request.user, 'change', image):
        return permission_denied(request)

    if request.method == 'POST':
        original_file = image.file
        form = ImageForm(request.POST, request.FILES, instance=image, user=request.user)
        if form.is_valid():
            if 'file' in form.changed_data:
                # if providing a new image file, delete the old one and all renditions.
                # NB Doing this via original_file.delete() clears the file field,
                # which definitely isn't what we want...
                original_file.storage.delete(original_file.name)
                image.renditions.all().delete()

                # Set new image file size
                image.file_size = image.file.size

            form.save()

            # Reindex the image to make sure all tags are indexed
            search_index.insert_or_update_object(image)

            messages.success(request, _("Image '{0}' updated.").format(image.title), buttons=[
                messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit again'))
            ])
            return redirect('wagtailimages:index')
        else:
            messages.error(request, _("The image could not be saved due to errors."))
    else:
        form = ImageForm(instance=image, user=request.user)

    # Check if we should enable the frontend url generator
    try:
        reverse('wagtailimages_serve', args=('foo', '1', 'bar'))
        url_generator_enabled = True
    except NoReverseMatch:
        url_generator_enabled = False

    if image.is_stored_locally():
        # Give error if image file doesn't exist
        if not os.path.isfile(image.file.path):
            messages.error(request, _(
                "The source image file could not be found. Please change the source or delete the image."
            ).format(image.title), buttons=[
                messages.button(reverse('wagtailimages:delete', args=(image.id,)), _('Delete'))
            ])

    return render(request, "wagtailimages/images/edit.html", {
        'image': image,
        'form': form,
        'url_generator_enabled': url_generator_enabled,
        'filesize': image.get_file_size(),
        'user_can_delete': permission_policy.user_has_permission_for_instance(
            request.user, 'delete', image
        ),
    })

def url_generator(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    if not permission_policy.user_has_permission_for_instance(request.user, 'change', image):
        return permission_denied(request)

    form = URLGeneratorForm(initial={
        'filter_method': 'original',
        'width': image.width,
        'height': image.height,
    })

    return render(request, "wagtailimages/images/url_generator.html", {
        'image': image,
        'form': form,
    })

def generate_url(request, image_id, filter_spec):
    # Get the image
    Image = get_image_model()
    try:
        image = Image.objects.get(id=image_id)
    except Image.DoesNotExist:
        return JsonResponse({
            'error': "Cannot find image."
        }, status=404)

    # Check if this user has edit permission on this image
    if not permission_policy.user_has_permission_for_instance(request.user, 'change', image):
        return JsonResponse({
            'error': "You do not have permission to generate a URL for this image."
        }, status=403)

    # Parse the filter spec to make sure its valid
    try:
        Filter(spec=filter_spec).operations
    except InvalidFilterSpecError:
        return JsonResponse({
            'error': "Invalid filter spec."
        }, status=400)

    # Generate url
    signature = generate_signature(image_id, filter_spec)
    url = reverse('wagtailimages_serve', args=(signature, image_id, filter_spec))

    # Get site root url
    try:
        site_root_url = Site.objects.get(is_default_site=True).root_url
    except Site.DoesNotExist:
        site_root_url = Site.objects.first().root_url

    # Generate preview url
    preview_url = reverse('wagtailimages:preview', args=(image_id, filter_spec))

    return JsonResponse({'url': site_root_url + url, 'preview_url': preview_url}, status=200)

def preview(request, image_id, filter_spec):
    image = get_object_or_404(get_image_model(), id=image_id)

    try:
        response = HttpResponse()
        image = Filter(spec=filter_spec).run(image, response)
        response['Content-Type'] = 'image/' + image.format_name
        return response
    except InvalidFilterSpecError:
        return HttpResponse("Invalid filter spec: " + filter_spec, content_type='text/plain', status=400)

@permission_checker.require('delete')
def delete(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    if not permission_policy.user_has_permission_for_instance(request.user, 'delete', image):
        return permission_denied(request)

    if request.method == 'POST':
        image.delete()
        messages.success(request, _("Image '{0}' deleted.").format(image.title))
        return redirect('wagtailimages:index')

    return render(request, "wagtailimages/images/confirm_delete.html", {
        'image': image,
    })

@permission_checker.require('add')
def add(request):
    ImageModel = get_image_model()
    ImageForm = get_image_form(ImageModel)

    if request.method == 'POST':
        image = ImageModel(uploaded_by_user=request.user)
        form = ImageForm(request.POST, request.FILES, instance=image, user=request.user)
        if form.is_valid():
            # Set image file size
            image.file_size = image.file.size

            form.save()

            # Reindex the image to make sure all tags are indexed
            search_index.insert_or_update_object(image)

            messages.success(request, _("Image '{0}' added.").format(image.title), buttons=[
                messages.button(reverse('wagtailimages:edit', args=(image.id,)), _('Edit'))
            ])
            return redirect('wagtailimages:index')
        else:
            messages.error(request, _("The image could not be created due to errors."))
    else:
        form = ImageForm(user=request.user)

    return render(request, "wagtailimages/images/add.html", {
        'form': form,
    })

def usage(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    paginator, used_by = paginate(request, image.get_usage())

    return render(request, "wagtailimages/images/usage.html", {
        'image': image,
        'used_by': used_by
    })


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using SatelliteService.Contracts;

namespace SatelliteService.Operations
{
    public class UpdateHostsOperation : Operation
    {
        private Regex lineParseRegex = new Regex(@"^(?<IP>[^\s]+)\s+(?<Domain>.+)", RegexOptions.Compiled | RegexOptions.Singleline);

        private dynamic configuration;
        private Guid? backupFileGuid = null;

        public UpdateHostsOperation(IBackupRepository backupRepository) : base(backupRepository)
        {
        }

        public void Configure(dynamic configuration)
        {
            this.configuration = configuration;
        }

        public override void Run()
        {
            const string hostsPath = @"C:\Windows\System32\drivers\etc\hosts";

            this.backupFileGuid = this.BackupRepository.StoreFile(hostsPath);

            IList<string> lines = File.ReadLines(hostsPath).ToList();
            IList<string> appendLines = new List<string>();

            if (this.configuration.add != null)
            {
                foreach (dynamic line in this.configuration.add)
                {
                    this.AppendLineIfRequred(lines, appendLines, (string) line.ip, (string) line.domain);
                }
            }

            if (appendLines.Count > 0)
            {
                using (FileStream fileStream = new FileStream(hostsPath, FileMode.Append, FileAccess.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter(fileStream))
                    {
                        streamWriter.WriteLine("");
                        streamWriter.WriteLine("###############################");
                        streamWriter.WriteLine("");

                        foreach (string line in appendLines)
                        {
                            streamWriter.WriteLine(line);
                        }

                        streamWriter.Flush();
                    }
                }
            }
        }

        public override void Rollback()
        {
            if (this.backupFileGuid.HasValue)
            {
                this.BackupRepository.RestoreFile(this.backupFileGuid.Value);
            }
        }

        private void AppendLineIfRequred(IEnumerable<string> lines, IList<string> appendLines, string ip, string domain)
        {
            if (lines.All(line => this.ParseHostsLine(line).Value.ToLower() != domain))
            {
                appendLines.Add(ip + "	" + domain);
            }
        }

        private KeyValuePair<string, string> ParseHostsLine(string line)
        {
            if (string.IsNullOrWhiteSpace(line))
            {
                return new KeyValuePair<string, string>(string.Empty, string.Empty);
            }

            Match match = lineParseRegex.Match(line);

            if (!match.Success)
            {
                return new KeyValuePair<string, string>(string.Empty, string.Empty);
            }

            return new KeyValuePair<string, string>(match.Groups["IP"].Value, match.Groups["Domain"].Value);
        }
    }
}


text:
```bash
echo -e "1\torange\t100" \
    | seqrequest --method POST --url "http://example.com/articles/{1}" --data "name={2}&cost={3}"
```

Request:
```
POST http://example.com/articles/1 (data: name=orange&cost=100)
```

### Few requests with parameters

File rparams.txt

```
1	orange	100
2	apple	150
3	plum	200
```

```bash
cat rparams.txt \
    | seqrequest --method POST --url "http://example.com/articles/{1}" --data "name={2}&cost={3}"
```
Requests:
```
POST http://example.com/articles/1 (data: name=orange&cost=100)
POST http://example.com/articles/2 (data: name=apple&cost=150)
POST http://example.com/articles/3 (data: name=plum&cost=200)
```


text:
'use strict';

module.exports = (aws, utils, tableName, resourceName) => {

	/*
	Call whichever data service or methods to persist
	your data. Make sure to call your `callback`:

	Function `callback` requires 3 parameters:

	`error` (required)
		-- Can be either a string, object, or an array.
		-- Must be `null` if there is no error.
		-- Non-null value indicates there was an error
			persisting data.

	`data` (required)
		-- Must be an array of objects.
		-- This allows us to expect the same data type,
			regardless of the data call.
		-- Must be an empty array if there was no data
			to return.

	`message` (required)
		-- Must be a string.
		-- If there's something special we should know
			about the data, we can message here.
		-- If no message, return an empty string.

	*/

	return function(itemId, itemUpdates, callback) {

		var dynamoDb = new aws.DynamoDB.DocumentClient();
		var _ = require('underscore');

		itemUpdates.updated_at = new Date().getTime();
		var attributeUpdates = utils.aws.toAttributeUpdates(itemUpdates);

		dynamoDb.update({
			TableName: tableName,
			AttributeUpdates: attributeUpdates,
			Key: {
				id: itemId
			},
			ReturnValues: 'ALL_NEW'
		}, (error, data) => {

			var data = data || {};
			var results = data.Attributes ? [data.Attributes] : [];
			var message = '';
			if (results.length > 0) {
				message = `Done, just updated that ${resourceName} item!`;
			}
			else {
				message = ``;
			}

			return callback(error, results, message);

		});

	};

};


text:
@import Realm;
@import RealmExtensions.RLMObject_RealmExtensions;

NS_ASSUME_NONNULL_BEGIN

@interface PMTestModel : RLMObject

@property NSString *name;
@property NSString *info;
@property NSNumber <RLMInt> *id;

@end

NS_ASSUME_NONNULL_END


text:
#ifndef TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_NODES_H_
#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_NODES_H_

#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "absl/types/optional.h"
#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h"
#include "tensorflow/compiler/tf2tensorrt/convert/utils.h"
#include "tensorflow/compiler/tf2tensorrt/convert/weights.h"
#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h"
#include "tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h"
#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h"
#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h"
#include "tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/stream_executor/lib/statusor.h"

#if GOOGLE_CUDA && GOOGLE_TENSORRT
#include "third_party/tensorrt/NvInfer.h"

namespace tensorflow {
namespace tensorrt {

namespace convert {
using ::stream_executor::port::StatusOr;

struct EngineConnection {
  // Constructs a non-control edge.
  EngineConnection(const string& outside, int out_id, int out_port,
                   const string& inside, int in_id, int in_port,
                   bool input_edge, int port)
      : outside_node_name(outside),
        outside_id(out_id),
        outside_port(out_port),
        inside_node_name(inside),
        inside_id(in_id),
        inside_port(in_port),
        is_input_edge(input_edge),
        port_number(port) {}

  // Constructs a control edge.
  EngineConnection(const string& outside, int out_id, const string& inside,
                   int in_id, bool input_edge)
      : outside_node_name(outside),
        outside_id(out_id),
        outside_port(Graph::kControlSlot),
        inside_node_name(inside),
        inside_id(in_id),
        inside_port(Graph::kControlSlot),
        is_input_edge(input_edge),
        port_number(Graph::kControlSlot) {}

  bool is_control_edge() const { return port_number == Graph::kControlSlot; }

  const string outside_node_name;
  const int outside_id;
  const int outside_port;
  PartialTensorShape outside_shape;  // Only set for input edge.

  const string inside_node_name;
  const int inside_id;
  const int inside_port;
  PartialTensorShape inside_shape;  // Only set for output edge.

  DataType connection_type;
  const bool is_input_edge;

  // The port number of the TRT node connected with this edge.
  const int port_number;
};

struct EngineInfo {
  EngineInfo()
      : engine_type(EngineType::TRTStatic),
        max_workspace_size_bytes(0),
        max_batch_size(absl::nullopt),
        maximum_cached_engines(0),
        precision_mode(TrtPrecisionMode::FP32),
        use_calibration(true),

        allow_build_at_runtime(true),
        use_explicit_precision(false) {}

  string engine_name;
  string device;
  GraphDef segment_graph_def;

  // Non-control input connections inside this vector are sorted in a way such
  // that, the segment nodes connecting to them are topological sorted.
  // In addition, for non-control connections, there must be no duplicates.
  std::vector<EngineConnection> connections;

  enum class EngineType { TRTStatic = 0, TRTDynamic = 1 };
  EngineType engine_type;
  int64 max_workspace_size_bytes;
  absl::optional<int> max_batch_size;
  int maximum_cached_engines;
  TrtPrecisionMode precision_mode;
  bool use_calibration;
  bool allow_build_at_runtime;
  bool use_explicit_precision;
};

// Constructs a graphdef from the segment in the given graph and stores it to
// the engine_info. Adds _Arg nodes for input edges (InputPH_*) and _Retval
// nodes for output edges (OutputPH_*). Maintains the topological order of the
// non-input/output nodes in the graphdef. This function needs to be called
// before TensorRT layers are created because it prepares the original graph
// for TensorRT conversion.
//
// - subgraph_node_names: the node names of the subgraph.
// - subgraph_node_ids: the node ids of the subgraph, must be sorted in
//   topological order.
// - engine_info: a data structure that records the information about the
//   engine containing the subgraph.
//
// TODO(aaroey): add tests to validate these properties.
Status ConvertSegmentToGraphDef(
    const Graph* graph, const grappler::GraphProperties& graph_properties,
    const std::vector<const Node*>& subgraph_nodes, EngineInfo* engine_info);

// Converts given subgraph to a TRT engine saved in 'engine'. Returns ok iff
// 'builder' successfully build the engine. If the result is not ok, 'engine'
// will be set to nullptr
// Once returned, 'builder' is not needed any more and can be safely destroyed.
//
// - convert_successfully: indicates whether the conversion to TensorRT network
//   is successful. This is different than successfully building the engine:
//   building can still fail afterwards.
// Note: When 'cluster' is not null, it contains the graph to be converted.
//       We may perform additional optimizations to the graph before converting
//       the graph.
Status ConvertGraphDefToEngine(
    const GraphDef& gdef, TrtPrecisionMode precision_mode, int max_batch_size,
    size_t max_workspace_size_bytes,
    const std::vector<PartialTensorShape>& input_shapes,
    nvinfer1::ILogger* logger, nvinfer1::IGpuAllocator* allocator,
    TRTInt8Calibrator* calibrator,
    TrtUniquePtrType<nvinfer1::ICudaEngine>* engine, bool use_calibration,
    const bool use_implicit_batch, bool* convert_successfully,
    TrtShapeOptimizationProfile* profiles, absl::string_view engine_name,
    bool use_explicit_precision,
    tensorflow::grappler::Cluster* cluster = nullptr);

// Helper class for the segmenter to determine whether an output edge from the
// TRT segment is valid.
class OutputEdgeValidator {
 public:
  // Return true if the specified edge is eligible to be an output edge of the
  // TRT segment.
  bool operator()(const Edge* out_edge) const;
};

// Class to verify if specific TF node is supported by TRT.
class TrtNodeValidator {
 public:
  // 'graph_properties' is the GraphProperties of the graph whose nodes will be
  // checked by IsTensorRTCandidate() later. It is used to get the shape and
  // data type information of a tensor for validation purpose.
  TrtNodeValidator(const grappler::GraphProperties& graph_properties,
                   TrtPrecisionMode precision_mode, bool use_calibration,
                   bool use_implicit_batch, bool use_explicit_precision);

  // Returns OK iff 'node' is a TF-TRT conversion candidate, which will be added
  // to TRT subgraph and later converted into TRT engine.
  Status IsTensorRTCandidate(const Node* node);

  static const std::set<string>* quantize_ops;

  // Returns validator by op type. If no validator is registered for
  // specific op, it means no validation is needed and ValidateNode() will
  // return OK.
  StatusOr<OpConverter> GetValidator(const std::string& op);

 private:
  // Convert a Const node to a TRT_TensorOrWeights.
  Status ConvertConstToWeights(const NodeDef& const_node_def,
                               const std::vector<TRT_TensorOrWeights>& inputs,
                               TRT_TensorOrWeights* output);

  // Convert the output tensor at 'output_port' of 'node_def' to a
  // TRT_TensorOrWeights which will be later used as an input to other nodes and
  // passed to ValidateNode() below.
  Status ConvertToTensorOrWeights(const NodeDef& node_def, int output_port,
                                  TRT_TensorOrWeights* tensor_or_weights);

  // Store the weights added during validation. Some validations (e.g.
  // validation for Const node) may produce weights.
  TrtWeightStore weight_store_;

  // GraphProperties of the graph whose nodes are to be validated by
  // IsTensorRTCandidate().
  const grappler::GraphProperties& graph_properties_;

  // Quantization ops are only converted when using quantized precisions.
  const TrtPrecisionMode precision_mode_;

  const bool use_calibration_;

  const bool use_implicit_batch_;

  const bool use_explicit_precision_;

  friend class ValidatorTest;
  friend class OpConverterTest;
};

// Class to convert TF nodes to TRT network.
class Converter {
 public:
  // Used for Converter::RenameAndMarkOutputTensors()
  struct EngineOutputInfo {
    // The TRT tensor name which produces the output.
    string source_tensor_name;
    // The TensorFlow node name which is receiving the output from the TRT
    // engine. This should always be the Identity node created in
    // ConvertSegmentToGraphDef.
    string dest_node_name;
    // Output type. TensorRT requires this to be explicitly set for engine
    // outputs.
    nvinfer1::DataType trt_dtype;
  };

  static StatusOr<std::unique_ptr<Converter>> Create(
      TrtPrecisionMode precision_mode, bool use_calibration,
      nvinfer1::ILogger* trt_logger, const bool use_implicit_batch,
      absl::string_view engine_name, bool use_explicit_precision = false);

  //////////////////////////////////////////////////////////////////////////////
  // Methods used by the TRT engine builder to build a TRT network from a TF
  // function/subgraph.

  // Convert the node to TRT network.
  Status ConvertNode(const NodeDef& node_def);

  // Add input tensor to the TRT network with given 'name', 'dtype', 'dims' and
  // 'batch_size'.
  Status AddInputTensor(const string& name, nvinfer1::DataType dtype,
                        const nvinfer1::Dims& dims, int batch_size);

  // Mark the tensors with names specified by source_tensor_name as output of
  // the TRT network, and set their names in the TRT network as dest_node_name.
  Status RenameAndMarkOutputTensors(
      const std::vector<EngineOutputInfo>& output_tensors);

  // Build a TRT engine using the created network.
  Status BuildCudaEngine(TrtUniquePtrType<nvinfer1::ICudaEngine>* engine,
                         int max_batch_size, size_t max_workspace_size_bytes,
                         nvinfer1::IGpuAllocator* allocator,
                         TRTInt8Calibrator* calibrator,
                         TrtShapeOptimizationProfile* profiles);

  //////////////////////////////////////////////////////////////////////////////
  // Methods used by op converters to convert individual TF node and add layers
  // to the TRT network.

  // Op converters (e.g. ConvertReshape) need to access the TRT network in order
  // to add TRT layers.
  nvinfer1::INetworkDefinition* network() { return trt_network_.get(); }

  // What precision are we targeting?
  TrtPrecisionMode precision_mode() const { return precision_mode_; }

  // Calibration will be or was previously performed on this network?
  bool use_calibration() const { return use_calibration_; }

  // Whether implicit batch mode is enabled
  bool use_implicit_batch() const { return use_implicit_batch_; }

  // This function should be called when we know the quantization range of a
  // tensor from a quantize/dequantize node.
  void ProvideQuantizationRange(ITensorProxyPtr* tensor, float min_range,
                                float max_range);

  // Should be called when full TRT network has been constructed and before
  // building the engine.
  void MaybeApplyQuantizationRanges();

  // Below are helper methods for op converters to add different layers to the
  // TRT network.

  // Transpose 'input_tensor' with given permutation 'order_with_batch_dim' to
  // 'output_tensor'. The permutation 'order_with_batch_dim' contains the batch
  // dimension which should always be 0. If this is for adding a transpose layer
  // to support the conversion of 'node_def', callers need to provide a
  // non-empty 'sub_op_name' appended to the name of 'node_def' to avoid layer
  // name conflicts.
  Status TransposeTensor(ITensorProxyPtr input_tensor,
                         const std::vector<int>& order_with_batch_dim,
                         ITensorProxyPtr* output_tensor,
                         const NodeDef& node_def,
                         absl::string_view sub_op_name = "");

  // Reshapes a dynamic shape tensor by removing or adding dimensions of size 1,
  // and/or permuting the dimensions. The new shape is derived from the shape of
  // the input tensor according to the slices and size_for_added_dims arguments.
  //
  // If there would be at most one unknown dimension, we could set the new shape
  // using IShuffleLayer::setReshapeDimensions, which treats -1 as a special
  // value (the same way as TF). In general, we can have more than one unknown
  // dimensions, and we have to manipulate the shape tensors during runtime to
  // define the new shape. This helper function defines the necessary shape
  // inference layers and calls reshape using the calculated new shape.
  //
  // Example:
  //
  // Assume that we want to reshape a tensor from shape {A,B,C,D} to {C,D,A,B}
  // (no transpose, just change the shape). In dynamic shape mode, the A,B,C,D
  // values are not necessarily known at conversion time, they can be all -1. We
  // can only define the new shape at runtime, when the actual shape is already
  // known. To define the new shape:
  // - We use an IShapeLayer to retrieve a shape tensor with the {A,B,C,D}
  //   values.
  // - Create two slices {C,D} and {A,B} of the shape tensor.
  // - Concatenate these slices {C,D,A,B},
  // - Set the {C,D,A,B} shape tensor as an input shape tensor for
  // IShuffleLayer.
  //
  // This can be achieved by calling DynamicReshape(input, {{2,4},{0,2}},
  // params).
  //
  // Before each slice we can insert new dims if the corresponding
  // size_for_added_dims element is not negative. The size_for_added_dims array
  // can have more than slices.size() elements, in order to insert a dimension
  // after the last slice. For example, to add two leading 1 dimensions, and
  // three trailing 1 dimensions, call DynamicReshape(input, {{0,nbDims}},
  // {2, 3}).
  //
  // Parameters:
  // input - input tensor
  // slices - [start, end) pairs of slices
  // params - conversion parameters
  // output - reshaped tensor
  // size_for_added_dims - size of dimension inserted right before slice[i]. We
  //   only insert a new dim if size_for_added_dims[i] >= 0.
  Status DynamicReshape(ITensorProxyPtr input,
                        std::vector<std::pair<int, int>> slices,
                        OpConverterParams* params, ITensorProxyPtr* output,
                        std::vector<int> size_for_added_dims = {},
                        absl::optional<int> op_instance = absl::nullopt);

  // Inserts a singleton dimension at axis for a dynamic shape tensor.
  Status DynamicExpandDims(ITensorProxyPtr input, const nvinfer1::Dims& dims,
                           int axis, OpConverterParams* params,
                           ITensorProxyPtr* output,
                           absl::optional<int> op_instance = absl::nullopt);

  // Helper function to add a squeeze op to the network.
  //
  // The input_dims argument stores the TRT dimensions of the input tensor,
  // where the dimensions to be squeezed are replaced by 0.
  Status SqueezeTensor(ITensorProxyPtr input, std::vector<int>* input_dims,
                       OpConverterParams* params, ITensorProxyPtr* output);

  // Creates an IConstantLayer using 'weights' whose dimensions are specified by
  // 'dims', and returns the output ITensor.
  ITensorProxyPtr CreateConstantLayer(const TRT_ShapedWeights& weights,
                                      const nvinfer1::Dims& dims);

  // Gets the min and max value in a TRT_ShapedWeights
  Status GetWeightRange(const TRT_ShapedWeights& weights, float* out_min,
                        float* out_max) const;

  // Constructs a name and passed it to the TensorRT layer to support xprof.
  void SetLayerName(
      nvinfer1::ILayer* layer, const NodeDef& node_def,
      absl::string_view sub_op_name = "",
      absl::optional<int> sub_op_instance = absl::nullopt,
      absl::optional<std::string> origin_node_name = absl::nullopt);

  void SetLayerName(nvinfer1::ILayer* layer, absl::string_view main_op_name,
                    absl::string_view sub_op_name,
                    absl::optional<int> sub_op_instance = absl::nullopt);

  std::unordered_map<string, TRT_TensorOrWeights>& TensorsMap() {
    return trt_tensors_;
  }

  bool UseExplicitPrecision() const { return use_explicit_precision_; }

 private:
  Converter(TrtPrecisionMode precision_mode, bool use_calibration,
            nvinfer1::ILogger* trt_logger, const bool use_implicit_batch,
            absl::string_view engine_name, bool use_explicit_precision);

  Status Init(nvinfer1::ILogger* trt_logger);

  // Verify the provided batch_size is consistent with batch_size_ and update it
  // if necessary.
  Status MaybeUpdateBatchSize(int batch_size);

  // Add the provided tensor/weights to the map trt_tensors_.
  Status AddTensorOrWeights(const string& name, TRT_TensorOrWeights input);

  // Get the tensor/weights from trt_tensors_ by 'name'.
  Status GetTensorOrWeights(const string& name, TRT_TensorOrWeights* output);

  // Get the inputs of 'node_def' from trt_tensors_.
  Status GetInputs(const NodeDef& node_def,
                   std::vector<TRT_TensorOrWeights>* inputs) const;

  // Tensors/weights added during construction of trt_network_.
  std::unordered_map<string, TRT_TensorOrWeights> trt_tensors_;

  // The TRT builder used to create the network and build the engine. Not owned.
  TrtUniquePtrType<nvinfer1::IBuilder> trt_builder_;

  // The TRT network being built.
  TrtUniquePtrType<nvinfer1::INetworkDefinition> trt_network_;

  // Store the weights added during construction of trt_network_.
  TrtWeightStore weight_store_;

  // During conversion, this table is populated with quantization ranges per
  // tensor. MaybeApplyQuantizationRanges() will use this table to set the TRT
  // quantization ranges. Since TRT only supports symmetric ranges, we will
  // store the range as a single float = max(abs(min_range), abs(max_range)).
  // Range refers to the floating point values, e.g. min_range = 0.0f, max_range
  // = 6.0f for Relu6.
  std::unordered_map<ITensorProxyPtr*, float> quantization_ranges_proxy_;
  std::unordered_map<nvinfer1::ITensor*, float> quantization_ranges_;

  const TrtPrecisionMode precision_mode_;

  const bool use_calibration_;

  // If this is false, all dimensions including the batch dimension are
  // set explicitely.
  const bool use_implicit_batch_;

  // Batch size of inputs to trt_network_ added by AddInputTensor(). During
  // network construction it will update this, use it to verify the batch
  // size of all inputs are compatible, and make sure individual TF node is
  // acceptable by TRT.
  int batch_size_ = -1;

  // Assign a ID to each constant layer we create, so that we can assign a
  // unique name to the layer.
  int next_constant_layer_id_ = 0;

  // The name of the TRTEngineOp node.
  absl::string_view engine_name_;

  // Indicates whether to use explicit precision in TensorRT (Q/DQ support).
  bool use_explicit_precision_;

  friend class ConverterTest;
  friend class OpConverterTest;
};

// Converts 'input' of 'node_def' into 'tensor' with shape specified by 'dims'
// (which doesn't contain the batch dimension).
//
// If validation_only is true, it doesn't do the conversion but only do some
// minimum validation for the eligibility of the conversion, and *tensor will
// be set to nullptr.
// If validation_only is false converter must not be nullptr.
Status PrepareTensorForShape(
    Converter* converter, const TRT_TensorOrWeights& input,
    const DimsAdapter& dims, const bool validation_only,
    ITensorProxyPtr* tensor, const NodeDef& node_def,
    absl::optional<int> op_instance = absl::nullopt,
    absl::optional<std::string> origin_node_name = absl::nullopt);

// Return OK if the broadcast scheme is supported and compute the shapes after
// broadcasting. check_feasibility can be set to false in cases where dimensions
// do not need to match exactly (as in the case of BatchMatMulV2).
Status GetTrtBroadcastShape(const TRT_TensorOrWeights& operand_l,
                            const TRT_TensorOrWeights& operand_r,
                            const bool check_feasibility,
                            const bool use_implicit_batch,
                            nvinfer1::Dims* operand_l_new_dims,
                            nvinfer1::Dims* operand_r_new_dims);

// Map of all supported UnaryOperations
const std::unordered_map<string, nvinfer1::UnaryOperation>* UnaryOperationMap();
// Map of all supported ActivationTypes
const std::unordered_map<string, nvinfer1::ActivationType>* ActivationTypeMap();
// Map of all supported BinaryOperations
const std::unordered_map<string, nvinfer1::ElementWiseOperation>*
BinaryOperationMap();

constexpr std::array<std::pair<const char*, nvinfer1::ElementWiseOperation>, 10>
    kBinaryOperations = {{
        {"Add", nvinfer1::ElementWiseOperation::kSUM},
        {"AddV2", nvinfer1::ElementWiseOperation::kSUM},
        {"Mul", nvinfer1::ElementWiseOperation::kPROD},
        {"Sub", nvinfer1::ElementWiseOperation::kSUB},
        {"Div", nvinfer1::ElementWiseOperation::kDIV},
        {"FloorDiv", nvinfer1::ElementWiseOperation::kFLOOR_DIV},
        {"RealDiv", nvinfer1::ElementWiseOperation::kDIV},
        {"Minimum", nvinfer1::ElementWiseOperation::kMIN},
        {"Maximum", nvinfer1::ElementWiseOperation::kMAX},
        {"Pow", nvinfer1::ElementWiseOperation::kPOW},
    }};

}  // namespace convert
}  // namespace tensorrt
}  // namespace tensorflow

#endif  // GOOGLE_CUDA && GOOGLE_TENSORRT

#endif  // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_NODES_H_


text:
package dagutils

import (
	"context"
	"fmt"

	mdag "gx/ipfs/QmRiQCJZ91B7VNmLvA6sxzDuBJGSojS3uXHHVuNr3iueNZ/go-merkledag"

	ipld "gx/ipfs/QmX5CsuHyVZeTLxgRSYkgLSDQKb9UjE8xnhQzCEJWWWFsC/go-ipld-format"
	cid "gx/ipfs/QmZFbDTY9jfSBms2MchvYM9oYRbAF19K7Pby47yDBfpPrb/go-cid"
)

// DiffEnumerate fetches every object in the graph pointed to by 'to' that is
// not in 'from'. This can be used to more efficiently fetch a graph if you can
// guarantee you already have the entirety of 'from'
func DiffEnumerate(ctx context.Context, dserv ipld.NodeGetter, from, to *cid.Cid) error {
	fnd, err := dserv.Get(ctx, from)
	if err != nil {
		return fmt.Errorf("get %s: %s", from, err)
	}

	tnd, err := dserv.Get(ctx, to)
	if err != nil {
		return fmt.Errorf("get %s: %s", to, err)
	}

	diff := getLinkDiff(fnd, tnd)

	sset := cid.NewSet()
	for _, c := range diff {
		// Since we're already assuming we have everything in the 'from' graph,
		// add all those cids to our 'already seen' set to avoid potentially
		// enumerating them later
		if c.bef != nil {
			sset.Add(c.bef)
		}
	}
	for _, c := range diff {
		if c.bef == nil {
			if sset.Has(c.aft) {
				continue
			}
			err := mdag.EnumerateChildrenAsync(ctx, mdag.GetLinksDirect(dserv), c.aft, sset.Visit)
			if err != nil {
				return err
			}
		} else {
			err := DiffEnumerate(ctx, dserv, c.bef, c.aft)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

// if both bef and aft are not nil, then that signifies bef was replaces with aft.
// if bef is nil and aft is not, that means aft was newly added
// if aft is nil and bef is not, that means bef was deleted
type diffpair struct {
	bef, aft *cid.Cid
}

// getLinkDiff returns a changeset between nodes 'a' and 'b'. Currently does
// not log deletions as our usecase doesnt call for this.
func getLinkDiff(a, b ipld.Node) []diffpair {
	ina := make(map[string]*ipld.Link)
	inb := make(map[string]*ipld.Link)
	var aonly []*cid.Cid
	for _, l := range b.Links() {
		inb[l.Cid.KeyString()] = l
	}
	for _, l := range a.Links() {
		var key = l.Cid.KeyString()
		ina[key] = l
		if inb[key] == nil {
			aonly = append(aonly, l.Cid)
		}
	}

	var out []diffpair
	var aindex int

	for _, l := range b.Links() {
		if ina[l.Cid.KeyString()] != nil {
			continue
		}

		if aindex < len(aonly) {
			out = append(out, diffpair{bef: aonly[aindex], aft: l.Cid})
			aindex++
		} else {
			out = append(out, diffpair{aft: l.Cid})
			continue
		}
	}
	return out
}


text:
Viz - short for visuals - is the client library and service implementations for
compositing and gpu presentation.

See [//services/viz](../../services/viz/README.md) for more information about
Viz overall.

For understanding compositing related terminology, check out
[//cc](../../cc/README.md). For understanding display compositor's position in
the graphics stack, check out
[Compositor Stack slides](https://docs.google.com/presentation/d/1ou3qdnFhKdjR6gKZgDwx3YHDwVUF7y8eoqM3rhErMMQ/edit?usp=sharing).
For more comprehensive list of design docs relating to Viz, check out
[WIP list of design doc](https://crbug.com/821901).

**Table of Contents**
1. [Terminology](#terminology)
2. [Directory structure](#directory-structure)
    1. [common](#directory-structure-common)
    2. [client](#directory-structure-client)
    3. [host](#directory-structure-host)
    4. [service](#directory-structure-service)
3. [Runtime Features](#runtime-features)
4. [Naming guidelines with Mojo](#naming-guidelines)

## Terminology

**Mojo Interface**: The interface definition, found in a .mojom file. This is
an abstract interface and can be thought of as a process/thread-independent C++
abstract class.

**Mojo Implementation**: The default implementation of a mojom interface for
production. Many interfaces will only have a single implementation that we
ship.

**Alternate Mojo Implementations**: Secondary implementations of a mojom
interface for platform-specific details, for tests, etc.

**Service**: Where Mojo implementations live and run.

**Host**: A privileged process that provides access to viz Mojo interfaces for
Clients. Most services in Chrome don't have these, and Clients find the service
directly, but they are more common in Viz. Currently the Host is in the browser
process. In a fully-realized mus+ash, the Host moves outside of Chrome to the
window server.

**Client**: All users of a Mojo interface who are not the Host. They will
usually need to go through the Host to gain access to the Mojo interface.

**Host-side Wrapper**: A C++ wrapper around a Mojo interface for use in Hosts,
that often also exposes or uses some privileged interfaces that Clients don't
have. Generally prefer to use the Mojo interfaces directly, but sometimes we
need another C++ helper around it.

**Client-side Wrapper**: A C++ wrapper around a Mojo interface for use in
Clients. Generally prefer to use the Mojo interface directly, but sometimes we
need another C++ helper around it.

**Host/Client-side Abstraction**: A C++ wrapper around a Mojo interface that is
also a subclass of a C++ interface. Generally prefer to use the Mojo interfaces
directly, but sometimes we need a higher-level C++ abstraction, usually because
other subclasses cannot use the Mojo interface.

## Directory Structure
To keep dependencies clear into the Viz source tree, all source code files
should appear in leaf directories.

### common
Data types and simple helpers that are used by the client library, or by
clients directly, and by service implementations.

### client
Client library for accessing Viz services. May be used from privileged (eg
browser) or unprivileged (eg renderer) processes. The client library should
remain agnostic about *how* to communicate with viz (in other words should not
use mojo bindings), as some viz clients use mojo but others use it in-process
or via other IPC mechanisms.

| Can depend on: |
|:---------------|
| viz/common/    |

### host
Privileged client library for owning and controlling Viz services. May only be
used from privileged (eg browser) processes.

This should not depend on other parts of Viz, as they are core data types and
helpers only, and can be used from anywhere else in Viz.

| Can depend on: |
|:---------------|
| viz/common/    |

### service
Service-side implementations of Viz Mojo interfaces, which are found in
[//services/viz](https://cs.chromium.org/chromium/src/services/viz/). Each
component of the service-side implementation is located in its own
sub-directory.

As of this writing, these service components may be instantiated and used
directly from the browser process. But these services are intended to be
abstracted away through Mojo interfaces so that they are able to live entirely
outside the browser process, and gain in-process access to the Gpu.

#### service/display
**Display compositor**: The display compositor uses Gpu or software to composite
a set of frames, from multiple clients, into a single backing store for display
to the user. Also deals in getting screenshots of content by drawing to
offscreen buffers.

The top-level scheduler that coordinates when the compositor should draw, along
with when clients should be submitting frames.

This component is platform-agnostic, with any platform-specific details
abstracted away from it. It accesses Gpu services through the command buffer as
a client even though it is in the same process as the Gpu service in order to
be scheduled as a peer among other clients.

| Can depend on:        |
|:----------------------|
| viz/common/*          |
| viz/service/surfaces/ |

#### service/display_embedder
**Platform details for display compositor**: While the display compositor is
platform-agnostic, this component provides implementations of platform-specific
behaviour needed for the display compositor, and injected into it.

Code here supports presentation of the backing store drawn by the display
compositor (typically thought of as SwapBuffers), as well as the use of
overlays.

The source code is split into two build targets,
``components/viz/service:service`` and
``components/viz/service:gpu_service_dependencies``. The latter is
code that requires being run in the gpu process, thus could not work
if the viz service is located elsewhere. This is forward-looking code
as the viz service is moving into the gpu process always.

| Can depend on:                        |
|:--------------------------------------|
| viz/common/*                          |
| viz/service/display/<some_interfaces> |

Dependencies onto viz/service/display should generally only be for interfaces
that the embedder must provide to the display.

#### service/frame_sinks
**Frame sinks**: This component implements the Mojo interfaces to send frames,
resources, and other data types from ``viz/common/`` for display to the
compositing service. It receives and organizes relationships between what should
be composited.

| Can depend on:                |
|:------------------------------|
| viz/common/*                  |
| viz/service/display/          |
| viz/service/display_embedder/ |
| viz/service/hit_test/         |
| viz/service/surfaces/         |
| viz/service/transitions/      |

#### service/frame_sinks/video_capture
**FrameSinkVideoCaptureImpl**: This component implements the [Mojo
interfaces](../../services/viz/privileged/mojom/compositing/frame_sink_video_capture.mojom)
to capture frames that are sent to the compositing service, producing a stream
of video frames. It provides a capture pipeline where asynchronous GPU readback
is executed (via [CopyOutputRequests](common/frame_sinks/README.md), and then
CopyOutputResults are applied to a pool of shared memory buffers backing video
frames that are sent to privileged consumers.

A capturer instance is created via [FrameSinkManager's
CreateVideoCapturer()](../../services/viz/privileged/mojom/compositing/frame_sink_manager.mojom)
method.

| Can depend on:                |
|:------------------------------|
| media/base/*                  |
| media/capture/*               |
| media/mojo/*                  |
| viz/common/*                  |
| viz/service/frame_sinks/*     |

#### service/gl
**GL**: This component implements the Mojo interfaces for allocating (and
deallocating) gpu memory buffers, setting up a channel for the command buffer,
etc.

Similar to ``service/display_embedder`` this is split into two targets in
the build system. Code that must run in the gpu process is compiled in
the ``components/viz/service:gpu_service_dependencies`` build target,
and the rest is compiled in ``components/viz/service:service``. As all
code moves to the gpu process, these two build targets will merge.

| Can depend on:        |
|:----------------------|
| viz/common/*          |

#### service/hit_test
**Hit testing**: Service-side code to resolve input events to individual
clients.

| Can depend on:        |
|:----------------------|
| viz/common/*          |
| viz/service/surfaces/ |

#### service/main
**Main**: TODO(fsamuel): This will hold implementation of the root interface
from which other service interfaces are accessed.

As the root of the service/ code structure, it instantiates and connects all
other parts of Viz.

| Can depend on: |
|:---------------|
| viz/common/*   |
| viz/service/*  |

#### service/surfaces
**Surfaces**: This component acts like the data model for the compositing service.
It holds data received from frame sinks, and provides access to them for the
display compositor.

| Can depend on: |
|:---------------|
| viz/common/*   |

#### service/transitions
**Transitions**: This directory is in support of the shared element transitions
project. See //third\_party/blink/rendering/core/document\_transition/README.md

| Can depend on:        |
|:----------------------|
| viz/common/           |
| viz/service/surfaces/ |

## Runtime Features

Viz related runtime feature flags, aka `base::Feature`s, should go in
[components/viz/common/features.h](https://cs.chromium.org/chromium/src/components/viz/common/features.h).

When adding a new feature `kMyFeature` it's recommended that you add a helper
function `IsMyFeatureEnabled()` to check if the feature is enabled. Code should
then use `IsMyFeatureEnabled()` instead of checking
`base::FeatureList::IsEnabled(kMyFeature)`. Having a helper function makes it
easy to enforce preconditions that must be met for the feature to be enabled or
to unconditionally enable a feature on a per platform basis.

### Runtime Feature Checks

Never check if a feature is enabled in a hot code path as
`base::FeatureList::IsEnabled()` has a non-trivial runtime cost (it does a map
lookup). Ideally the feature state should be stored as a member variable in a
long lived class.

Resist the temptation to cache if a feature is enabled in a variable with static
storage duration, for example:

```cpp
bool IsMyFeatureEnabled() {
  static bool enabled = base::FeatureList::IsEnabled(kMyFeature);  // NO!
  return enabled;
}
```

While this avoids repeated calls to `FeatureList::IsEnabled()` it breaks tests.
The first time `IsMyFeatureEnabled()` is called from the test runner process the
feature state is cached. If a later test uses `base::ScopedFeatureList` to
change the feature state, that change will not be reflected in
`IsMyFeatureEnabled()` and the test will (most likely) fail. Test retries in a
new test runner process will pass, adding hidden flake and slowing down CQ.

### Testing Viz Features

Ensure that features are enabled/disabled for testing before any viz code is
initialized. As a general rule `base::ScopedFeatureList` should be the first
thing initialized in a test fixture to avoid data races and incorrect feature
values.

## Naming guidelines with Mojo

Viz makes extensive use of Mojo, and there are conflicting patterns with
regard to naming types around Mojo interfaces in the codebase today. This aims
to provide a standard to adhere to for future naming to increase our
consistency within the team.

For a given mojo service called `TimeTraveller`, we would use the following.

**Mojo Interface**: `mojom::TimeTraveller`
* This is the abstract interface definition. It comes with no prefix or suffix,
and lives in a (sometimes nested) mojom namespace.

**Mojo Implementation**: `TimeTravellerImpl`
* This is the implementation of the interface. For other C++ interfaces we
commonly use the Impl suffix, and we will repeat this here, as it's already
commonly used and is well understood.
* If there will be multiple implementations, see below.

**Alternative Mojo Implementation**: `DescriptivePrefixTimeTravellerImpl`
* This is a non-default implementation of the interface. It follows the same
rules as a default implementation, but is used for tests, or cases where we
don't have a simple default production implementation.
* The descriptive prefix should describe what makes this implementation
different from others, as such why it exists.

**Host-side Wrapper**: `HostTimeTraveller`
* This wraps the Mojo interface, providing a higher-level abstraction and
utilities for using the Mojo interface. It only is meant to exist and be
accessed in the privileged Host process. We prefix with Host to explain what
makes this interface special and when it can be used. We do not suffix to be
consistent with Clients.

**Client-side Wrapper**: `ClientTimeTraveller`
* This wraps the Mojo interface, providing a higher-level abstraction and
utilities for using the Mojo interface. It may exist and be used in any Client
in place of the Mojo interface. Prefer to use the Mojo interface directly when
possible. We prefix with Client to explain in what situations it can be used.
We do not suffix to avoid a TimeTravellerClientClient in the case where this
class has itself a C++ client, as ClientTimeTravellerClient appeared to be a
better option of the two.

**Host/Client-side Abstraction**: `OtherAbstractionName`
* This is a case of an object implementing a C++ interface, which it should be
named after. A prefix describing what makes this implementation special can
refer to its use of the Mojo interface.


text:
"""
Client which will talk to the server run by pbAnonServer.py, logging in
either anonymously or with username/password credentials.
"""

from __future__ import print_function

from sys import stdout

from twisted.python.log import err, startLogging
from twisted.cred.credentials import Anonymous, UsernamePassword
from twisted.internet import reactor
from twisted.internet.defer import gatherResults
from twisted.spread.pb import PBClientFactory

def error(why, msg):
    """
    Catch-all errback which simply logs the failure.  This isn't expected to
    be invoked in the normal case for this example.
    """
    err(why, msg)

def connected(perspective):
    """
    Login callback which invokes the remote "foo" method on the perspective
    which the server returned.
    """
    print("got perspective1 ref:", perspective)
    print("asking it to foo(13)")
    return perspective.callRemote("foo", 13)

def finished(ignored):
    """
    Callback invoked when both logins and method calls have finished to shut
    down the reactor so the example exits.
    """
    reactor.stop()

def main():
    """
    Connect to a PB server running on port 8800 on localhost and log in to
    it, both anonymously and using a username/password it will recognize.
    """
    startLogging(stdout)
    factory = PBClientFactory()
    reactor.connectTCP("localhost", 8800, factory)

    anonymousLogin = factory.login(Anonymous())
    anonymousLogin.addCallback(connected)
    anonymousLogin.addErrback(error, "Anonymous login failed")

    usernameLogin = factory.login(UsernamePassword("user1", "pass1"))
    usernameLogin.addCallback(connected)
    usernameLogin.addErrback(error, "Username/password login failed")

    bothDeferreds = gatherResults([anonymousLogin, usernameLogin])
    bothDeferreds.addCallback(finished)

    reactor.run()

if __name__ == '__main__':
    main()


text:
module SessionHelper
  def login(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.hash(remember_token))
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    remember_token = User.hash(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end

  def logged_in?
    !current_user.nil?
  end

  def logged_in_user
    unless logged_in?
      respond_to do |format|
        format.html {
            store_location
            redirect_to login_url
          }
        format.js   {
            store_location request.referer
            render js: "window.location.pathname='#{login_path}'"
          }
      end
    end
  end

  def logout
    current_user.update_attribute(:remember_token, User.hash(User.new_remember_token))
    cookies.delete(:remember_token)
    self.current_user = nil
  end

  def current_user?(user)
    user == current_user
  end

  def choose_campaign(campaign)
    session[:campaign_id] = campaign ? campaign.id : nil
  end

  def current_campaign
    session[:campaign_id] ? Campaign.find(session[:campaign_id]) : nil
  end

  def current_campaign?
    !current_campaign.nil?
  end

  private
    def store_location(override = nil)
       session[:return_to] = override.nil? ? request.fullpath : override
    end

    def redirect_back_or(default)
      redirect_to(session[:return_to] || default)
      session.delete(:return_to)
    end
end


text:
/*
 * EdgeList.cpp
 *
 *  Created on: 07.03.2013
 *
 */

#include "EdgeList.h"

namespace Delaunay
{

	EdgeList::EdgeList( Number xmin, Number deltax, int sqrt_nsites )
	{
		_xmin = xmin;
		_deltax = deltax;
		_hashsize = 2 * sqrt_nsites;

		_hash.resize( _hashsize );

		// two dummy Halfedges:
		_leftEnd = Halfedge::createDummy( );
		_rightEnd = Halfedge::createDummy( );
		_leftEnd->edgeListLeftNeighbor = NULL;
		_leftEnd->edgeListRightNeighbor = _rightEnd;
		_rightEnd->edgeListLeftNeighbor = _leftEnd;
		_rightEnd->edgeListRightNeighbor = NULL;
		_hash[0] = _leftEnd;
		_hash[_hashsize - 1] = _rightEnd;
	}

	EdgeList::~EdgeList( )
	{
		if( _leftEnd && _rightEnd )
			dispose();
	}

	void EdgeList::dispose( )
	{
		Halfedge* halfEdge = _leftEnd;
		Halfedge* prevHe = NULL;
		while( halfEdge != _rightEnd ){
			prevHe = halfEdge;
			halfEdge = halfEdge->edgeListRightNeighbor;
			prevHe->dispose( );
		}
		_leftEnd->reallyDispose();
		_leftEnd = NULL;
		_rightEnd->reallyDispose( );
		_rightEnd = NULL;
		_hash.clear( );
	}

	Halfedge* EdgeList::leftEnd( )
	{
		return _leftEnd;
	}

	Halfedge* EdgeList::rightEnd( )
	{
		return _rightEnd;
	}

	void EdgeList::insert( Halfedge* lb, Halfedge* newHalfedge )
	{
		newHalfedge->edgeListLeftNeighbor = lb;
		newHalfedge->edgeListRightNeighbor = lb->edgeListRightNeighbor;
		lb->edgeListRightNeighbor->edgeListLeftNeighbor = newHalfedge;
		lb->edgeListRightNeighbor = newHalfedge;
	}

	void EdgeList::remove( Halfedge* halfEdge )
	{
		halfEdge->edgeListLeftNeighbor->edgeListRightNeighbor =
				halfEdge->edgeListRightNeighbor;
		halfEdge->edgeListRightNeighbor->edgeListLeftNeighbor =
				halfEdge->edgeListLeftNeighbor;
		halfEdge->edge = Edge::DELETED;
		halfEdge->edgeListLeftNeighbor = halfEdge->edgeListRightNeighbor = NULL;
	}

	Halfedge* EdgeList::edgeListLeftNeighbor( const Point* p )
	{
		Halfedge* halfEdge = NULL;

		/* Use hash table to get close to desired halfedge */
		int bucket = (p->x - _xmin) / _deltax * _hashsize;
		if( bucket < 0 )
			bucket = 0;
		if( bucket >= _hashsize )
			bucket = _hashsize - 1;
		halfEdge = getHash( bucket );
		if( halfEdge == NULL ){
			for( int i = 1; true; ++i ){
				if( (halfEdge = getHash( bucket - i )) != NULL )
					break;
				if( (halfEdge = getHash( bucket + i )) != NULL )
					break;
			}
		}
		/* Now search linear list of halfedges for the correct one */
		if( halfEdge == leftEnd() || (halfEdge != rightEnd() && halfEdge->isLeftOf( p )) ){
			do{
				halfEdge = halfEdge->edgeListRightNeighbor;
			}while( halfEdge != rightEnd() && halfEdge->isLeftOf( p ) );
			halfEdge = halfEdge->edgeListLeftNeighbor;
		}else{
			do{
				halfEdge = halfEdge->edgeListLeftNeighbor;
			}while( halfEdge != leftEnd() && !halfEdge->isLeftOf( p ) );
		}

		/* Update hash table and reference counts */
		if( bucket > 0 && ( bucket < _hashsize - 1 ) )
			_hash[bucket] = halfEdge;

		return halfEdge;
	}

	Halfedge* EdgeList::getHash( int b )
	{
		if( b < 0 || b >= _hashsize )
			return NULL;

		Halfedge* halfEdge = _hash[b];
		if( halfEdge != NULL && halfEdge->edge == Edge::DELETED ){
			/* Hash table points to deleted halfedge.  Patch as necessary. */
			_hash[b] = NULL;
			// still can't dispose halfEdge yet!
			return NULL;
		}

		return halfEdge;
	}

} /* namespace Delaunay */


text:
require(['config'], function () {
  // load expect, mocha and sinon stuff
  require([
    'jquery',
    'expect',
    'mocha',
    'sinon'
  ], function (jquery, _expect, mocha, _sinon) {
    // setup mocha
    mocha.globals([ 'jQuery*' ])
    mocha.checkLeaks();
    mocha.setup('bdd');
    mocha.reporter('html');

    // load then Parsley modules for UT
    require([
      'src/parsley',
      'parsley/factory',
      'parsley/form',
      'parsley/field',
      'parsley/ui',
      'parsley/utils',
      'parsley/validator',
      'i18n/fr'
    ], function (Parsley, ParsleyFactory, ParsleyForm, ParsleyField, ParsleyUI, ParsleyUtils, ParsleyValidator) {

      // Setup console.warn so we insure it is called when we expect it
      beforeEach(function() {
        sinon.spy(console, 'warn');
        console.warn.expectedCallCount = 0;
      });
      afterEach(function() {
        expect(console.warn.callCount).to.be(console.warn.expectedCallCount);
        console.warn.restore();
      });
      window.expectWarning = function(fn) {
        var w = console.warn;
        expect(w.callCount).to.be(w.expectedCallCount);
        var result = fn.call();
        w.expectedCallCount++;
        expect(w.callCount).to.be(w.expectedCallCount);
        return result;
      };

      // load full parsley.js + UT
      require([
        'features/utils',
        'features/parsley',
        'features/pubsub',
        'features/abstract',
        'features/field',
        'features/multiple',
        'features/form',
        'features/validator',
        'features/ui'
      ], function (utils, parsleyBase, pubsub, abstract, field, multiple, form, validator, ui) {
        describe('ParsleyStandard', function () {
          // Use a pristine ParsleyExtend for the standard suite:
          var previousExtend;
          before(function () {
            previousExtend = window.ParsleyExtend;
            window.ParsleyExtend = {};
          });
          after(function () {
            window.ParsleyExtend = previousExtend;
            ParsleyUtils._resetWarnings();
          });
          utils(ParsleyUtils);
          parsleyBase(Parsley.Factory);
          pubsub();
          abstract();
          field(ParsleyField);
          multiple();
          form(ParsleyForm);
          validator(ParsleyValidator);
          ui(ParsleyUI);
        });

        // tested by it('should handle remote validator option') in `features/remote`
        window.ParsleyExtend = {
          asyncValidators: {
            custom: {
              fn: function (xhr) {
                return xhr.status === 404;
              }
            }
          }
        };

        require([
          'features/remote',
          'features/abstract',
          'features/field',
          'features/form'
        ], function (remote, abstract, field, form) {
          describe('Parsley+Remote', function () {
            // beforeEach(function () {
            //   window.ParsleyConfig = $.extend(true, {}, window.ParsleyConfig, { excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], input[disabled]' });
            // });
            remote(ParsleyExtend);
            abstract();
            field(ParsleyField);
            form(ParsleyForm);
          });

          require([
            'features/extra'
          ], function (extra) {
            extra(ParsleyValidator);

            // run mocha
            if (window.mochaPhantomJS)
              mochaPhantomJS.run();
            else
              mocha.run();
          });
        });
      });
    });
  });
});


text:
<?php
namespace app\MediBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
Use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;

class ProfesionalType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add(
                'psnombre', 'entity', array(
                    'label' => 'Profesional a asignar: ',
                    'class' => 'AppMediBundle:User1',
                    'query_builder' => function(EntityRepository $er) {
                     return $er->createQueryBuilder('u')
                               ->where('u.id >= 1');},
                    'property' => 'psNombre',
                    'attr' => array(
                        'class' => 'classs',
                        'data-native-menu' => 'false'
                    )));

    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'app\MediBundle\Entity\User1',
                                     'csrf_protection' => true,
                                     'csrf_field_name' => '_token',
                                     'intention' => 'actividad_item'));
    }

    public function getName() {
        return 'Profesional';
    }
}

?>


text:
require_relative "measure"

module GasBlender
  class Length < Measure
  end

  class Feet < Length
    def to_s
      "%.#{PRECISION}f feet" % magnitude
    end
  end
  class Meter < Length
    def to_s
      "%.#{PRECISION}f m" % magnitude
    end
  end
end


text:
package eu.daxiongmao.prv.wordpress.service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.net.ftp.FTPFile;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtpServiceIntegrationTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(FtpServiceIntegrationTest.class);

    @Ignore("You must adjust the test configuration in src/test/resources/app_settings/gallery-files.properties")
    @Test
    public void testListWordpressGalleriesAndTheirContent() throws IOException, URISyntaxException {
        // Load properties file
        final Path configFile = Paths.get(FileServiceTest.class.getClassLoader().getResource("app_settings/gallery-files.properties").toURI());
        final AppPropertiesService appPropService = new AppPropertiesService();
        final Properties properties = appPropService.loadApplicationProperties(configFile);

        // Process properties
        final String ftpHost = properties.getProperty("ftp.url");
        final int ftpPort = Integer.parseInt(properties.getProperty("ftp.port"));
        final String ftpUsername = properties.getProperty("ftp.username");
        final String ftpPassword = properties.getProperty("ftp.password");
        final String wordpressRelativePath = properties.getProperty("wordpress.relativePath");

        // Business test case
        final FtpService ftpService = new FtpService();
        ftpService.connect(ftpHost, ftpPort, ftpUsername, ftpPassword);
        final Map<String, FTPFile> files = ftpService.listAllGalleriesAndTheirContent(wordpressRelativePath);
        ftpService.disconnect();

        // Assertions
        Assert.assertNotNull(files);
        Assert.assertFalse(files.isEmpty());
    }

    @Ignore("You must adjust the test configuration in src/test/resources/app_settings/gallery-files.properties")
    @Test
    public void testListWordpressGalleriesAndTheirContentAndStartDownload() throws IOException, URISyntaxException {
        // Load properties file
        final Path configFile = Paths.get(FileServiceTest.class.getClassLoader().getResource("app_settings/gallery-files.properties").toURI());
        final AppPropertiesService appPropService = new AppPropertiesService();
        final Properties properties = appPropService.loadApplicationProperties(configFile);

        // Process properties
        final String ftpHost = properties.getProperty("ftp.url");
        final int ftpPort = Integer.parseInt(properties.getProperty("ftp.port"));
        final String ftpUsername = properties.getProperty("ftp.username");
        final String ftpPassword = properties.getProperty("ftp.password");
        final String wordpressRelativePath = properties.getProperty("wordpress.relativePath");

        // Create temp folder to backup files
        final Path backupDirectory = Files.createTempDirectory("gallery-files_junit");

        try {
            // Business test case
            final FtpService ftpService = new FtpService();
            ftpService.connect(ftpHost, ftpPort, ftpUsername, ftpPassword);
            final Map<String, FTPFile> files = ftpService.listAllGalleriesAndTheirContent(wordpressRelativePath);
            files.forEach((filename, ftpFile) -> {
                ftpService.downloadFile(filename, backupDirectory);
            });
            ftpService.waitForAllDownloadsThenDisconnect();

            // Assertions
            Assert.assertTrue(Files.exists(backupDirectory));
        } catch (final Exception e) {
            LOGGER.error("Failed to download gallery", e);
        } finally {
            // Cleanup test
            final FileService fileService = new FileService();
            fileService.recursiveDelete(backupDirectory);
        }
    }

}


text:
-- phpMyAdmin SQL Dump
-- version 3.3.2deb1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Nov 08, 2010 at 10:45 PM
-- Server version: 5.1.41
-- PHP Version: 5.3.2-1ubuntu4.2

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `iapps4me`
--
CREATE DATABASE `iapps4me` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `iapps4me`;

-- --------------------------------------------------------

--
-- Table structure for table `ideas`
--

CREATE TABLE IF NOT EXISTS `ideas` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) DEFAULT NULL,
  `description` varchar(500) DEFAULT NULL,
  `likes` int(11) DEFAULT NULL,
  `title` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=43 ;

--
-- Dumping data for table `ideas`
--

INSERT INTO `ideas` (`id`, `email`, `description`, `likes`, `title`) VALUES
(42, 'rob.skelton@gmail.com', 'Often people in cabs are bored and drunk. And they have an opinion of the cab/cab driver. And the cab driver has an ID name/number. It would be fun to write whatever you want about the cab/cabbie, and then see the ratings of others. A free app, but charge cab companies to see all the results. Win-Win!', 0, 'Rate A Cab'),
(14, '1millionthuser@iapps4.me', 'Post offices register to this app and the app will tell the person who is using the app if the post office which is neverest to them is open and how long it is open for. Also i could say diretions to it from were they are.\r\n', 1, 'Post Office Finder'),
(16, 'jones@me.com', 'I'd love an app that summarizes the FLYLady routines that can be found at www.flylady.net or in the book "Sink Reflections". I'm currently using the "home routines" app but would like to see the development of something to the effect of a true FLYLady control Journal.\r\n', 1, 'FlyLady App'),
(17, 'bula@baba.com', 'Choosing freelance writing as a profession is the easy decision; the work begins when it comes to looking for freelance writing jobs and freelance writing gigs.\r\nAs many freelance writers know finding freelance work can be time consuming and require a lot of effort and heartache. Numerous rejection letters, continuous query letters, and at the end of it all nothing is guaranteed of online writing job.\r\nThis is where ghost-writing and writers markets come into play. Ghost writing can allow you to', 0, 'Freelance Writing'),
(18, 'be@be.com', 'An app that allows an incoming call to be answered automatically when a headset is connected. I ride a motorbike with a comms system but I cannot answer calls without touching a button.\r\nThis could also be configured so that when an incoming call is received with either a plug in headset or a bluetooth headset the call would be automatically answered.', 3, 'Auto Answer for Calls'),
(20, 'gula@gula.com', 'The technical team of the company in coordination with the IT staff of the clinic enables the secure HIPAA compliant VPN connectivity, and using a secure password the medical transcribers can login and document the physician narrations read into the centralized voice recording system.\r\nIf the EMR application that is in use by a health care facility allows for Local Area Network (LAN) connectivity, the transcription companies set it up in a similar manner as the VPN. The EMR applications that are', 0, 'EMR VPN App'),
(21, 'dumdum@hooray.com', 'there is currently an app called Viigo for Blackberry, we need to have a app like this for android, something that brings your RSS feeds, socialnetworks, sports, entertainment all into one app, from there you can veiw your articles, and email them to friends, or to your self, you can twitter them , facebook them and so on,,...this app would be great', 0, 'Viigo for Android'),
(22, 'mightyjungle@lionsleeps.com', '\r\nyou have an elephant, yes. And it is a multidimensional resonator whoms trunk can rip open the very fabric of time and space! shake your ipod to make him travel deep into 1 of 1000's of other dimensions, some might be blank boxs of nothingness, one might be a tropical telephone with afro kangaroos on it who have a cat controlling their every move! just for a bit of fun, a random plaything of crazyness. Ill keep the ideas coming and it would be great if I could win once so please, vote on ANY', 0, 'Elephant Game'),
(23, 'guraba@huhu.com', 'Anyone ever heard on garry's mod. great game, but a few floors. One, you cant play the game on the go, two, theres not enough things that do something, like not just a barrel, but maybe a barrel with a shreddar inside, and three, you cant create movies, speak into it to make a charecter say something, ect… well dippido-ado fixes all these, first, its portable, second, it has special affect stuff like an imploding keyboard or a telephone that cows can come out, which brings us to another floo', 0, 'Garry''s Mod'),
(27, 'geek@gamyme.com', 'Millions of people are out of work. This app will allow you to access all help wanted ads in all major newspapers. Included will be links to real estate, reports on quality of life issues like school ratings, crime, taxes etc. Links to major headhunters and employment agencies will be broken down by state, city and county.\r\nA built in resume writer to help you prepare should also be included.\r\nIt will give the person the best leads possible to help find a job and then provide details that the fa', 0, 'Job Finder'),
(28, 'baba@blakksheep.com', 'I would like to have an app on my iPhone that could scan lotto ticket barcodes to see if they are a winner. Much easier than going somewhere or looking it up on the internet or TV. Would work with any phone with a camera and those capabilities ie iPhone, Androids, Blackberry's etc. Havent found anything through all my searches and I know that I would pay for it but I have no idea how to create apps.', 0, 'Lotto Barcode Scanner'),
(29, 'eiaieiai@ow.com', 'Create a new iPad case, no thicker than the current ones but embed a small camera, similar to that found in iPhone 3GS. Whereas to add no thickness or cost.\r\nSell the case for only slightly more than the average case similar to that.\r\nEnable users once bought to download an app which allows them to either connect wirelessly to the camera, or is connected when plugged into the 30 pin connector case on the dock area. \r\nThis would enable photos to be taken and used throughout applications adding a ', 1, 'iPad Case'),
(30, 'dud@dulono.com', 'We all have RSS Feeds to read. It is very time consuming, if you get the same content from several sources. So I think it's time for a "Genius". An intelligent smartlist/system for your RSS Reader to find identical content and avoid duplicates.', 0, 'RSS Feed Reader'),
(31, 'mimi@mula.com', 'Remocate is an idea I've had for some time. The idea is simple. 1) You need to remember to to pick up your dry cleaning! You enter the address of where it is and when you are within a certain distance of the dry cleaners, Remocate pushes a message to remind you or an audible alarm. A timed backup could also be used if you ignore it. 2) You need to find a chemist, newsagent, bank etc. You put in what you are looking for and leave it running in the background. When you get within a certain dista', 1, 'Remocate'),
(32, 'heman@sillyflower.com', 'Turn your BOSS into an animal and hear his/ her grunt, bark, growl. Upload a voice file (or text) of someone you HATE (boss) and turn his voice into an animal's grunt, squeak, bark or growl!\r\n(Can also be a colleague, friend, , politician, actor, in-law). Choose a drop down of animals (pig, dog, wounded lion, dinosaur, beetle, turkey, octopus).\r\nSelect the mood of the boss – Angry, insane, jealous, demanding, foolish, partisan, idiotic…\r\nAnd lo! Your BOSS sounds hilarious.', 4, 'Boss Noise'),
(33, 'dudu@dolodolo.com', 'Now that there is bluetooth keyboard funtionality I would like to see a game like the classic SEGA "Typing of the dead" or clone of. Educational in that you learn to type under pressure from Zombies! Each correctly spelt word keeps the zombies at bay! The only way to get through it is by learning to touch type and not taking your eyes off the screen! A game way ahead of its time, good way to promote the use of Bluetooth keyboards now that you can use them with iphone. They could give the App', 0, 'Bluetooth Keyboard'),
(34, 'Richardchen_78@hotmail.com', 'A better multi language translator/dictionary for the iphone with a Real voice pronunciation, for example when you search a chinese word on the iphone you can type it in using pinyin or zhuyin or just draw the character in and the search will come up with the word with the correct pinyin and zhuyin and the meaning and pronunciation.', 0, 'Language Translator'),
(39, 'test@hotmail.com', 'Build an application which can predict the future with a certain degree of accuracy. Make it so that I can ask it questions and the application will be able to respond accordingly.', 1, 'Crystal Ball'),
(37, 'andy@universalsprout.com', 'If I''m stuck in the rain and the bus is late it would be really good to have an app to find out where the bus is. This could be combined with the ability to view the bus timetable and propose alternate routes to my planned destination.', 11, 'Where''s my bus?');

-- --------------------------------------------------------

--
-- Table structure for table `iprovider`
--

CREATE TABLE IF NOT EXISTS `iprovider` (
  `ipid` int(11) NOT NULL AUTO_INCREMENT,
  `id` int(11) DEFAULT NULL,
  `email` varchar(100) NOT NULL,
  `price` double NOT NULL,
  PRIMARY KEY (`ipid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;

--
-- Dumping data for table `iprovider`
--

INSERT INTO `iprovider` (`ipid`, `id`, `email`, `price`) VALUES
(1, 18, '0', 0),
(2, 18, '0', 0),
(3, 32, '0', 0),
(4, 18, '0', 0),
(5, 35, '0', 0),
(6, 32, '0', 0),
(7, 31, '0', 0),
(8, 32, '0', 0),
(9, 29, 'heyhey@me.com', 0),
(10, 37, 'minty@minty-ai.net', 5),
(11, 37, 'edisonxh@gmail.com', 2),
(12, 37, 'writeameer@gmail.com', 3),
(13, 37, 'admin@nisch.org', 1),
(14, 37, 'test@test.com', 0),
(15, 32, 'test@nisch.org', 0),
(16, 37, 'test@test.com', 5),
(17, 14, 'test@hotmail.com', 20),
(18, 39, 'msn@nisch.org', 100),
(19, 40, 'eset@asefasf.com', 10),
(20, 40, 'eset@asefasf.com', 10),
(21, 41, 'test@hotmail.com', 4),
(22, 37, 'msn@nisch.org', 1),
(23, 37, 'me@me.com', 5),
(24, 37, 'me@me.com', 2),
(25, 37, 'ndy@gmail.com', 3),
(26, 37, 'me@me.com', 7);

-- --------------------------------------------------------

--
-- Table structure for table `solutions`
--

CREATE TABLE IF NOT EXISTS `solutions` (
  `sid` int(11) NOT NULL AUTO_INCREMENT,
  `id` int(11) DEFAULT NULL,
  `spid` int(11) DEFAULT NULL,
  `solution` varchar(500) DEFAULT NULL,
  `approved` tinyint(1) NOT NULL DEFAULT '0',
  `hash` varchar(32) NOT NULL,
  PRIMARY KEY (`sid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ;

--
-- Dumping data for table `solutions`
--

INSERT INTO `solutions` (`sid`, `id`, `spid`, `solution`, `approved`, `hash`) VALUES
(1, 1, 1, 'Solution 1', 1, ''),
(2, 2, 7, '222222', 1, ''),
(3, 2, 8, 'blah', 1, ''),
(4, 4, 9, 'new solution', 1, ''),
(5, 4, 10, 'another solution', 1, ''),
(6, 3, 11, 'test', 1, ''),
(7, 1, 12, 'blah blah', 1, ''),
(8, 11, 13, 'Life in my Pocket\r\n\r\nIt would be great if I could carry around my life list with me all the time on my iPhone, but the only way I could do that is to buy a "to-do" list application and manually put them in one by one. That is such a pain; there must be an easier way?', 1, ''),
(9, 25, 14, 'Millions of people are out of work. This app will allow you to access all help wanted ads in all major newspapers. Included will be links to real estate, reports on quality of life issues like school ratings, crime, taxes etc. Links to major headhunters and employment agencies will be broken down by state, city and county.\r\nA built in resume writer to help you prepare should also be included.\r\nIt will give the person the best leads possible to help find a job and then provide details that the fa', 1, ''),
(10, 30, 15, 'Amoogle!', 1, ''),
(11, 36, 18, 'test', 1, 'o61m90b1nqUzMM8je3kYkwT3trZaL5na'),
(12, 37, 19, 'I can build this application for the iPhone platform.', 0, 'NCEq4ZVV3NmmnhP01znTXtFzCxwpakHY'),
(13, 39, 20, 'I have the solution.', 0, 'CKleG4jDvejIoc6D1uRqA72Y5jjVUrzw'),
(14, 39, 21, 'I have the solution.', 0, 'AdrsbUnbt85Laq8VNMGycuCgyTimqEU0'),
(15, 30, 22, 'Such RSS utility should do the following:\r\n1. create list of RSS feeds to be analyzed\r\n2. prioritize RSS feeds on this list - which one should be read as first, second, etc., thus deciding the main source.\r\n3. define depth of lexical analysis of feeds - full header, first sentence, first line of header.\r\n4. as option decide what to do with duplicated feed - remove (no access to comments) or mark as read.', 0, '8YmyQpkrCQKjbCHk8w8XhsKcH6sO9ebi'),
(16, 14, 23, 'In fact, this app already exists in the form of USPS Mobile:\r\n\r\nhttp://itunes.apple.com/us/app/usps-mobile/id339597578?mt=8\r\n\r\nYou can even track shipments in the app.', 0, 'hvqTSOSZB7bEu0XpBpKe1SVjzHUmRgM9'),
(17, 30, 24, 'Why not simply use feedsifter with combination of feedrinse', 0, 'pRho9o8Bg6eRjs4tVeonxcRaROB5c7EB'),
(18, 14, 26, 'around me app does this', 0, 'Dz8gI89epp1gLZHjgikT3Ihahp71EXLi'),
(19, 37, 27, 'nextbus.com', 0, 'Mm490EtoyBxuTjlOL9oV1YJl4OAdY6DK');

-- --------------------------------------------------------

--
-- Table structure for table `sprovider`
--

CREATE TABLE IF NOT EXISTS `sprovider` (
  `spid` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`spid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=28 ;

--
-- Dumping data for table `sprovider`
--

INSERT INTO `sprovider` (`spid`, `email`) VALUES
(1, 'testsp@iapps4me.com'),
(2, 'test solution'),
(3, 'test@hotmail.com'),
(4, 'test@hotmail.com'),
(5, 'test@hotmail.com'),
(6, 'test2@hotmail.com'),
(7, '2@2.com'),
(8, 'blah@blah.com'),
(9, 'new@new.com'),
(10, 'another@test.com'),
(11, 'test@test.com'),
(12, 'me@me.com'),
(13, 'writeameer@gmail.com'),
(14, 'a@a.com'),
(15, 'david@cloudartisan.com'),
(16, 'me@me.com'),
(17, 'minty@minty-ai.net'),
(18, 'me@me.com'),
(19, 'me@me.com'),
(20, 'soln1@hotmail.com'),
(21, 'test@hotmail.com'),
(22, 'mar3kg@gmail.com'),
(23, 'computerwiz908@gmail.com'),
(24, 'marun2@gmail.com'),
(25, 'peter.evil1@gmail.com'),
(26, 'buddy@buddy.com'),
(27, 'gtdminh@gmail.com');