text:
package uk.co.bsol.trezorj.core.usb;

import com.codeminders.hidapi.HIDDevice;
import org.junit.Test;

import java.io.IOException;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

public class HIDInputStreamTest {

  // Note that Mockito cannot mock native methods
  // This is just to avoid a null reference and remove USB dependency from build environments
  private HIDDevice device = mock(HIDDevice.class);

  @Test
  public void verifySingleFrameUnbuffered() throws IOException {

    final byte[] hidFrame = HIDStreams.newHIDFrame(2);

    byte[] expected = HIDStreams.newHIDPayload(2);
    byte[] actual = new byte[expected.length];

    HIDInputStream testObject = HIDStreams.newSingleFrameHIDInputStream(device, hidFrame);

    assertThat(testObject.read(actual)).isEqualTo(expected.length);
    assertThat(actual).isEqualTo(expected);

    testObject.close();

  }

    @Test
    public void verifySingleFrameBuffered() throws IOException {

      final byte[] hidFrame = HIDStreams.newHIDFrame(4);

      byte[] expected = HIDStreams.newHIDPayload(4);
      byte[] actual = new byte[expected.length];

      HIDInputStream testObject = HIDStreams.newSingleFrameHIDInputStream(device, hidFrame);

      // Create the payload through a series of single byte reads
      for (int i = 0; i < expected.length; i++) {
        byte b = (byte) testObject.read();
        actual[i] = b;
      }

      assertThat(actual).isEqualTo(expected);

      testObject.close();

    }

    @Test
    public void verifyMultiFrameUnbuffered() throws IOException {

      // Create a multi-frame HID
      final byte[][] hidFrames = new byte[][]{
        HIDStreams.newHIDFrame(63),
        HIDStreams.newHIDFrame(3)
      };

      byte[] expected = new byte[66];
      for (int i=0; i< expected.length; i++) {
        expected[i] = (byte) (i % 63);
      }
      byte[] actual = new byte[expected.length];

      HIDInputStream testObject = HIDStreams.newMultiFrameHIDInputStream(device, hidFrames);

      assertThat(testObject.read(actual, 0, expected.length)).isEqualTo(expected.length);

      assertThat(actual).isEqualTo(expected);

      testObject.close();

    }

    @Test
    public void verifyMultiFrameBuffered() throws IOException {

      // Create a multi-frame HID
      final byte[][] hidFrames = new byte[][]{
        HIDStreams.newHIDFrame(63),
        HIDStreams.newHIDFrame(3)
      };

      byte[] expected = new byte[66];
      for (int i=0; i< expected.length; i++) {
        expected[i] = (byte) (i % 63);
      }
      byte[] actual = new byte[expected.length];

      HIDInputStream testObject = HIDStreams.newMultiFrameHIDInputStream(device, hidFrames);

      for (int i = 0; i < expected.length; i++) {
        byte b = (byte) testObject.read();
        actual[i] = b;
      }

      assertThat(actual).isEqualTo(expected);

      testObject.close();

    }

}


text:
/* Boehm, May 19, 1994 2:23 pm PDT */
# ifndef CORD_POSITION_H

/* The representation of CORD_position.  This is private to the	*/
/* implementation, but the size is known to clients.  Also	*/
/* the implementation of some exported macros relies on it.	*/
/* Don't use anything defined here and not in cord.h.		*/

# define MAX_DEPTH 48
	/* The maximum depth of a balanced cord + 1.		*/
	/* We don't let cords get deeper than MAX_DEPTH.	*/

struct CORD_pe {
    CORD pe_cord;
    size_t pe_start_pos;
};

/* A structure describing an entry on the path from the root 	*/
/* to current position.						*/
typedef struct CORD_Pos {
    size_t cur_pos;
    int path_len;
#	define CORD_POS_INVALID (0x55555555)
		/* path_len == INVALID <==> position invalid */
    const char *cur_leaf;	/* Current leaf, if it is a string.	*/
    				/* If the current leaf is a function,	*/
    				/* then this may point to function_buf	*/
    				/* containing the next few characters.	*/
    				/* Always points to a valid string	*/
    				/* containing the current character 	*/
    				/* unless cur_end is 0.			*/
    size_t cur_start;	/* Start position of cur_leaf	*/
    size_t cur_end;	/* Ending position of cur_leaf	*/
    			/* 0 if cur_leaf is invalid.	*/
    struct CORD_pe path[MAX_DEPTH + 1];
    	/* path[path_len] is the leaf corresponding to cur_pos	*/
    	/* path[0].pe_cord is the cord we point to.		*/
#   define FUNCTION_BUF_SZ 8
    char function_buf[FUNCTION_BUF_SZ];	/* Space for next few chars	*/
    					/* from function node.		*/
} CORD_pos[1];

/* Extract the cord from a position:	*/
CORD CORD_pos_to_cord(CORD_pos p);

/* Extract the current index from a position:	*/
size_t CORD_pos_to_index(CORD_pos p);

/* Fetch the character located at the given position:	*/
char CORD_pos_fetch(CORD_pos p);

/* Initialize the position to refer to the give cord and index.	*/
/* Note that this is the most expensive function on positions:	*/
void CORD_set_pos(CORD_pos p, CORD x, size_t i);

/* Advance the position to the next character.	*/
/* P must be initialized and valid.		*/
/* Invalidates p if past end:			*/
void CORD_next(CORD_pos p);

/* Move the position to the preceding character.	*/
/* P must be initialized and valid.			*/
/* Invalidates p if past beginning:			*/
void CORD_prev(CORD_pos p);

/* Is the position valid, i.e. inside the cord?		*/
int CORD_pos_valid(CORD_pos p);

char CORD__pos_fetch(CORD_pos);
void CORD__next(CORD_pos);
void CORD__prev(CORD_pos);

#define CORD_pos_fetch(p)	\
    (((p)[0].cur_end != 0)? \
     	(p)[0].cur_leaf[(p)[0].cur_pos - (p)[0].cur_start] \
     	: CORD__pos_fetch(p))

#define CORD_next(p)	\
    (((p)[0].cur_pos + 1 < (p)[0].cur_end)? \
    	(p)[0].cur_pos++ \
    	: (CORD__next(p), 0))

#define CORD_prev(p)	\
    (((p)[0].cur_end != 0 && (p)[0].cur_pos > (p)[0].cur_start)? \
    	(p)[0].cur_pos-- \
    	: (CORD__prev(p), 0))

#define CORD_pos_to_index(p) ((p)[0].cur_pos)

#define CORD_pos_to_cord(p) ((p)[0].path[0].pe_cord)

#define CORD_pos_valid(p) ((p)[0].path_len != CORD_POS_INVALID)

/* Some grubby stuff for performance-critical friends:	*/
#define CORD_pos_chars_left(p) ((long)((p)[0].cur_end) - (long)((p)[0].cur_pos))
	/* Number of characters in cache.  <= 0 ==> none	*/

#define CORD_pos_advance(p,n) ((p)[0].cur_pos += (n) - 1, CORD_next(p))
	/* Advance position by n characters	*/
	/* 0 < n < CORD_pos_chars_left(p)	*/

#define CORD_pos_cur_char_addr(p) \
	(p)[0].cur_leaf + ((p)[0].cur_pos - (p)[0].cur_start)
	/* address of current character in cache.	*/

#endif

redpajama_set_name: RedPajamaGithub


text:
jasmine.TrivialReporter = function() {
};

jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
  var el = document.createElement(type);

  for (var i = 2; i < arguments.length; i++) {
    var child = arguments[i];

    if (typeof child === 'string') {
      el.appendChild(document.createTextNode(child));
    } else {
      el.appendChild(child);
    }
  }

  for (var attr in attrs) {
    if (attr == 'className') {
      el.setAttribute('class', attrs[attr]);
    } else {
      if (attr.indexOf('x-') == 0) {
        el.setAttribute(attr, attrs[attr]);
      } else {
        el[attr] = attrs[attr];
      }
    }
  }

  return el;
};

jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
  console.log(runner);
};

jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
  console.log(suite);
};

jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
  var specDiv = this.createDom('div', {
    className: spec.getResults().passed() ? 'spec passed' : 'spec failed'
  }, spec.getFullName());

  var resultItems = spec.getResults().getItems();
  for (var i = 0; i < resultItems.length; i++) {
    var result = resultItems[i];
    if (!result.passed) {
      var resultMessageDiv = this.createDom('div', {className: 'resultMessage'});
      resultMessageDiv.innerHTML = result.message; // todo: lame; mend
      specDiv.appendChild(resultMessageDiv);
      specDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
    }
  }

  document.body.appendChild(specDiv);
};

jasmine.TrivialReporter.prototype.log = function() {
  console.log.apply(console, arguments);
};


text:
if [ "X$(basename -- "$0")" == "Xzephyr-env.sh" ]; then
    echo "Source this file (do NOT execute it!) to set the Zephyr Kernel environment."
    exit
fi

# You can further customize your environment by creating a bash script called
# zephyr-env_install.bash in your home directory. It will be automatically
# run (if it exists) by this script.

uname | grep -q MINGW && MINGW_OPT="-W"

# identify OS source tree root directory
export ZEPHYR_BASE=$( builtin cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ${MINGW_OPT})

scripts_path=${ZEPHYR_BASE}/scripts
echo "${PATH}" | grep -q "${scripts_path}"
[ $? != 0 ] && export PATH=${scripts_path}:${PATH}
unset scripts_path

# enable custom environment settings
zephyr_answer_file=~/zephyr-env_install.bash
[ -f ${zephyr_answer_file} ] && . ${zephyr_answer_file}
unset zephyr_answer_file


text:
<?xml version="1.0" encoding="utf-8"?>

<query style="NullStyle.xsl" startDoc="0" maxDocs="10">
  <text indexPath="IndexDB" maxSnippets="100" contextChars="80" termMode="all">
    <term>you</term>
    <not>
      <term>particular</term>
    </not>
  </text>
</query>


text:
using System;
using System.Linq;
using Xamarin.Forms;
using System.Collections.Generic;
using MapsuiFormsSample.DataObjects;
using MapsuiFormsSample.Services;
using System.Diagnostics;
using System.Threading.Tasks;
using Plugin.Permissions.Abstractions;
using Plugin.Permissions;
using MapsuiFormsSample.DataObjects.UI;
using MapsuiFormsSample.Helpers;
#if __MOBILE__
using Plugin.Geolocator;
using Plugin.Geolocator.Abstractions;
#endif

namespace MapsuiFormsSample
{
    public partial class MainPage : ILocationServiceChangeWatcher
    {
        private IMarkerService _markerService;
        private ILocationService _locationService;

        private Double? _currentLat = null;
        private Double? _currentLong = null;
        ListView _listView;
        List<Marker> _markersList;

        public MainPage()
        {
            this.Title = "Closest Markers";

            _markerService = new MarkerService();
            _locationService = new LocationService(this);

            // Required line when using XAML file.
            InitializeComponent();
            //ShowTestButton();
            ShowMarkersList();

            _locationService.InitLocationChangeListener();
        }

        void ShowTestButton()
        {
            Label testLabel = new Label
            {
                Text = "Test Label",
                HorizontalOptions = LayoutOptions.Center
            };
            Button button = new Button
            {
                Text = "Click Me!",
                BorderWidth = 1,
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions = LayoutOptions.CenterAndExpand
            };
            button.Clicked += OnButtonClicked;
            ContentGrid.Children.Add(testLabel);
            ContentGrid.Children.Add(button);
        }

        private List<MarkerListViewItem> GetMarkersWithDistances(List<Marker> markersList)
        {
            List<MarkerListViewItem> list = new List<MarkerListViewItem>();
            foreach (Marker marker in markersList)
            {
                var item = new MarkerListViewItem()
                {
                    Marker = marker
                };

                if (_currentLat != null && _currentLong != null)
                {
                    /*
                    // Adapted from https://forums.xamarin.com/discussion/comment/34987/#Comment_34987
                    double d = Math.Acos(
                        (Math.Sin((double)_currentLat) * Math.Sin(marker.Latitude)) +
                        (Math.Cos((double)_currentLat) * Math.Cos(marker.Latitude))
                        * Math.Cos(marker.Longitude - (double)_currentLong));

                    // in meters
                    //item.DistanceAway = (6378137 * d).ToString();
                    // in miles
                    item.DistanceAway = (3959 * d).ToString();
                    */

                    Double distInMeters = DistanceHelper.DistanceInMetres((double)_currentLat, (double)_currentLong, marker.Latitude, marker.Longitude);
                    Decimal distInMiles = (Decimal)(distInMeters * 0.000621371);
                    Decimal distRounded = Decimal.Round(distInMiles, 1);
                    item.DistanceAway = distRounded.ToString() + " mi";
                    item.DistanceAwayDecimal = distRounded;
                }
                else
                {
                    item.DistanceAway = "Unknown";
                    item.DistanceAwayDecimal = 0;

                }

                list.Add(item);
            }
            return list;
        }

        async void ShowMarkersList()
        {
            _markersList = await _markerService.GetAllMarkers();

            List<MarkerListViewItem> markersWithDistances = GetMarkersWithDistances(_markersList);

            // Create the ListView.
            _listView = new ListView
            {
                // Source of data items.
                ItemsSource = markersWithDistances,

                // Define template for displaying each item.
                // (Argument of DataTemplate constructor is called for
                //      each item; it must return a Cell derivative.)
                ItemTemplate = new DataTemplate(() =>
                {
                    // Create views with bindings for displaying each property.
                    Label nameLabel = new Label();
                    nameLabel.SetBinding(Label.TextProperty, "Marker.Title");

                    Label nodeIdLabel = new Label();
                    nodeIdLabel.SetBinding(Label.TextProperty, "DistanceAway");
                    /*nodeIdLabel.SetBinding(Label.TextProperty,
                        new Binding("DistanceAway", BindingMode.OneWay,
                            null, null, "Distance:  {0}"));
*/

                    // Return an assembled ViewCell.
                    return new ViewCell
                    {
                        View = new StackLayout
                        {
                            Padding = new Thickness(0, 5),
                            Orientation = StackOrientation.Horizontal,
                            Children =
                                {
                                    new StackLayout
                                    {
                                        VerticalOptions = LayoutOptions.Center,
                                        Spacing = 0,
                                        Children =
                                        {
                                            nameLabel,
                                            nodeIdLabel
                                        }
                                        }
                                }
                        }
                    };
                })
            };

            _listView.ItemTapped += async (sender, args) =>
            {
                MarkerListViewItem marker = args.Item as MarkerListViewItem;
                if (marker == null)
                {
                    return;
                }
                // TODO: Show marker detail screen
                //ShowMarkerLocation(marker.Title, "/?q=mobileapi/node/" + marker.NodeId);

                await Navigation.PushAsync(new MarkerInfoPage(marker.Marker));
                _listView.SelectedItem = null;
            };

            ContentGrid.Children.Add(_listView);

        }

        async void OnButtonClicked(object sender, EventArgs e)
        {
            // TODO: load the specific item clicked.
            // ShowMarkerLocation("Test hardcoded marker", "/?q=mobileapi/node/2.json");
        }

        public async void PositionChanged(object sender, PositionEventArgs e)
        {
            Debug.WriteLine("PositionChanged called");
            //If updating the UI, ensure you invoke on main thread
            var position = e.Position;
            var output = "PositionChanged() called. Full: Lat: "
                + position.Latitude + " Long: " + position.Longitude;
            output += "\n" + $"Time: {position.Timestamp}";
            output += "\n" + $"Heading: {position.Heading}";
            output += "\n" + $"Speed: {position.Speed}";
            output += "\n" + $"Accuracy: {position.Accuracy}";
            output += "\n" + $"Altitude: {position.Altitude}";
            output += "\n" + $"Altitude Accuracy: {position.AltitudeAccuracy}";
            Debug.WriteLine(output);

            _currentLat = position.Latitude;
            _currentLong = position.Longitude;

            // Refresh marker list and recalculate distance away.
            List<MarkerListViewItem> markersWithDistances = GetMarkersWithDistances(_markersList);
            markersWithDistances.Sort((m1, m2) => m1.DistanceAwayDecimal.CompareTo(m2.DistanceAwayDecimal));

            _listView.ItemsSource = markersWithDistances;
            /*if (_initialLoadCompleted)
            {
                // Redraw map

                _mapControl.NativeMap.Layers.Remove(_layer);
                _layer = await GenerateLayer(position);

                _mapControl.NativeMap.Layers.Add(_layer);
            }
            else
            {
                Debug.WriteLine("Initial load not completed so skipping map redraw");
            }
            */
        }

        /*
        async void ShowMarkerLocation(string title, string url)
        {
            var json = await client.GetStringAsync(url);
            try
            {
                dynamic stuff = JsonConvert.DeserializeObject(json);
                double lat = stuff.field_coordinates.und[0].safe_value;
                double longitude = stuff.field_coordinates.und[1].safe_value;
                // TODO: Open Google maps URL.
                //await Navigation.PushAsync(new MapPage(title, longitude, lat));
            }
            catch (RuntimeBinderException)
            {
                await DisplayAlert("Alert", "No valid GPS coordinates found for this marker", "OK");
            }
            catch (JsonReaderException e)
            {
                // Console.WriteLine("Exception: " + e.Message);
                //Console.WriteLine("Stack trace: " + e.StackTrace);
                await DisplayAlert("Alert", "Data for this marker is invalid: " + e.Message, "OK");

            }
            catch (InvalidCastException)
            {
                await DisplayAlert("Alert", "GPS coordinates are in invalid format for this marker", "OK");
            }
        }
        */

    }
}


text:
package cloudconfig

import (
	"fmt"

	"gopkg.in/urfave/cli.v2"
	"gopkg.in/yaml.v2"

	"github.com/enaml-ops/enaml"
	"github.com/enaml-ops/enaml/cloudproperties/aws"
	"github.com/enaml-ops/omg-cli/plugins/cloudconfigs"
	"github.com/enaml-ops/omg-cli/plugins/cloudconfigs/aws/cloud-config/generated"
)

type AWSCloudConfig struct {
	Context *cli.Context
}

type AZCloudProperties struct {
	AvailabiltyZone string `yaml:"availability_zone"`
}

func NewAWSCloudConfig(c *cli.Context) cloudconfigs.CloudConfigProvider {

	provider := &AWSCloudConfig{
		Context: c,
	}
	return provider
}

func (c *AWSCloudConfig) CreateAZs() ([]enaml.AZ, error) {
	azNames := c.Context.StringSlice("az")
	availablityZones := c.Context.StringSlice("aws-availablity-zone")
	if len(azNames) != len(availablityZones) {
		return nil, fmt.Errorf("you must specify one --aws-availability-zone flag for each --az flag")
	}

	azs := []enaml.AZ{}
	for i, azName := range azNames {
		az := enaml.AZ{
			Name: azName,
			CloudProperties: AZCloudProperties{
				AvailabiltyZone: availablityZones[i],
			},
		}
		azs = append(azs, az)
	}
	return azs, nil
}

/*func NewAWSCloudConfig(region string, securityGroupList []string, subnets []SubnetBucket) (awsCloudConfig *enaml.CloudConfigManifest) {
	if err := validateFlags(region, subnets, securityGroupList); err != nil {
		lo.G.Error(err)
		return
	}
	DefaultSecurityGroups = securityGroupList
	Region = region

	awsCloudConfig = &enaml.CloudConfigManifest{}
	AddAZs(awsCloudConfig, subnets)
	AddDisk(awsCloudConfig)
	AddNetwork(awsCloudConfig, subnets)
	AddVMTypes(awsCloudConfig)

	for _, azname := range subnets {
		AddCompilation(awsCloudConfig, azname.BoshAZName, MediumVMName, PrivateNetworkName)
		break
	}
	return
}*/

func (c *AWSCloudConfig) CreateCompilation() (*enaml.Compilation, error) {
	return cloudconfigs.CreateCompilation(c.Context)
}

func (c *AWSCloudConfig) CreateNetworks() ([]enaml.DeploymentNetwork, error) {
	networks, err := cloudconfigs.CreateNetworks(c.Context, c.validateCloudProperties, c.networkCloudProperties)
	return networks, err
}

func (c *AWSCloudConfig) networkCloudProperties(i, index int) interface{} {
	networkNames := c.Context.StringSlice(fmt.Sprintf("aws-subnet-name-%d", i))
	securityGroupNames := c.Context.StringSlice(fmt.Sprintf("aws-security-group-%d", i))
	return awscloudproperties.Network{
		Subnet:         networkNames[index],
		SecurityGroups: securityGroupNames,
	}
}

func (c *AWSCloudConfig) validateCloudProperties(length, i int) error {
	return cloudconfigs.CheckRequiredLength(length, i, c.Context, "aws-subnet-name-%d")
}

func (c *AWSCloudConfig) CreateVMTypes() ([]enaml.VMType, error) {

	var vmTypes []enaml.VMType
	if fileBytes, err := generated.Asset("files/vm_types.yml"); err == nil {
		if err = yaml.Unmarshal(fileBytes, &vmTypes); err == nil {
			return vmTypes, nil
		} else {
			return nil, err
		}
	} else {
		return nil, err
	}
}

func (c *AWSCloudConfig) CreateDiskTypes() ([]enaml.DiskType, error) {
	var diskTypes []enaml.DiskType
	if fileBytes, err := generated.Asset("files/disk_types.yml"); err == nil {
		if err = yaml.Unmarshal(fileBytes, &diskTypes); err == nil {
			return diskTypes, nil
		} else {
			return nil, err
		}
	} else {
		return nil, err
	}
}


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/base/testing_profile.h"

#include <memory>
#include <utility>

#include "base/base_paths.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/test_file_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/autocomplete/in_memory_url_index_factory.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/background_fetch/background_fetch_delegate_factory.h"
#include "chrome/browser/background_fetch/background_fetch_delegate_impl.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h"
#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_factory.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/history/history_service_factory.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/schema_registry_service.h"
#include "chrome/browser/policy/schema_registry_service_builder.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/prefs/pref_service_syncable_util.h"
#include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
#include "chrome/browser/profiles/profile_key.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/storage_partition_descriptor.h"
#include "chrome/browser/search_engines/template_url_fetcher_factory.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/signin_util.h"
#include "chrome/browser/ssl/stateful_ssl_host_state_delegate_factory.h"
#include "chrome/browser/transition_manager/full_browser_transition_manager.h"
#include "chrome/browser/ui/read_later/reading_list_model_factory.h"
#include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h"
#include "chrome/browser/web_data_service_factory.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/testing_profile_key.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/history/core/browser/history_service.h"
#include "components/history/core/test/history_service_test_util.h"
#include "components/keyed_service/core/refcounted_keyed_service.h"
#include "components/keyed_service/core/simple_factory_key.h"
#include "components/keyed_service/core/simple_key_map.h"
#include "components/leveldb_proto/public/proto_database_provider.h"
#include "components/omnibox/browser/autocomplete_classifier.h"
#include "components/omnibox/browser/history_index_restore_observer.h"
#include "components/omnibox/browser/in_memory_url_index.h"
#include "components/policy/core/common/cloud/cloud_external_data_manager.h"
#include "components/policy/core/common/cloud/mock_user_cloud_policy_store.h"
#include "components/policy/core/common/cloud/user_cloud_policy_manager.h"
#include "components/policy/core/common/configuration_policy_provider.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/core/common/policy_service_impl.h"
#include "components/policy/core/common/schema.h"
#include "components/prefs/pref_notifier_impl.h"
#include "components/prefs/testing_pref_store.h"
#include "components/profile_metrics/browser_profile_type.h"
#include "components/security_interstitials/content/stateful_ssl_host_state_delegate.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/test/model/fake_sync_change_processor.h"
#include "components/sync/test/model/sync_error_factory_mock.h"
#include "components/sync_preferences/pref_service_syncable.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "components/user_prefs/user_prefs.h"
#include "components/webdata_services/web_data_service_wrapper.h"
#include "components/zoom/zoom_event_manager.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/zoom_level_delegate.h"
#include "content/public/test/mock_resource_context.h"
#include "content/public/test/test_utils.h"
#include "extensions/buildflags/buildflags.h"
#include "extensions/common/constants.h"
#include "net/cookies/cookie_store.h"
#include "services/network/test/test_network_connection_tracker.h"
#include "services/service_manager/public/cpp/service.h"
#include "testing/gmock/include/gmock/gmock.h"

#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_special_storage_policy.h"
#include "chrome/browser/extensions/extension_system_factory.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/web_applications/test/fake_web_app_provider.h"
#include "chrome/browser/web_applications/web_app_provider_factory.h"
#include "components/guest_view/browser/guest_view_manager.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_pref_value_map.h"
#include "extensions/browser/extension_pref_value_map_factory.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_prefs_factory.h"
#include "extensions/browser/extension_prefs_observer.h"
#include "extensions/browser/extension_system.h"
#endif

#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/components/account_manager/account_manager_factory.h"
#include "chrome/browser/ash/arc/session/arc_service_launcher.h"
#include "chrome/browser/ash/net/delay_network_call.h"
#include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h"
#include "chrome/browser/ash/settings/cros_settings.h"
#include "components/account_manager_core/chromeos/account_manager.h"
#endif

#if BUILDFLAG(IS_CHROMEOS_LACROS)
#include "chromeos/lacros/lacros_service.h"
#include "chromeos/lacros/lacros_test_helper.h"
#endif

#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#include "chrome/browser/supervised_user/supervised_user_settings_service.h"
#include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
#endif

using base::Time;
using content::BrowserThread;
using content::DownloadManagerDelegate;
using testing::NiceMock;
using testing::Return;

namespace {

void TestProfileErrorCallback(WebDataServiceWrapper::ErrorType error_type,
                              sql::InitStatus status,
                              const std::string& diagnostics) {
  NOTREACHED();
}

std::unique_ptr<KeyedService> BuildWebDataService(
    content::BrowserContext* context) {
  const base::FilePath& context_path = context->GetPath();
  return std::make_unique<WebDataServiceWrapper>(
      context_path, g_browser_process->GetApplicationLocale(),
      content::GetUIThreadTaskRunner({}),
      base::BindRepeating(&TestProfileErrorCallback));
}

std::unique_ptr<KeyedService> BuildPersonalDataManagerInstanceFor(
    content::BrowserContext* context) {
  return std::unique_ptr<KeyedService>(
      autofill::PersonalDataManagerFactory::BuildPersonalDataManager(context));
}

}  // namespace

// static
const char TestingProfile::kDefaultProfileUserName[] = "testing_profile";

// static
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Must be kept in sync with
// `ChromeBrowserMainPartsAsh::PreEarlyInitialization`.
const char TestingProfile::kTestUserProfileDir[] = "test-user";
#else
const char TestingProfile::kTestUserProfileDir[] = "Default";
#endif

TestingProfile::TestingProfile() : TestingProfile(base::FilePath()) {}

TestingProfile::TestingProfile(const base::FilePath& path)
    : TestingProfile(path, nullptr) {}

TestingProfile::TestingProfile(const base::FilePath& path, Delegate* delegate)
    : profile_path_(path), delegate_(delegate) {
  if (profile_path_.empty()) {
    profile_path_ = base::CreateUniqueTempDirectoryScopedToTest();
  }
  Init(/*is_supervised_profile=*/false);
  if (delegate_) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::BindOnce(&TestingProfile::FinishInit, base::Unretained(this)));
  } else {
    FinishInit();
  }
}

TestingProfile::TestingProfile(
    const base::FilePath& path,
    Delegate* delegate,
#if BUILDFLAG(ENABLE_EXTENSIONS)
    scoped_refptr<ExtensionSpecialStoragePolicy> extension_policy,
#endif
    std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs,
    TestingProfile* parent,
    bool guest_session,
    bool allows_browser_windows,
    bool is_new_profile,
    bool is_supervised_profile,
#if BUILDFLAG(IS_CHROMEOS_LACROS)
    bool is_main_profile,
#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)
#if BUILDFLAG(IS_CHROMEOS_ASH)
    std::unique_ptr<policy::UserCloudPolicyManagerAsh> policy_manager,
#else
    std::unique_ptr<policy::UserCloudPolicyManager> policy_manager,
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
    std::unique_ptr<policy::PolicyService> policy_service,
    TestingFactories testing_factories,
    const std::string& profile_name,
    absl::optional<bool> override_policy_connector_is_managed,
    absl::optional<OTRProfileID> otr_profile_id,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : prefs_(std::move(prefs)),
      original_profile_(parent),
      guest_session_(guest_session),
      allows_browser_windows_(allows_browser_windows),
      is_new_profile_(is_new_profile),
#if BUILDFLAG(IS_CHROMEOS_LACROS)
      is_main_profile_(is_main_profile),
#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)
#if BUILDFLAG(ENABLE_EXTENSIONS)
      extension_special_storage_policy_(extension_policy),
#endif
      profile_path_(path),
      user_cloud_policy_manager_(std::move(policy_manager)),
      delegate_(delegate),
      profile_name_(profile_name),
      override_policy_connector_is_managed_(
          override_policy_connector_is_managed),
      otr_profile_id_(otr_profile_id),
      policy_service_(std::move(policy_service)),
      url_loader_factory_(url_loader_factory) {
  if (parent)
    parent->SetOffTheRecordProfile(std::unique_ptr<Profile>(this));

  // Only OffTheRecord profiles have an OTRProfileID.
  DCHECK(!parent || otr_profile_id_.has_value());

  // If no profile path was supplied, create one.
  if (profile_path_.empty()) {
    profile_path_ = base::CreateUniqueTempDirectoryScopedToTest();
  }

  // Set any testing factories prior to initializing the services.
  for (TestingFactories::value_type& pair : testing_factories)
    pair.first->SetTestingFactory(this, std::move(pair.second));
  testing_factories.clear();

  Init(is_supervised_profile);

  // If caller supplied a delegate, delay the FinishInit invocation until other
  // tasks have run.
  // TODO(atwilson): See if this is still required once we convert the current
  // users of the constructor that takes a Delegate* param.
  if (delegate_) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::BindOnce(&TestingProfile::FinishInit, base::Unretained(this)));
  } else {
    FinishInit();
  }
}

void TestingProfile::Init(bool is_supervised_profile) {
  base::ScopedAllowBlockingForTesting allow_blocking;
  // If threads have been initialized, we should be on the UI thread.
  DCHECK(!content::BrowserThread::IsThreadInitialized(
             content::BrowserThread::UI) ||
         content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

  InitializeProfileType();

  if (IsOffTheRecord()) {
    key_ = std::make_unique<TestingProfileKey>(
        this, original_profile_->GetPath(), original_profile_->GetProfileKey());
  } else {
    key_ = std::make_unique<TestingProfileKey>(this, profile_path_);
  }

#if BUILDFLAG(IS_ANDROID)
  signin::SetUpMockAccountManagerFacade();
#endif

#if BUILDFLAG(IS_CHROMEOS_LACROS)
  // `LacrosService` has to be initialized before
  // `EnsureBrowserContextKeyedServiceFactoriesBuilt` call.
  if (!chromeos::LacrosService::Get()) {
    lacros_service_test_helper_ =
        std::make_unique<chromeos::ScopedLacrosServiceTestHelper>();
  }
#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)

  // Normally this would happen during browser startup, but for tests
  // we need to trigger creation of Profile-related services.
  ChromeBrowserMainExtraPartsProfiles::
      EnsureBrowserContextKeyedServiceFactoriesBuilt();

#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  if (!IsOffTheRecord()) {
    SupervisedUserSettingsService* settings_service =
        SupervisedUserSettingsServiceFactory::GetForKey(key_.get());
    supervised_user_pref_store_ = new TestingPrefStore();
    settings_service->Init(supervised_user_pref_store_.get());
    settings_service->MergeDataAndStartSyncing(
        syncer::SUPERVISED_USER_SETTINGS, syncer::SyncDataList(),
        std::unique_ptr<syncer::SyncChangeProcessor>(
            new syncer::FakeSyncChangeProcessor),
        std::unique_ptr<syncer::SyncErrorFactory>(
            new syncer::SyncErrorFactoryMock));

    supervised_user_pref_store_->SetInitializationCompleted();
  }
#endif

  if (prefs_.get())
    user_prefs::UserPrefs::Set(this, prefs_.get());
  else if (IsOffTheRecord())
    CreateIncognitoPrefService();
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  else if (is_supervised_profile)
    CreatePrefServiceForSupervisedUser();
#endif
  else
    CreateTestingPrefService();

  if (is_supervised_profile)
    SetIsSupervisedProfile();

  key_->SetPrefs(prefs_.get());
  SimpleKeyMap::GetInstance()->Associate(this, key_.get());

  if (!base::PathExists(profile_path_))
    base::CreateDirectory(profile_path_);

#if BUILDFLAG(IS_CHROMEOS_ASH)
  // Initialize |account_manager::AccountManager|.
  auto* factory =
      g_browser_process->platform_part()->GetAccountManagerFactory();
  auto* account_manager = factory->GetAccountManager(profile_path_.value());
  account_manager::AccountManager::DelayNetworkCallRunner
      immediate_callback_runner = base::BindRepeating(
          [](base::OnceClosure closure) -> void { std::move(closure).Run(); });
  account_manager->Initialize(profile_path_, GetURLLoaderFactory(),
                              immediate_callback_runner);
  account_manager->SetPrefService(GetPrefs());
  if (!ash::CrosSettings::IsInitialized()) {
    scoped_cros_settings_test_helper_ =
        std::make_unique<ash::ScopedCrosSettingsTestHelper>();
  }
  arc::ArcServiceLauncher* launcher = arc::ArcServiceLauncher::Get();
  if (launcher)
    launcher->MaybeSetProfile(this);
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

  autofill::PersonalDataManagerFactory::GetInstance()->SetTestingFactory(
      this, base::BindRepeating(&BuildPersonalDataManagerInstanceFor));

  ReadingListModelFactory::GetInstance()->SetTestingFactory(
      this, ReadingListModelFactory::GetDefaultFactoryForTesting());

  // TODO(joaodasilva): remove this once this PKS isn't created in ProfileImpl
  // anymore, after converting the PrefService to a PKS. Until then it must
  // be associated with a TestingProfile too.
  if (!IsOffTheRecord())
    CreateProfilePolicyConnector();

  extensions_path_ = profile_path_.AppendASCII("Extensions");

#if BUILDFLAG(ENABLE_EXTENSIONS)
  // Note that the GetPrefs() creates a TestingPrefService, therefore
  // the extension controlled pref values set in ExtensionPrefs
  // are not reflected in the pref service. One would need to
  // inject a new ExtensionPrefStore(extension_pref_value_map, false).
  bool extensions_disabled = base::CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kDisableExtensions);
  std::unique_ptr<extensions::ExtensionPrefs> extension_prefs(
      extensions::ExtensionPrefs::Create(
          this, GetPrefs(), extensions_path_,
          ExtensionPrefValueMapFactory::GetForBrowserContext(this),
          extensions_disabled,
          std::vector<extensions::EarlyExtensionPrefsObserver*>()));
  extensions::ExtensionPrefsFactory::GetInstance()->SetInstanceForTesting(
      this, std::move(extension_prefs));

  extensions::ExtensionSystemFactory::GetInstance()->SetTestingFactory(
      this, base::BindRepeating(&extensions::TestExtensionSystem::Build));

  extensions::EventRouterFactory::GetInstance()->SetTestingFactory(
      this, BrowserContextKeyedServiceFactory::TestingFactory());

  web_app::WebAppProviderFactory::GetInstance()->SetTestingFactory(
      this, base::BindRepeating(&web_app::FakeWebAppProvider::BuildDefault));
#endif

  // Prefs for incognito profiles are set in CreateIncognitoPrefService().
  SimpleFactoryKey* key = GetProfileKey();
  if (!IsOffTheRecord()) {
    DCHECK(!original_profile_);
    user_prefs::PrefRegistrySyncable* pref_registry =
        static_cast<user_prefs::PrefRegistrySyncable*>(
            prefs_->DeprecatedGetPrefRegistry());
    simple_dependency_manager_->RegisterProfilePrefsForServices(pref_registry);
    browser_context_dependency_manager_->RegisterProfilePrefsForServices(
        pref_registry);
  }

  FullBrowserTransitionManager::Get()->OnProfileCreated(this);

  simple_dependency_manager_->CreateServicesForTest(key);
  browser_context_dependency_manager_->CreateBrowserContextServicesForTest(
      this);
}

void TestingProfile::InitializeProfileType() {
  if (guest_session_) {
    profile_metrics::SetBrowserProfileType(
        this, profile_metrics::BrowserProfileType::kGuest);
    return;
  }

  bool is_system = false;
  if (IsOffTheRecord()) {
    is_system = original_profile_->IsSystemProfile();
  } else {
    ProfileManager* profile_manager = g_browser_process->profile_manager();
    if (profile_manager) {
      is_system = (profile_path_ == profile_manager->GetSystemProfilePath());
    }
  }
  if (is_system) {
    profile_metrics::SetBrowserProfileType(
        this, profile_metrics::BrowserProfileType::kSystem);
    return;
  }

  if (IsOffTheRecord()) {
    profile_metrics::SetBrowserProfileType(
        this,
        (otr_profile_id_ == OTRProfileID::PrimaryID())
            ? profile_metrics::BrowserProfileType::kIncognito
            : profile_metrics::BrowserProfileType::kOtherOffTheRecordProfile);
    return;
  }

  profile_metrics::SetBrowserProfileType(
      this, profile_metrics::BrowserProfileType::kRegular);
}

void TestingProfile::FinishInit() {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  if (profile_manager)
    profile_manager->InitProfileUserPrefs(this);

  if (original_profile_) {
    DCHECK(!delegate_) << "Not expecting a delegate for an OTR profile";
    original_profile_->NotifyOffTheRecordProfileCreated(this);
    return;
  }

  if (delegate_) {
    delegate_->OnProfileCreationFinished(this, CREATE_MODE_ASYNCHRONOUS, true,
                                         false);
  } else {
    // It is the role of the delegate to ensure that the signout allowed is
    // properly updated after the profile is create is initialized.
    // For testing profiles that do not have a delegate, the signout allowed
    // must be initialized when the testing profile finishes its
    // initialization.
    signin_util::EnsureUserSignoutAllowedIsInitializedForProfile(this);
  }
}

TestingProfile::~TestingProfile() {
  if (!profile_destruction_callback_.is_null())
    std::move(profile_destruction_callback_).Run();

  // If this profile owns OffTheRecord profiles, tear them down first.
  otr_profiles_.clear();

  // Any objects holding live URLFetchers should be deleted before teardown.
  TemplateURLFetcherFactory::ShutdownForProfile(this);

  MaybeSendDestroyedNotification();

  FullBrowserTransitionManager::Get()->OnProfileDestroyed(this);

  // The SimpleDependencyManager should always be passed after the
  // BrowserContextDependencyManager. This is because the KeyedService
  // instances in the BrowserContextDependencyManager's dependency graph can
  // depend on the ones in the SimpleDependencyManager's graph.
  DependencyManager::PerformInterlockedTwoPhaseShutdown(
      browser_context_dependency_manager_, this, simple_dependency_manager_,
      key_.get());
  key_.reset();

  SimpleKeyMap::GetInstance()->Dissociate(this);

  if (profile_policy_connector_)
    profile_policy_connector_->Shutdown();

  if (user_cloud_policy_manager_)
    user_cloud_policy_manager_->Shutdown();

  if (host_content_settings_map_.get())
    host_content_settings_map_->ShutdownOnUIThread();

  // Make sure SharedProtoDatabase doesn't post delayed tasks anymore.
  ForEachStoragePartition(
      base::BindRepeating([](content::StoragePartition* storage_partition) {
        if (auto* provider =
                storage_partition->GetProtoDatabaseProviderForTesting()) {
          provider->SetSharedDBDeleteObsoleteDelayForTesting(base::TimeDelta());
        }
      }));

  // Shutdown storage partitions before we post a task to delete
  // the resource context.
  ShutdownStoragePartitions();

  // Failing a post == leaks == heapcheck failure. Make that an immediate test
  // failure.
  if (resource_context_) {
    CHECK(BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
                                    resource_context_.get()));
    resource_context_ = nullptr;
    content::RunAllPendingInMessageLoop(BrowserThread::IO);
  }
}

void TestingProfile::CreateWebDataService() {
  WebDataServiceFactory::GetInstance()->SetTestingFactory(
      this, base::BindRepeating(&BuildWebDataService));
}

void TestingProfile::SetGuestSession(bool guest) {
  guest_session_ = guest;
  InitializeProfileType();
}

void TestingProfile::SetIsNewProfile(bool is_new_profile) {
  is_new_profile_ = is_new_profile;
}

base::FilePath TestingProfile::GetPath() {
  return profile_path_;
}

base::FilePath TestingProfile::GetPath() const {
  return profile_path_;
}

base::Time TestingProfile::GetCreationTime() const {
  return start_time_;
}

std::unique_ptr<content::ZoomLevelDelegate>
TestingProfile::CreateZoomLevelDelegate(const base::FilePath& partition_path) {
  return std::make_unique<ChromeZoomLevelPrefs>(
      GetPrefs(), GetPath(), partition_path,
      zoom::ZoomEventManager::GetForBrowserContext(this)->GetWeakPtr());
}

scoped_refptr<base::SequencedTaskRunner> TestingProfile::GetIOTaskRunner() {
  return base::ThreadTaskRunnerHandle::Get();
}

sync_preferences::TestingPrefServiceSyncable*
TestingProfile::GetTestingPrefService() {
  DCHECK(prefs_);
  DCHECK(testing_prefs_);
  return testing_prefs_;
}

TestingProfile* TestingProfile::AsTestingProfile() {
  return this;
}

std::string TestingProfile::GetProfileUserName() const {
  return profile_name_;
}

bool TestingProfile::IsOffTheRecord() {
  return original_profile_;
}

bool TestingProfile::IsOffTheRecord() const {
  return original_profile_;
}

#if BUILDFLAG(IS_CHROMEOS_LACROS)
bool TestingProfile::IsMainProfile() const {
  return is_main_profile_;
}

void TestingProfile::SetIsMainProfile(bool is_main_profile) {
  is_main_profile_ = is_main_profile;
}

#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)

const Profile::OTRProfileID& TestingProfile::GetOTRProfileID() const {
  DCHECK(IsOffTheRecord());
  return *otr_profile_id_;
}

void TestingProfile::SetOffTheRecordProfile(
    std::unique_ptr<Profile> otr_profile) {
  DCHECK(otr_profile);
  DCHECK(!IsOffTheRecord());
  DCHECK_EQ(this, otr_profile->GetOriginalProfile());
  otr_profiles_[otr_profile->GetOTRProfileID()] = std::move(otr_profile);
}

Profile* TestingProfile::GetOffTheRecordProfile(
    const OTRProfileID& otr_profile_id,
    bool create_if_needed) {
  if (IsOffTheRecord()) {
    return original_profile_->GetOffTheRecordProfile(otr_profile_id,
                                                     create_if_needed);
  }

  if (!HasOffTheRecordProfile(otr_profile_id)) {
    if (!create_if_needed)
      return nullptr;

    TestingProfile::Builder builder;
    if (IsGuestSession() && otr_profile_id == OTRProfileID::PrimaryID())
      builder.SetGuestSession();
    builder.SetPath(GetPath());
    builder.BuildOffTheRecord(this, otr_profile_id);
    DCHECK(HasOffTheRecordProfile(otr_profile_id));
  }

  return otr_profiles_[otr_profile_id].get();
}

std::vector<Profile*> TestingProfile::GetAllOffTheRecordProfiles() {
  std::vector<Profile*> otr_profiles;

  for (auto& otr : otr_profiles_)
    otr_profiles.push_back(otr.second.get());

  return otr_profiles;
}

void TestingProfile::DestroyOffTheRecordProfile(Profile* otr_profile) {
  if (HasOffTheRecordProfile(otr_profile->GetOTRProfileID()))
    otr_profiles_.erase(otr_profile->GetOTRProfileID());
}

bool TestingProfile::HasOffTheRecordProfile(
    const OTRProfileID& otr_profile_id) {
  return base::Contains(otr_profiles_, otr_profile_id);
}

bool TestingProfile::HasAnyOffTheRecordProfile() {
  return !otr_profiles_.empty();
}

Profile* TestingProfile::GetOriginalProfile() {
  if (original_profile_)
    return original_profile_;
  return this;
}

const Profile* TestingProfile::GetOriginalProfile() const {
  if (original_profile_)
    return original_profile_;
  return this;
}

void TestingProfile::SetIsSupervisedProfile() {
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  GetPrefs()->SetString(prefs::kSupervisedUserId,
                        supervised_users::kChildAccountSUID);
#else
  NOTREACHED() << "Supervised users are not enabled";
#endif
}

bool TestingProfile::IsChild() const {
#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
  return GetPrefs()->GetString(prefs::kSupervisedUserId) ==
         supervised_users::kChildAccountSUID;
#else
  return false;
#endif
}

bool TestingProfile::AllowsBrowserWindows() const {
  return allows_browser_windows_;
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
void TestingProfile::SetExtensionSpecialStoragePolicy(
    scoped_refptr<ExtensionSpecialStoragePolicy>
        extension_special_storage_policy) {
  extension_special_storage_policy_ =
      std::move(extension_special_storage_policy);
}
#endif

ExtensionSpecialStoragePolicy*
TestingProfile::GetExtensionSpecialStoragePolicy() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  if (!extension_special_storage_policy_.get()) {
    extension_special_storage_policy_ =
        base::MakeRefCounted<ExtensionSpecialStoragePolicy>(nullptr);
  }
  return extension_special_storage_policy_.get();
#else
  return nullptr;
#endif
}

void TestingProfile::CreateTestingPrefService() {
  DCHECK(!prefs_.get());
  testing_prefs_ = new sync_preferences::TestingPrefServiceSyncable();
  prefs_.reset(testing_prefs_);
  user_prefs::UserPrefs::Set(this, prefs_.get());
  RegisterUserProfilePrefs(testing_prefs_->registry());
}

#if BUILDFLAG(ENABLE_SUPERVISED_USERS)
void TestingProfile::CreatePrefServiceForSupervisedUser() {
  DCHECK(!prefs_.get());

  // Construct testing_prefs_ by hand to add the supervised user pref store.
  testing_prefs_ = new sync_preferences::TestingPrefServiceSyncable(
      /*managed_prefs=*/new TestingPrefStore, supervised_user_pref_store_,
      /*extension_prefs=*/new TestingPrefStore,
      /*standalone_browser_prefs=*/new TestingPrefStore,
      /*user_prefs=*/new TestingPrefStore,
      /*recommended_prefs=*/new TestingPrefStore,
      new user_prefs::PrefRegistrySyncable, new PrefNotifierImpl);
  prefs_.reset(testing_prefs_);
  user_prefs::UserPrefs::Set(this, prefs_.get());
  RegisterUserProfilePrefs(testing_prefs_->registry());
}
#endif  // BUILDFLAG(ENABLE_SUPERVISED_USERS)

void TestingProfile::CreateIncognitoPrefService() {
  DCHECK(original_profile_);
  DCHECK(!testing_prefs_);
  // Simplified version of ProfileImpl::GetOffTheRecordPrefs(). Note this
  // leaves testing_prefs_ unset.
  prefs_ = CreateIncognitoPrefServiceSyncable(original_profile_->prefs_.get(),
                                              nullptr);
  user_prefs::UserPrefs::Set(this, prefs_.get());
}

void TestingProfile::CreateProfilePolicyConnector() {
  schema_registry_service_ =
      BuildSchemaRegistryServiceForProfile(this, policy::Schema(), nullptr);

  if (!policy_service_) {
    std::vector<policy::ConfigurationPolicyProvider*> providers;
    std::unique_ptr<policy::PolicyServiceImpl> policy_service =
        std::make_unique<policy::PolicyServiceImpl>(std::move(providers));
    policy_service_ = std::move(policy_service);
  }
  profile_policy_connector_ =
      std::make_unique<policy::ProfilePolicyConnector>();
  profile_policy_connector_->InitForTesting(std::move(policy_service_));
  if (override_policy_connector_is_managed_.has_value())
    profile_policy_connector_->OverrideIsManagedForTesting(
        override_policy_connector_is_managed_.value());
}

PrefService* TestingProfile::GetPrefs() {
  DCHECK(prefs_);
  return prefs_.get();
}

const PrefService* TestingProfile::GetPrefs() const {
  DCHECK(prefs_);
  return prefs_.get();
}

ChromeZoomLevelPrefs* TestingProfile::GetZoomLevelPrefs() {
  return static_cast<ChromeZoomLevelPrefs*>(
      GetDefaultStoragePartition()->GetZoomLevelDelegate());
}

DownloadManagerDelegate* TestingProfile::GetDownloadManagerDelegate() {
  return nullptr;
}

scoped_refptr<network::SharedURLLoaderFactory>
TestingProfile::GetURLLoaderFactory() {
  return url_loader_factory_;
}

content::ResourceContext* TestingProfile::GetResourceContext() {
  if (!resource_context_)
    resource_context_ = new content::MockResourceContext();
  return resource_context_;
}

content::BrowserPluginGuestManager* TestingProfile::GetGuestManager() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  return guest_view::GuestViewManager::FromBrowserContext(this);
#else
  return nullptr;
#endif
}

content::PlatformNotificationService*
TestingProfile::GetPlatformNotificationService() {
  return nullptr;
}

content::PushMessagingService* TestingProfile::GetPushMessagingService() {
  return nullptr;
}

content::StorageNotificationService*
TestingProfile::GetStorageNotificationService() {
  return nullptr;
}

bool TestingProfile::IsSameOrParent(Profile* profile) {
  if (this == profile)
    return true;
  return profile && profile->GetOriginalProfile() == this;
}

base::Time TestingProfile::GetStartTime() const {
  return start_time_;
}

ProfileKey* TestingProfile::GetProfileKey() const {
  DCHECK(key_);
  return key_.get();
}

policy::SchemaRegistryService*
TestingProfile::GetPolicySchemaRegistryService() {
  return schema_registry_service_.get();
}

#if BUILDFLAG(IS_CHROMEOS_ASH)
policy::UserCloudPolicyManagerAsh*
TestingProfile::GetUserCloudPolicyManagerAsh() {
  return user_cloud_policy_manager_.get();
}

policy::ActiveDirectoryPolicyManager*
TestingProfile::GetActiveDirectoryPolicyManager() {
  return nullptr;
}
#else
policy::UserCloudPolicyManager* TestingProfile::GetUserCloudPolicyManager() {
  return user_cloud_policy_manager_.get();
}
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

policy::ProfilePolicyConnector* TestingProfile::GetProfilePolicyConnector() {
  return profile_policy_connector_.get();
}

const policy::ProfilePolicyConnector*
TestingProfile::GetProfilePolicyConnector() const {
  return profile_policy_connector_.get();
}

base::FilePath TestingProfile::last_selected_directory() {
  return last_selected_directory_;
}

void TestingProfile::set_last_selected_directory(const base::FilePath& path) {
  last_selected_directory_ = path;
}

#if BUILDFLAG(IS_CHROMEOS_ASH)
void TestingProfile::ChangeAppLocale(const std::string& locale,
                                     AppLocaleChangedVia via) {
  requested_locale_ = locale;
}

ash::ScopedCrosSettingsTestHelper*
TestingProfile::ScopedCrosSettingsTestHelper() {
  return scoped_cros_settings_test_helper_.get();
}
#endif

void TestingProfile::BlockUntilHistoryProcessesPendingRequests() {
  history::HistoryService* history_service =
      HistoryServiceFactory::GetForProfile(this,
                                           ServiceAccessType::EXPLICIT_ACCESS);
  DCHECK(history_service);
  history::BlockUntilHistoryProcessesPendingRequests(history_service);
}

GURL TestingProfile::GetHomePage() {
  return GURL(chrome::kChromeUINewTabURL);
}

void TestingProfile::SetCreationTimeForTesting(base::Time creation_time) {
  start_time_ = creation_time;
}

bool TestingProfile::IsSignedIn() {
  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(this);
  return identity_manager &&
         identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSync);
}

storage::SpecialStoragePolicy* TestingProfile::GetSpecialStoragePolicy() {
#if BUILDFLAG(ENABLE_EXTENSIONS)
  return GetExtensionSpecialStoragePolicy();
#else
  return nullptr;
#endif
}

content::SSLHostStateDelegate* TestingProfile::GetSSLHostStateDelegate() {
  return StatefulSSLHostStateDelegateFactory::GetForProfile(this);
}

content::PermissionControllerDelegate*
TestingProfile::GetPermissionControllerDelegate() {
  return nullptr;
}

content::ClientHintsControllerDelegate*
TestingProfile::GetClientHintsControllerDelegate() {
  return nullptr;
}

content::BackgroundFetchDelegate* TestingProfile::GetBackgroundFetchDelegate() {
  return BackgroundFetchDelegateFactory::GetForProfile(this);
}

content::BackgroundSyncController*
TestingProfile::GetBackgroundSyncController() {
  return nullptr;
}

content::BrowsingDataRemoverDelegate*
TestingProfile::GetBrowsingDataRemoverDelegate() {
  // TestingProfile contains a real BrowsingDataRemover from BrowserContext.
  // Since ChromeBrowsingDataRemoverDelegate is just a Chrome-specific extension
  // of BrowsingDataRemover, we include it here for consistency.
  //
  // This is not a problem, since ChromeBrowsingDataRemoverDelegate mostly
  // just serves as an interface to deletion mechanisms of various browsing
  // data backends, which are already mocked if considered too heavy-weight
  // for TestingProfile.
  return ChromeBrowsingDataRemoverDelegateFactory::GetForProfile(this);
}

bool TestingProfile::WasCreatedByVersionOrLater(const std::string& version) {
  return true;
}

bool TestingProfile::IsGuestSession() const {
  return profile_metrics::GetBrowserProfileType(this) ==
         profile_metrics::BrowserProfileType::kGuest;
}

bool TestingProfile::IsNewProfile() const {
  return is_new_profile_;
}

TestingProfile::Builder::Builder() = default;

TestingProfile::Builder::~Builder() = default;

void TestingProfile::Builder::SetPath(const base::FilePath& path) {
  path_ = path;
}

void TestingProfile::Builder::SetDelegate(Delegate* delegate) {
  delegate_ = delegate;
}

#if BUILDFLAG(ENABLE_EXTENSIONS)
void TestingProfile::Builder::SetExtensionSpecialStoragePolicy(
    scoped_refptr<ExtensionSpecialStoragePolicy> policy) {
  extension_policy_ = policy;
}
#endif

void TestingProfile::Builder::SetPrefService(
    std::unique_ptr<sync_preferences::PrefServiceSyncable> prefs) {
  pref_service_ = std::move(prefs);
}

void TestingProfile::Builder::SetGuestSession() {
  guest_session_ = true;
}

void TestingProfile::Builder::DisallowBrowserWindows() {
  allows_browser_windows_ = false;
}

void TestingProfile::Builder::SetIsNewProfile(bool is_new_profile) {
  is_new_profile_ = is_new_profile;
}

void TestingProfile::Builder::SetIsSupervisedProfile() {
  is_supervised_profile_ = true;
}

#if BUILDFLAG(IS_CHROMEOS_LACROS)
void TestingProfile::Builder::SetIsMainProfile(bool is_main_profile) {
  is_main_profile_ = is_main_profile;
}
#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)

#if BUILDFLAG(IS_CHROMEOS_ASH)
void TestingProfile::Builder::SetUserCloudPolicyManagerAsh(
    std::unique_ptr<policy::UserCloudPolicyManagerAsh>
        user_cloud_policy_manager) {
  user_cloud_policy_manager_ = std::move(user_cloud_policy_manager);
}
#else
void TestingProfile::Builder::SetUserCloudPolicyManager(
    std::unique_ptr<policy::UserCloudPolicyManager> user_cloud_policy_manager) {
  user_cloud_policy_manager_ = std::move(user_cloud_policy_manager);
}
#endif

void TestingProfile::Builder::SetPolicyService(
    std::unique_ptr<policy::PolicyService> policy_service) {
  policy_service_ = std::move(policy_service);
}

void TestingProfile::Builder::SetProfileName(const std::string& profile_name) {
  profile_name_ = profile_name;
}

void TestingProfile::Builder::SetSharedURLLoaderFactory(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
  url_loader_factory_ = url_loader_factory;
}

void TestingProfile::Builder::OverridePolicyConnectorIsManagedForTesting(
    bool is_managed) {
  override_policy_connector_is_managed_ = is_managed;
}

void TestingProfile::Builder::AddTestingFactory(
    BrowserContextKeyedServiceFactory* service_factory,
    BrowserContextKeyedServiceFactory::TestingFactory testing_factory) {
  testing_factories_.emplace_back(service_factory, std::move(testing_factory));
}

void TestingProfile::Builder::AddTestingFactories(
    const TestingFactories& testing_factories) {
  testing_factories_.insert(testing_factories_.end(), testing_factories.begin(),
                            testing_factories.end());
}

std::unique_ptr<TestingProfile> TestingProfile::Builder::Build() {
  DCHECK(!build_called_);
  build_called_ = true;

  return std::make_unique<TestingProfile>(
      path_, delegate_,
#if BUILDFLAG(ENABLE_EXTENSIONS)
      extension_policy_,
#endif
      std::move(pref_service_), nullptr, guest_session_,
      allows_browser_windows_, is_new_profile_, is_supervised_profile_,
#if BUILDFLAG(IS_CHROMEOS_LACROS)
      is_main_profile_,
#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)
      std::move(user_cloud_policy_manager_), std::move(policy_service_),
      std::move(testing_factories_), profile_name_,
      override_policy_connector_is_managed_, absl::optional<OTRProfileID>(),
      url_loader_factory_);
}

TestingProfile* TestingProfile::Builder::BuildOffTheRecord(
    TestingProfile* original_profile,
    const OTRProfileID& otr_profile_id) {
  DCHECK(!build_called_);
  DCHECK(original_profile);
  build_called_ = true;

  // Note: Owned by |original_profile|.
  return new TestingProfile(
      path_, delegate_,
#if BUILDFLAG(ENABLE_EXTENSIONS)
      extension_policy_,
#endif
      std::move(pref_service_), original_profile, guest_session_,
      allows_browser_windows_, is_new_profile_, is_supervised_profile_,
#if BUILDFLAG(IS_CHROMEOS_LACROS)
      is_main_profile_,
#endif  // BUILDFLAG(IS_CHROMEOS_LACROS)
      std::move(user_cloud_policy_manager_), std::move(policy_service_),
      std::move(testing_factories_), profile_name_,
      override_policy_connector_is_managed_,
      absl::optional<OTRProfileID>(otr_profile_id), url_loader_factory_);
}

TestingProfile* TestingProfile::Builder::BuildIncognito(
    TestingProfile* original_profile) {
  return BuildOffTheRecord(original_profile, OTRProfileID::PrimaryID());
}


text:
<?php

Prado::using("System.Wsat.TWsatARGenerator");

class TWsatHome extends TPage
{

}


text:
<!--
  Copyright 2014 Soichiro Kashima

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<com.lianzong.logistics.app.ui.view.observableviews.TouchInterceptionFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primary"
    android:paddingTop="?attr/actionBarSize">

    <!--
    Padding for ViewPager must be set outside the ViewPager itself
    because with padding, EdgeEffect of ViewPager become strange.
    -->
    <FrameLayout
        android:id="@+id/pager_wrapper"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="@dimen/tab_height">

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white" />

        <include
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            layout="@layout/floating_menus" />
    </FrameLayout>

    <com.lianzong.logistics.app.ui.view.observableviews.SlidingTabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="@dimen/tab_height"
        android:background="@color/primary" />

</com.lianzong.logistics.app.ui.view.observableviews.TouchInterceptionFrameLayout>


text:
#ifndef	__LINUX_USB_ANDROID_H
#define	__LINUX_USB_ANDROID_H

#include <linux/usb/composite.h>

#define MAX_STREAMING_FUNCS 3
#define FUNC_NAME_LEN 10

enum android_pm_qos_state {
	WFI,
	IDLE_PC,
	IDLE_PC_RPM,
	NO_USB_VOTE,
	MAX_VOTES = NO_USB_VOTE,
};

struct android_usb_platform_data {
	int (*update_pid_and_serial_num)(uint32_t, const char *);
	u32 pm_qos_latency[MAX_VOTES];
	u8 usb_core_id;
	char streaming_func[MAX_STREAMING_FUNCS][FUNC_NAME_LEN];
	int  streaming_func_count;
};

#ifndef CONFIG_TARGET_CORE
static inline int f_tcm_init(int (*connect_cb)(bool connect))
{
	/*
	 * Fail bind() not init(). If a function init() returns error
	 * android composite registration would fail.
	 */
	return 0;
}
static inline void f_tcm_exit(void)
{
}
static inline int tcm_bind_config(struct usb_configuration *c)
{
	return -ENODEV;
}
#endif

extern int gport_setup(struct usb_configuration *c);
extern void gport_cleanup(void);
extern int gserial_init_port(int port_num, const char *name,
					const char *port_name);

int acm_port_setup(struct usb_configuration *c);
void acm_port_cleanup(void);
int acm_init_port(int port_num, const char *name);

#endif	/* __LINUX_USB_ANDROID_H */


text:
const { sequelize, models, sync, clear } = require('./common');
const { Customer, Note, Item, ItemType, Order, Audit } = models;

const embed = require('../src/index')(sequelize);
const { mkIncludes, mkInclude } = embed.util.helpers;

/* --- setup --- */

const include = mkIncludes(mkInclude(Order.Notes));
const opts = { reload: { include } };

/* --- tests --- */

describe('misc', () => {
  beforeEach(sync);

  it('shouldn\'t lose pk to pruning if it\'s also the fk', done => {
    Order.create({ name: 'o1' }).then(o =>
      Note.create({ orderId: o.id, body: 'foo'}).then(n =>
        embed.update(Order, { id: o.id }, include, opts).then(pruned => {
          pruned.notes[0].body = 'bar';
          embed.update(Order, pruned, include, opts).then(result => {
            expect(result.notes.length).toBe(1);
            expect(result.notes[0].body).toBe('bar');
            done();
          });
        })));
  });
});


text:
gem 'savon', '~>0.9.1'
require 'savon'

module AdsCommon
  class SavonService
    attr_accessor :headerhandler

    # Creates a new service.
    def initialize(endpoint, namespace)
      if self.class() == AdsCommon::SavonService
        raise NoMethodError, "Tried to instantiate an abstract class"
      end
      @headerhandler = []
      @client = Savon::Client.new do |wsdl|
        wsdl.namespace = namespace
        wsdl.endpoint = endpoint
      end
    end

    private

    # Returns ServiceRegistry for the current service. Has to be overriden.
    def get_service_registry()
      raise NoMethodError, "This methods needs to be overriden"
    end

    # Returns Module for the current service. Has to be overriden.
    def get_module()
      raise NoMethodError, "This methods needs to be overriden"
    end

    # Executes SOAP action specified as a string with given arguments.
    def execute_action(action_name, args)
      args = validate_args(action_name, args)
      response = execute_soap_request(action_name.to_sym, args)
      handle_errors(response)
      return extract_result(response, action_name)
    end

    # Executes the SOAP request with original SOAP name.
    def execute_soap_request(action, args)
      original_action_name =
          get_service_registry.get_method_signature(action)[:original_name]
      original_action_name = action if original_action_name.nil?
      response = @client.request(original_action_name) do |soap|
        set_headers(soap, args)
      end
      return response
    end

    # Validates input parameters to:
    # - add parameter names;
    # - resolve xsi:type where required;
    # - convert some native types to xml.
    def validate_args(action_name, args)
      validated_args = {}
      in_params = get_service_registry.get_method_signature(action_name)[:input]
      in_params.each_with_index do |in_param, index|
        key = in_param[:name]
        value = deep_copy(args[index])
        validated_args[key] = (value.nil?) ? nil :
            validate_arg(value, validated_args, key)
      end
      return validated_args
    end

    # Validates method argument. Runs recursively if hash or array encountered.
    # Also handles some types that need special conversions.
    def validate_arg(arg, parent = nil, key = nil)
      result = case arg
        when Hash then validate_hash_arg(arg, parent, key)
        when Array then arg.map {|item| validate_arg(item, parent, key)}
        when Time then time_to_xml_hash(arg)
        else arg
      end
      return result
    end

    # Validates hash argument recursively. Keeps tracking of correct place
    # for xsi:type and adds is when required.
    def validate_hash_arg(arg, parent = nil, key = nil)
      xsi_type = arg.delete('xsi:type') || arg.delete(:xsi_type)
      if xsi_type
        if parent and key
          add_xsi_type(parent, key, xsi_type)
        else
          raise AdsCommon::Errors::ApiException.new(
              "Can't find correct position for xsi:type (%s) [%s], [%s]" %
                  [xsi_type, parent, key])
        end
      end
      return arg.inject({}) do |result, (key, value)|
        result[key] = (key == :attributes!) ? value :
            validate_arg(value, result, key)
        result
      end
    end

    # Adds ":attributes!" record for Savon to specify xsi:type.
    def add_xsi_type(parent, key, xsi_type)
      parent[:attributes!] ||= {}
      parent[:attributes!][key] ||= {}
      parent[:attributes!][key]["xsi:type"] ||= []
      parent[:attributes!][key]["xsi:type"] << xsi_type
    end

    # Executes each handler to generate SOAP headers.
    def set_headers(soap, args)
      @headerhandler.each do |handler|
        handler.prepare_request(@client.http, soap, args)
      end
    end

    # Checks for errors in response and raises appropriate exception.
    def handle_errors(response)
      if response.soap_fault?
        exception = exception_for_soap_fault(response)
        raise exception
      end
      if response.http_error?
        raise AdsCommon::Errors::HttpError,
            "HTTP Error occurred: %s" % response.http_error
      end
    end

    # Finds an exception object for a given response.
    def exception_for_soap_fault(response)
      begin
        fault = response[:fault]
        if fault[:detail] and fault[:detail][:api_exception_fault]
          exception_fault = fault[:detail][:api_exception_fault]
          exception_name = exception_fault[:application_exception_type]
          exception_class = get_module().const_get(exception_name)
          return exception_class.new(exception_fault)
        elsif fault[:faultstring]
          fault_message = fault[:faultstring]
          return AdsCommon::Errors::ApiException.new(
              "Unknown exception with error: %s" % fault_message)
        else
          raise ArgumentError.new(fault.to_s)
        end
      rescue Exception => e
        return AdsCommon::Errors::ApiException.new(
            "Failed to resolve exception (%s), SOAP fault: %s" %
            [e.message, response.soap_fault])
      end
    end

    # Extracts the finest results possible for the given result. Returns the
    # response itself in worst case (contents unknown).
    def extract_result(response, action_name)
      method = get_service_registry.get_method_signature(action_name)
      action = method[:output][:name].to_sym
      result = response.to_hash
      result = result[action] if result.include?(action)
      return normalize_output(result, method)
    end

    # Normalizes output starting with root node "rval".
    def normalize_output(output_data, method_definition)
      fields_list = method_definition[:output][:fields]
      result = normalize_output_field(output_data, fields_list, :rval)
      return result[:rval]
    end

    # Normalizes one field of a given data recursively.
    # Args:
    #  - output_data: XML data to normalize
    #  - fields_list: expected list of fields from signature
    #  - field_name: specifies field name to normalize
    def normalize_output_field(output_data, fields_list, field_name)
      return nil if output_data.nil?
      field_definition = get_field_by_name(fields_list, field_name)
      field_sym = field_name.to_sym
      output_data[field_sym] = normalize_type(output_data[field_sym],
          field_definition)

      sub_type = get_service_registry.get_type_signature(
          field_definition[:type])
      if sub_type
        sub_type[:fields] += implode_parent(sub_type)
        if sub_type[:fields]
          # go recursive
          sub_type[:fields].each do |sub_type_field|
            if output_data[field_sym].is_a?(Array)
              items_list = output_data[field_sym]
              output_data[field_sym] = []
              items_list.each do |item|
                output_data[field_sym] <<
                    normalize_output_field(item, sub_type_field,
                                           sub_type_field[:name])
              end
            else
              output_data[field_sym] =
                  normalize_output_field(output_data[field_sym], sub_type_field,
                                         sub_type_field[:name])
            end
          end
        end
      end
      return output_data
    end

    # Converts XML input string into a native format.
    def normalize_type(data, field)
      type_name = field[:type]
      result = case data
        when Array
          data.map {|item| normalize_item(type_name, item)}
        else
          normalize_item(type_name, data)
      end
      # If field signature allows an array, forcing array structure even for one
      # item.
      if !field[:min_occurs].nil? and
          (field[:max_occurs].nil? or field[:max_occurs] > 1)
        result = arrayize(result)
      end
      return result
    end

    # Converts one leaf item to a built-in type.
    def normalize_item(type_name, item)
      return (item.nil?) ? item :
          case type_name
            when 'long', 'int' then Integer(item)
            when 'double' then Float(item)
            when 'boolean' then item.kind_of?(String) ?
                item.casecmp('true') == 0 : item
            else item
          end
    end

    # Finds a field in a list by its name.
    def get_field_by_name(fields_list, name)
      fields_array = arrayize(fields_list)
      index = fields_array.find_index {|field| field[:name].eql?(name)}
      return (index.nil?) ? nil : fields_array.at(index)
    end

    # Makes sure object is an array.
    def arrayize(object)
      return [] if object.nil?
      return object.is_a?(Array) ? object : [object]
    end

    # Converts Time to a hash for XML marshalling.
    def time_to_xml_hash(time)
      return {
          :hour => time.hour, :minute => time.min, :second => time.sec,
          :date => {:year => time.year, :month => time.month, :day => time.day}
      }
    end

    # Returns all inherited fields of superclasses for given type.
    def implode_parent(data_type)
      result = []
      if data_type and data_type[:base]
        parent_type = get_service_registry.get_type_signature(data_type[:base])
        result += parent_type[:fields] if parent_type[:fields]
        result += implode_parent(parent_type) if parent_type[:base]
      end
      return result
    end

    # Returns copy of object and its sub-objects ("deep" copy).
    def deep_copy(data)
      return Marshal.load(Marshal.dump(data))
    end
  end
end


text:
describe("API", function() {

    var actual = window;
    var expected = {Ext:{core:{Element: function(){} }}},
    Ext = expected.Ext;

    /* Element.static-more.js */ Ext.core.Element.getActiveElement = function getActiveElement(){};
    /* Element.static-more.js */ Ext.core.Element.serializeForm = function serializeForm(){};

    APITest({Ext:expected.Ext}, {Ext:actual.Ext});

});


text:
package ui;

import app.ControlUnit;
import ui.tools.Refreshable;
import app.MyImage;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import ui.io.MouseGuy;

public final class InfoPanel extends JPanel implements Refreshable {

    private final JLabel mouseText;
    private final JLabel colorInfo;
    private final JPanel colorPanel;
    private JLabel scaleInfo;
    private JLabel cmdInfo;
    private final JSlider slider;
    private final PaintPanel pan;
    private final MouseGuy mouse;
    private final ControlUnit cu;

    public InfoPanel(ControlUnit cu, PaintPanel pan, MouseGuy mouse) {
        this.pan = pan;
        this.cu = cu;
        this.mouse = mouse;
        setPreferredSize(new Dimension(pan.getWidth(), 60));
        FlowLayout flowLayout = new FlowLayout();
        flowLayout.setAlignment(FlowLayout.LEADING);
        setLayout(flowLayout);

        mouseText = new JLabel();
        mouseText.setText("width:" + cu.getImg().getImg().getWidth() + " height: " + cu.getImg().getImg().getHeight());
        add(mouseText);

        colorInfo = new JLabel();
        colorInfo.setText("           Alpha:" + cu.getImg().getColor().getAlpha() + "    Current color: ");
        add(colorInfo);

        colorPanel = new JPanel() {
            @Override
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(cu.getImg().getColor());
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        add(colorPanel);

        slider = new JSlider(1, 16);
        scaleInfo = new JLabel("     Scale:" + pan.getScale() + "x  ");

        slider.setMinorTickSpacing(1);
        slider.setValue((int) pan.getScale());
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.addChangeListener((ChangeEvent e) -> {
            JSlider source = (JSlider) e.getSource();
            int value = source.getValue();
            scaleInfo.setText("     Scale:" + value + "x  ");
            pan.setScale(value);
            pan.revalidate();
            pan.repaint();

        });
        scaleInfo.setLabelFor(slider);

        add(scaleInfo);
        add(slider);

        cmdInfo = new JLabel("Brush");
        add (new JLabel("Current CMD: "));
        add(cmdInfo);
    }

    @Override
    public void refresh() {
        slider.setValue((int) pan.getScale());
        mouseText.setText(
                "width:" + cu.getImg().getImg().getWidth()
                + " height: " + cu.getImg().getImg().getHeight()
                + "           mouse x:"
                + Math.min(mouse.getToolTip().getCurX(), cu.getImg().getImg().getWidth())
                + " y:" + Math.min(mouse.getToolTip().getCurY(), cu.getImg().getImg().getHeight()));
        colorInfo.setText("           Alpha:" + cu.getImg().getColor().getAlpha() + "    Current color: ");
        colorPanel.repaint();
    }

    public JLabel getCmdInfo() {
        return cmdInfo;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.Core;

namespace Azure.Communication.Chat
{
    /// <summary> Collection of participants belong to a particular thread. </summary>
    internal partial class ChatParticipantsCollection
    {
        /// <summary> Initializes a new instance of ChatParticipantsCollection. </summary>
        /// <param name="value"> Chat participants. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        internal ChatParticipantsCollection(IEnumerable<ChatParticipantInternal> value)
        {
            Argument.AssertNotNull(value, nameof(value));

            Value = value.ToList();
        }

        /// <summary> Initializes a new instance of ChatParticipantsCollection. </summary>
        /// <param name="value"> Chat participants. </param>
        /// <param name="nextLink"> If there are more chat participants that can be retrieved, the next link will be populated. </param>
        internal ChatParticipantsCollection(IReadOnlyList<ChatParticipantInternal> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Chat participants. </summary>
        public IReadOnlyList<ChatParticipantInternal> Value { get; }
        /// <summary> If there are more chat participants that can be retrieved, the next link will be populated. </summary>
        public string NextLink { get; }
    }
}


text:
define([
  'underscore',
  'backbone'
], function(_, Backbone){
  var AboutmeModel = Backbone.Model.extend({
    urlRoot: '/static/js/data/data-aboutme.json',
    initialize: function(){
    }
  });

  return AboutmeModel;

});


text:
'use strict';
//Writing pubsub module for socket.io
module.exports = {
    //Publishing a event..
    publish: function(socket, options ){
        if(options){
            var collectionName = options.collectionName;
            var method         = options.method;
            var data           = options.data;
            var modelId        = options.modelId;
            if(method === 'POST'){
                //console.log('Posting new data');
                var name = '/' + collectionName + '/' + method;
                socket.emit(name, data);
            }
            else{
                var name = '/' + collectionName + '/' + modelId + '/' + method;
                socket.emit(name, data);
            }
        }else{
            throw 'Error: Option must be an object type';
        }
    }, //End Publish..

    isEmpty:function (obj) {
        var hasOwnProperty = Object.prototype.hasOwnProperty;
        // null and undefined are "empty"
        if (obj == null) return true;
        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;
        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
            if (this.hasOwnProperty.call(obj, key)) return false;
        }
        return true;
    } //isEmpty function..
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { PadreComponent } from './padre/padre.component';
import { HijoComponent } from './hijo/hijo.component';

@NgModule({
  declarations: [AppComponent, HeaderComponent, PadreComponent, HijoComponent],
  imports: [BrowserModule, FormsModule],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
<?php
/**
 * @var common\components\web\View $this
 * @var \common\models\college\Subject $subject
 * @var string $folder
 * @var \RecursiveDirectoryIterator $materialsIterator
 * @var \common\models\college\subjects\MaterialFolder $materialFolderForm
 * @var \common\models\college\subjects\MaterialFile $materialFileForm
 * @var array $pages
 */

use yii\helpers\Url;
use frontend\modules\pulpit\assets\SubjectMaterialsAsset;
use yii\helpers\Html;
use common\components\helpers\FileHelper;

$this->title = "Учебные материалы предмета `{$subject->name}`";

$this->params['breadcrumbs'][] = ['label' => 'Учебные предметы', 'url' => ['/pulpit/subjects']];
$this->params['breadcrumbs'][] = $subject->code;
$this->params['breadcrumbs'][] = 'Материалы';

SubjectMaterialsAsset::register($this);

?>

        <button type="button" class="btn btn-primary" id="add-file">Добавить Файл</button>
        <button type="button" class="btn btn-primary" id="add-folder">Добавить папку</button>

            <a href="<?= Url::to([
                'subject-materials/index',
                'subjectCode' => $subject->code,
                'path' => ''
            ]) ?>">Начало

        <?php foreach ($pages as $page) : ?>

                /
                <a href="<?= Url::to([
                    'subject-materials/index',
                    'subjectCode' => $subject->code,
                    'path' => $page['path']
                ]) ?>">
                    <?= $page['name'] ?>

        <?php endforeach; ?>

    <form action="<?= Url::to(['subject-materials/add-file']) ?>" class="hidden" id="adding-file-form">
        <input type="hidden" name="<?= Html::getInputName($materialFileForm, 'path') ?>" value="<?= $folder ?>">
        <input type="hidden" name="<?= Html::getInputName($materialFileForm, 'subjectCode') ?>"
               value="<?= $subject->code ?>">
        <input type="file" name="<?= Html::getInputName($materialFileForm, 'file') ?>">
    </form>

    <form action="<?= Url::to(['subject-materials/add-folder']) ?>"
          class="hidden"
          id="form-add-folder"
          method="POST">
        <input type="hidden" name="<?= Html::getInputName($materialFolderForm, 'path') ?>" value="<?= $folder ?>">
        <input type="hidden" name="<?= Html::getInputName($materialFolderForm, 'subjectCode') ?>"
               value="<?= $subject->code ?>">
        <input type="text" name="<?= Html::getInputName($materialFolderForm, 'folder') ?>" title="Название папки">
        <button type="submit">

        </button>

    </form>

        <?php foreach ($materialsIterator as $item): ?>
            <?php $path = FileHelper::join($folder, $item->getFilename()) ?>
            <?php /* @var \common\components\base\storage\StorageItem $item */ ?>

                <?php if ($item->isFile()) : ?>

                        <?= $item->getFilename() ?>

                            <a href="<?= $item->getUrl() ?>" target="_blank">

                            <a href="<?= Url::to([
                                'subject-materials/remove-file',
                                'subjectCode' => $subject->code
                            ]) ?>" class="material-remove"
                               data-path="<?= $path ?>"
                               data-confirm-msg="Вы подтвеждаете удаление?">

                <?php else : ?>

                        <a href="<?= Url::to([
                            'subject-materials/index',
                            'subjectCode' => $subject->code,
                            'path' => $path
                        ]) ?>">

                            <?= $item->getFilename() ?>

                            <a href="<?= Url::to([
                                'subject-materials/remove-folder',
                                'subjectCode' => $subject->code,
                            ]) ?>" class="material-remove-folder"
                               data-path="<?= $path ?>"
                               data-confirm-msg="Вы подтвеждаете удаление?">

                <?php endif; ?>

        <?php endforeach; ?>

            <a href="<?= urldecode(Url::to([
                'subject-materials/index',
                'subjectCode' => $subject->code,
                'path' => '{path}'
            ])) ?>">

                {name}

            <a href="<?= Url::to([
                'subject-materials/remove-folder',
                'subjectCode' => $subject->code,
            ]) ?>" class="material-remove-folder"
               data-path="{path}"
               data-confirm-msg="Вы подтвеждаете удаление?">

            {name}

            <a href="<?= Url::to([
                'subject-materials/remove-file',
                'subjectCode' => $subject->code
            ]) ?>" class="material-remove"
               data-path="{path}"
               data-confirm-msg="Вы подтвеждаете удаление?">


text:
const char *file_rc(void);
const char *file_info(void);

#endif


text:
/* Generacion automatica de TRIGGERS para Logger */
/* Fecha y hora: 05/15/2017 13:21  */
/* Servidor: 10.3.1.3 Puerto: 3306 */
/* Base de datos: psalud_ri_testing */
/* Version aplicación: 0.0.1 */
/* Debug sobre tabla: camas */

DELIMITER ;

/* ---------------------------------- */
/* Trigger after insert - tabla camas */
/* ---------------------------------- */

DROP TRIGGER IF EXISTS logs_after_insert_camas;

DELIMITER $$

CREATE TRIGGER

    logs_after_insert_camas

AFTER INSERT

ON camas

FOR EACH ROW

BEGIN

    DECLARE estado INTEGER;
    DECLARE msg VARCHAR(255);
    DECLARE campos TEXT;
    DECLARE valores TEXT;

    SET campos = CONCAT_WS('|;|',
                'id_cama',
                'id_clasificacion_cama',
                'id_efector',
                'id_habitacion',
                'id_internacion',
                'nombre',
                'estado',
                'rotativa',
                'baja',
                'usuario',
                'fecha_modificacion');

    SET valores = CONCAT_WS('|;|',
                IFNULL(NEW.id_cama,''),
                IFNULL(NEW.id_clasificacion_cama,''),
                IFNULL(NEW.id_efector,''),
                IFNULL(NEW.id_habitacion,''),
                IFNULL(NEW.id_internacion,''),
                IFNULL(NEW.nombre,''),
                IFNULL(NEW.estado,''),
                IFNULL(NEW.rotativa,''),
                IFNULL(NEW.baja,''),
                IFNULL(NEW.usuario,''),
                IFNULL(NEW.fecha_modificacion,''));

    CALL logs_debug
        ('camas',
        campos,
        valores,
        'I',
        @estado,
        @msg);

END;

$$

DELIMITER ;

/* ----------------------------------- */
/* Trigger before update - tabla camas */
/* ----------------------------------- */

DROP TRIGGER IF EXISTS logs_before_update_camas;

DELIMITER $$

CREATE TRIGGER

    logs_before_update_camas

BEFORE UPDATE

ON camas

FOR EACH ROW

BEGIN

    DECLARE estado INTEGER;
    DECLARE msg VARCHAR(255);
    DECLARE campos TEXT;
    DECLARE valores TEXT;
    DECLARE guardar_modificaciones_nulas TINYINT(1);

    /* flag guardar modificaciones nulas */
    SET guardar_modificaciones_nulas =
        (SELECT
            la.guardar_modificaciones_nulas
        FROM
            logs_auditados la
        LIMIT 0,1);

    SET campos = CONCAT_WS('|;|',
                'id_cama',
                'id_clasificacion_cama',
                'id_efector',
                'id_habitacion',
                'id_internacion',
                'nombre',
                'estado',
                'rotativa',
                'baja',
                'usuario',
                'fecha_modificacion');

    SET valores = CONCAT_WS('|;|',
                IFNULL(OLD.id_cama,''),
                IFNULL(OLD.id_clasificacion_cama,''),
                IFNULL(OLD.id_efector,''),
                IFNULL(OLD.id_habitacion,''),
                IFNULL(OLD.id_internacion,''),
                IFNULL(OLD.nombre,''),
                IFNULL(OLD.estado,''),
                IFNULL(OLD.rotativa,''),
                IFNULL(OLD.baja,''),
                IFNULL(OLD.usuario,''),
                IFNULL(OLD.fecha_modificacion,''));

    IF( OLD.id_cama <> NEW.id_cama
        OR OLD.id_clasificacion_cama <> NEW.id_clasificacion_cama
        OR OLD.id_efector <> NEW.id_efector
        OR (
            ( ISNULL(OLD.id_habitacion) AND NOT ISNULL(NEW.id_habitacion) ) OR
            ( NOT ISNULL(OLD.id_habitacion) AND ISNULL(NEW.id_habitacion) ) OR
            ( NOT ISNULL(OLD.id_habitacion)
                AND NOT ISNULL(NEW.id_habitacion)
                AND OLD.id_habitacion <> NEW.id_habitacion)
           )
        OR (
            ( ISNULL(OLD.id_internacion) AND NOT ISNULL(NEW.id_internacion) ) OR
            ( NOT ISNULL(OLD.id_internacion) AND ISNULL(NEW.id_internacion) ) OR
            ( NOT ISNULL(OLD.id_internacion)
                AND NOT ISNULL(NEW.id_internacion)
                AND OLD.id_internacion <> NEW.id_internacion)
           )
        OR OLD.nombre <> NEW.nombre
        OR OLD.estado <> NEW.estado
        OR OLD.rotativa <> NEW.rotativa
        OR OLD.baja <> NEW.baja
        OR OLD.usuario <> NEW.usuario
        OR OLD.fecha_modificacion <> NEW.fecha_modificacion
        OR guardar_modificaciones_nulas = 1 ) THEN

        CALL logs_debug
            ('camas',
            campos,
            valores,
            'O',
            @estado,
            @msg);

    END IF;

END;

$$

DELIMITER ;

/* ---------------------------------- */
/* Trigger after update - tabla camas */
/* ---------------------------------- */

DROP TRIGGER IF EXISTS logs_after_update_camas;

DELIMITER $$

CREATE TRIGGER

    logs_after_update_camas

AFTER UPDATE

ON camas

FOR EACH ROW

BEGIN

    DECLARE estado INTEGER;
    DECLARE msg VARCHAR(255);
    DECLARE campos TEXT;
    DECLARE valores TEXT;
    DECLARE guardar_modificaciones_nulas TINYINT(1);

    /* flag guardar modificaciones nulas */
    SET guardar_modificaciones_nulas =
        (SELECT
            la.guardar_modificaciones_nulas
        FROM
            logs_auditados la
        LIMIT 0,1);

    SET campos = CONCAT_WS('|;|',
                'id_cama',
                'id_clasificacion_cama',
                'id_efector',
                'id_habitacion',
                'id_internacion',
                'nombre',
                'estado',
                'rotativa',
                'baja',
                'usuario',
                'fecha_modificacion');

    SET valores = CONCAT_WS('|;|',
                IFNULL(NEW.id_cama,''),
                IFNULL(NEW.id_clasificacion_cama,''),
                IFNULL(NEW.id_efector,''),
                IFNULL(NEW.id_habitacion,''),
                IFNULL(NEW.id_internacion,''),
                IFNULL(NEW.nombre,''),
                IFNULL(NEW.estado,''),
                IFNULL(NEW.rotativa,''),
                IFNULL(NEW.baja,''),
                IFNULL(NEW.usuario,''),
                IFNULL(NEW.fecha_modificacion,''));

    IF( OLD.id_cama <> NEW.id_cama
        OR OLD.id_clasificacion_cama <> NEW.id_clasificacion_cama
        OR OLD.id_efector <> NEW.id_efector
        OR (
            ( ISNULL(OLD.id_habitacion) AND NOT ISNULL(NEW.id_habitacion) ) OR
            ( NOT ISNULL(OLD.id_habitacion) AND ISNULL(NEW.id_habitacion) ) OR
            ( NOT ISNULL(OLD.id_habitacion)
                AND NOT ISNULL(NEW.id_habitacion)
                AND OLD.id_habitacion <> NEW.id_habitacion)
           )
        OR (
            ( ISNULL(OLD.id_internacion) AND NOT ISNULL(NEW.id_internacion) ) OR
            ( NOT ISNULL(OLD.id_internacion) AND ISNULL(NEW.id_internacion) ) OR
            ( NOT ISNULL(OLD.id_internacion)
                AND NOT ISNULL(NEW.id_internacion)
                AND OLD.id_internacion <> NEW.id_internacion)
           )
        OR OLD.nombre <> NEW.nombre
        OR OLD.estado <> NEW.estado
        OR OLD.rotativa <> NEW.rotativa
        OR OLD.baja <> NEW.baja
        OR OLD.usuario <> NEW.usuario
        OR OLD.fecha_modificacion <> NEW.fecha_modificacion
        OR guardar_modificaciones_nulas = 1 ) THEN

        CALL logs_debug
            ('camas',
            campos,
            valores,
            'N',
            @estado,
            @msg);

    END IF;

END;

$$

DELIMITER ;

/* ----------------------------------- */
/* Trigger before delete - tabla camas */
/* ----------------------------------- */

DROP TRIGGER IF EXISTS logs_before_delete_camas;

DELIMITER $$

CREATE TRIGGER

    logs_before_delete_camas

BEFORE DELETE

ON camas

FOR EACH ROW

BEGIN

    DECLARE estado INTEGER;
    DECLARE msg VARCHAR(255);
    DECLARE campos TEXT;
    DECLARE valores TEXT;

    SET campos = CONCAT_WS('|;|',
                'id_cama',
                'id_clasificacion_cama',
                'id_efector',
                'id_habitacion',
                'id_internacion',
                'nombre',
                'estado',
                'rotativa',
                'baja',
                'usuario',
                'fecha_modificacion');

    SET valores = CONCAT_WS('|;|',
                IFNULL(OLD.id_cama,''),
                IFNULL(OLD.id_clasificacion_cama,''),
                IFNULL(OLD.id_efector,''),
                IFNULL(OLD.id_habitacion,''),
                IFNULL(OLD.id_internacion,''),
                IFNULL(OLD.nombre,''),
                IFNULL(OLD.estado,''),
                IFNULL(OLD.rotativa,''),
                IFNULL(OLD.baja,''),
                IFNULL(OLD.usuario,''),
                IFNULL(OLD.fecha_modificacion,''));

    CALL logs_debug
        ('camas',
        campos,
        valores,
        'D',
        @estado,
        @msg);

END;

$$


text:
package org.senkbeil.debugger.akka.messages

import org.senkbeil.debugger.akka.messages.structures.{JDILocation, JDIThread, JDIMethod}

case class MethodEntryMessage(
  thread:   Option[JDIThread]   = None,
  location: Option[JDILocation] = None,
  method:   Option[JDIMethod]   = None
) extends LocatableMessageLike with MessageLike