text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { Roles } from '../roles.model';
import { User } from '../../user.model';
import { UserService } from '../../user.service';
import { ToasterService } from 'angular2-toaster';
import { TranslateService } from 'ng2-translate';

@Component({
  moduleId: module.id,
  templateUrl: 'edit-user.component.html',
  styleUrls: ['edit-user.component.css'],
})
export class EditUserComponent implements OnInit {
  user: User = User.getEmptyUser();
  showStudentDetails = false;
  roles: string[] = Roles.ROLES;
  updatedRole: string[] = [];
  selectedRole: string[];
  newRole = false;

  constructor(private route: ActivatedRoute,
    private router: Router,
    private userService: UserService,
    private toasterService: ToasterService,
    private translateService: TranslateService) { }

  ngOnInit(): void {
    const userId = decodeURI(this.route.snapshot.params['id']);
    this.userService.getUser(userId)
      .then(
        (data: User) => {
          this.user = data;
          for (let role of this.user.roles) {
            if (role === 'Student') {
              this.showStudentDetails = true;
            }
          }
        }
      ).catch(
        () => {
          this.router.navigate(['/error']);
        }
      );
  }

  selectRole(role) {
    if (this.updatedRole.indexOf(role) === -1) {
      this.updatedRole.push(role);
      this.newRole = true;
    }
  }

  updateUser(): void {
    if (this.newRole === true) {
      this.userService.updateRoles(this.updatedRole, this.user)
        .then(
          (response: any) => this.toasterService.pop('success', this.getTranslatedString('Information successfully updated'))
        ).catch(
          // tslint:disable-next-line:no-shadowed-variable
          (error: any) => console.error(error)
        );
    }
    if (this.newRole === false) {
      this.userService.updateUser(this.user)
        .then(
          (response: any) => this.toasterService.pop('success', this.getTranslatedString('Information successfully updated'))
        )
        .catch(
          // tslint:disable-next-line:no-shadowed-variable
          (error: any) => console.error(error)
        );
    }
  }

  getTranslatedString(data: any) {
    let translatedResponse = '';
    this.translateService.get(data).subscribe(
      (value: string) => {
        translatedResponse = value;
      }
    );
    return translatedResponse;
  }
}


text:
package org.apache.hadoop.hive.metastore.events;

import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;

import java.util.Arrays;
import java.util.List;

public class PreAddPartitionEvent extends PreEventContext {

  private final Table table;
  private final List<Partition> partitions;

  public PreAddPartitionEvent (Table table, List<Partition> partitions, HMSHandler handler) {
    super(PreEventType.ADD_PARTITION, handler);
    this.table = table;
    this.partitions = partitions;
  }

  public PreAddPartitionEvent(Table table, Partition partition, HMSHandler handler) {
    this(table, Arrays.asList(partition), handler);
  }

  /**
   * @return the partitions
   */
  public List<Partition> getPartitions() {
    return partitions;
  }

  /**
   * @return the table
   */
  public Table getTable() {
    return table ;
  }
}

redpajama_set_name: RedPajamaGithub


text:
        <?php $count = count($navinotes); $title = 'Navinotes'; $color = $count?'success':'default'; $ico = 'fa-users';  ?>

                {{$count}}

{{$title}}

    @if($count)

                    {{$count}} {{$title}}

                    @foreach($navinotes as $row)

Title: {{$row->name}}

Desc.: {{$row->description}}

Unit: {{$row->unit->name}}

Author: {{$row-> user -> fullname()}}

                    @endforeach

    @endif


text:
namespace BuildMon.Teamcity
{
    public class TeamcityBuild : TeamcityDescriptor
    {
        public int percentageComplete { get; set; }
        public string status { get; set; }
        public string buildTypeId { get; set; }
        public bool running { get; set; }
    }
}


text:
Create Unity classes and methods easily.

![Visual Studio Marketplace Installs](https://img.shields.io/visual-studio-marketplace/i/kleber-swf.unity-code-snippets?color=red&style=for-the-badge)
![Visual Studio Marketplace Rating (Stars)](https://img.shields.io/visual-studio-marketplace/stars/kleber-swf.unity-code-snippets?color=blue&style=for-the-badge)
![Visual Studio Marketplace Version](https://img.shields.io/visual-studio-marketplace/v/kleber-swf.unity-code-snippets?color=orange&style=for-the-badge)

## Features

All the Unity code snippets you need. This extension intends to be the complete collection of Unity snippets for Visual Studio Code.

It takes advantage of latest Visual Studio Code snippets features to create the code faster for you.

### MonoBehaviour
Create game classes like `MonoBehaviours`, `NetworkBehaviours` and `StateMachineBehaviours` easily. Also create common methods like `Start()`, `Update()` or `OnTriggerEnter2D()` and log calls.

![MonoBehaviour](https://raw.githubusercontent.com/kleber-swf/vscode-unity-code-snippets/master/images/usage-01.gif)

### Editor
Create Editor classes like `Editor`, `EditorWindow` and `PropertyDrawer` as easy as it can be.

![Unity Editor](https://raw.githubusercontent.com/kleber-swf/vscode-unity-code-snippets/master/images/usage-02.gif)

### ScriptableObject
You never remember the property that goes with the `ScriptableObject` to create it via Unity create menu? Not a problem.

![ScriptableObject](https://raw.githubusercontent.com/kleber-swf/vscode-unity-code-snippets/master/images/usage-03.gif)

## Installation

As in any Visual Studio Code Extension you have several options to install:

* Enter the Visual Studio Code Marketplace, search for _Unity Code Snippets_ (or enter directly on [the extension page](https://marketplace.visualstudio.com/items?itemName=kleber-swf.unity-code-snippets)) and click on _Install_ button.
* Inside Visual Studio Code, enter in the Extensios panel, search for _Unity Code Snippets_ and click on _Install_ button
* Run the following command in the Command Palette:
	```
	ext install kleber-swf.unity-code-snippets
	```

## All the snippets

Start typing the names to create the corresponding snippets.

* Game classes:
	* `MonoBehaviour`
	* `StateMachineBehaviour`
	* `NetworkBehaviour`
	* `ScriptableObject`

* Editor Classes:
	* `Editor`
	* `Editor with Reorderable List` **_(NEW)_**
	* `EditorWindow`
	* `PropertyDrawer`
	* `ScriptableWizard`

* MonoBehaviour Methods:
	* `Awake()`
	* `FixedUpdate()`
	* `LateUpdate()`
	* `OnAnimatorIK()`
	* `OnAnimatorMove()`
	* `OnApplicationFocus()`
	* `OnApplicationPause()`
	* `OnApplicationQuit()`
	* `OnAudioFilterRead()`
	* `OnBecameInvisible()`
	* `OnBecameVisible()`
	* `OnCollisionEnter()`
	* `OnCollisionEnter2D()`
	* `OnCollisionExit()`
	* `OnCollisionExit2D()`
	* `OnCollisionStay()`
	* `OnCollisionStay2D()`
	* `OnConnectedToServer()`
	* `OnControllerColliderHit()`
	* `OnDestroy()`
	* `OnDisable()`
	* `OnDisconnectedFromServer()`
	* `OnDrawGizmos()`
	* `OnDrawGizmosSelected()`
	* `OnEnable()`
	* `OnFailedToConnect()`
	* `OnFailedToConnectToMasterServer()`
	* `OnGUI()`
	* `OnJointBreak()`
	* `OnJointBreak2D()`
	* `OnMasterServerEvent()`
	* `OnMouseDown()`
	* `OnMouseDrag()`
	* `OnMouseEnter()`
	* `OnMouseExit()`
	* `OnMouseOver()`
	* `OnMouseUp()`
	* `OnMouseUpAsButton()`
	* `OnNetworkInstantiate()`
	* `OnParticleCollision()`
	* `OnParticleTrigger()`
	* `OnPlayerConnected()`
	* `OnPlayerDisconnected()`
	* `OnPostRender()`
	* `OnPreCull()`
	* `OnPreRender()`
	* `OnRenderImage()`
	* `OnRenderObject()`
	* `OnSerializeNetworkView()`
	* `OnServerInitialized()`
	* `OnTransformChildrenChanged()`
	* `OnTransformParentChanged()`
	* `OnTriggerEnter()`
	* `OnTriggerEnter2D()`
	* `OnTriggerExit()`
	* `OnTriggerExit2D()`
	* `OnTriggerStay()`
	* `OnTriggerStay2D()`
	* `OnValidate()`
	* `OnWillRenderObject()`
	* `Reset()`
	* `Start()`
	* `Update()`

* Debug class
	* `Debug.DrawLine()`
	* `Debug.DrawRay()`

* Some useful code snippets:
	* `Debug.Log()` (type _`log`_)
	* `Debug.LogError()` (type _`logerror`_)
	* `Debug.LogWarning()` (type _`logwarning`_)
	* `Debug.LogException()`  (type _`logexception`_)

If you have any suggestions, [open an issue in the Github project](https://github.com/kleber-swf/vscode-unity-code-snippets/issues) page and I'll add them as soon as I can :).

If you like the color theme of the previews, you can download it here: [Base16 Ocean Dark Extended Theme](https://marketplace.visualstudio.com/items?itemName=kleber-swf.ocean-dark-extended).

Thank you for downloading this extension.


text:
<?php

// You can find the keys here : https://console.developers.google.com

return array(
    'KEY' => 'AIzaSyBZ7JjEEQwCVCDiyApveP6QuTwMXdtN5Ig'
);


text:
import * as types from '../constants/actionTypes';
import { combineReducers } from 'redux';

const initialState = {
  home: {
    feed: {}
  }
};

function createReducer(initialState, handlers) {
  return function reducer(state = initialState, action) {
    if (handlers.hasOwnProperty(action.type)) {
      return handlers[action.type](state, action);
    } else {
      return state;
    }
  }
}

export const home = createReducer(initialState.home, {
  [types.ALBUMS_SUCCESS](state, action) {
    return {
      ...state,
      feed: action.response.responseBody.feed
    }
  }
})


text:
package org.deeplearning4j.datasets.iterator;

import org.nd4j.linalg.dataset.api.DataSet;
import org.nd4j.linalg.dataset.api.DataSetPreProcessor;

public class DummyPreProcessor implements DataSetPreProcessor {
    /**
     * Pre process a dataset
     *
     * @param toPreProcess the data set to pre process
     */
    @Override
    public void preProcess(DataSet toPreProcess) {
        // no-op
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Security.Permissions;
using System.Web;
using System.Web.Mvc;
using geocoderNet.WellKnowBinary;
using Microsoft.Ajax.Utilities;
using WebGrease;

namespace geocoderNet.Models
{
    public class Database
    {

        private double Street_Weight = 3.0;
        private double Number_Weight = 2.0;
        private double Parity_Weight = 1.25;
        private double City_Weight = 1.0;

        public Database()
        {

        }

        public List<string> unique_values(List<Item> rows, string key)
        {
            return rows.Select(o => o.getValue(key)).Distinct().ToList();
        }

        public Dictionary<List<string>, List<Item>> rows_to_h(List<Item> rows, string[] keys)
        {
            var hash = new Dictionary<List<string>, List<Item>>();

            if (rows == null) return hash;

            var tempKeyList = new List<List<string>>();
            foreach (var row in rows)
            {
                // must do this because of reference to List.
                var keyPair = row.values_at(keys);
                var tempKey = tempKeyList.FirstOrDefault(o => Utilities.IsStringListSame(o, keyPair));

                if (tempKey == null)
                {
                    tempKeyList.Add(keyPair);
                    tempKey = keyPair;
                }

                if (!hash.ContainsKey(tempKey))
                    hash.Add(tempKey, new List<Item>());
                hash[tempKey].Add(row);

            }
            return hash;
        }

        public List<Item> merge_rows(List<Item> dest, List<Item> src, string[] keys)
        {
            var newDest = new List<Item>();
            var newSrc = rows_to_h(src, keys);
            foreach (var row in dest)
            {
                var vals = row.values_at(keys);
                var srcItemDict = newSrc.Where(o => Utilities.IsStringListSame(o.Key, vals));
                bool didAdd = false;
                if (srcItemDict != null)
                    foreach (var srcItemD in srcItemDict)
                    {
                        foreach (var srcItem in srcItemD.Value)
                        {
                            newDest.Add(Item.Merge(Item.Merge(new Item(), row), srcItem));
                            didAdd = true;
                        }
                    }

                if (!didAdd)
                    newDest.Add(Item.Merge(new Item(), row));

            }
            return newDest;
        }

        public List<Item> find_candidates(Address address)
        {
            var places = new List<Item>();
            var candidates = new List<Item>();

            string city = address.city.OrderBy(o => o.Length).FirstOrDefault();
            if (!String.IsNullOrEmpty(address.zip))
            {
                places = Place.places_by_zip(city, address.zip);
            }
            if (places == null || places.Count == 0)
                places = Place.places_by_city(city, address.city_parts(), address.state);

            if (places == null || places.Count == 0) return null;

            address.city = unique_values(places, "city");
            if (address.street == null || address.street.Count == 0) return places;

            var zips = unique_values(places, "zip");
            var street = address.street.OrderBy(o => o.Length).FirstOrDefault();
            candidates = Feature.features_by_street_and_zip(new List<string>(){ street}, address.street_parts(), zips.ToArray());

            if (candidates == null || candidates.Count == 0)
            {
                candidates = Feature.more_features_by_street_and_zip(new List<string>() { street }, address.street_parts(), zips.ToArray());
            }

            candidates = merge_rows(candidates, places, new string[] { "zip" });
            return candidates;
        }

        public List<Item> filter_by_score(List<Item> items, double score, string key)
        {
            var result = new List<Item>();
            var val = 0.0;
            if (items != null)
            {
                foreach (var item in items)
                {
                    if (Double.TryParse(item.getValue(key), out val) && val < score)
                    {
                        result.Add(item);
                    }
                }
            }

            return result;
        }

        public bool filter_by_score_is_empty(List<Item> items, double score, string key)
        {
            var lst = filter_by_score(items, score, key);
            if (lst == null || lst.Count() == 0)
                return true;
            return false;
        }

        public List<Item> find_candidates_new(Address address)
        {
            var score_threshold = 0.65;
            var city_score_threshold = 0.5;

            var places = new List<Item>();
            var candidates = new List<Item>();

            var lowest_city_score = 1.0;

            string city = ""; //= address.city.OrderBy(o => o.Length).FirstOrDefault();
            if (address.city != null)
            {
                foreach (var cty in address.city)
                {
                    if (cty != null && !String.IsNullOrEmpty(address.zip))
                    {
                        var parts = cty.Split(' ');
                        var count = parts.Count();
                        var temp_city = "";

                        for (var i = (count - 1); i >= 0; i--)
                        {
                            temp_city = (parts[i] + " " + temp_city).Trim();
                            var temp_places = Place.places_by_zip(temp_city, address.zip);

                            if (temp_places != null && temp_places.Count() > 0)
                            {
                                foreach (var a_place in temp_places)
                                {
                                    if (a_place.city_score < lowest_city_score)
                                    {
                                        places = temp_places;
                                        city = cty;
                                        lowest_city_score = a_place.city_score;
                                    }
                                }

                            }
                        }
                    }
                }
            }

            //places = filter_by_score(places, city_score_threshold, "city_score");

            if (filter_by_score_is_empty(places, city_score_threshold, "city_score"))
            {
                if (places == null)
                    places = new List<Item>();

                if (city != null && city != "")
                    places.AddRange(Place.places_by_city(city, address.city_parts(), address.state));
                else
                {

                    foreach (var mCity in address.city)
                    {
                        var tempPlaces = Place.places_by_city(mCity, address.city_parts(), address.state);
                        if (tempPlaces != null && tempPlaces.Count > 0)
                            places.AddRange(tempPlaces);
                    }
                }
            }

            if (places == null || places.Count == 0) return null;

            address.city = unique_values(places, "city");

            if (address.city != null && address.street != null)
            {
                var newStreets = new List<string>();
                foreach (var ct in address.city)
                {
                    foreach (var st in address.street)
                    {
                        if (st.ToLower().EndsWith(ct.ToLower()))
                            newStreets.Add(st.Substring(0, st.ToLower().LastIndexOf(ct.ToLower())));
                        else
                            newStreets.Add(st);
                    }
                }
                address.street = newStreets.Distinct().ToList();
            }

            if (address.street == null || address.street.Count == 0) return places;

            var zips = unique_values(places, "zip");
            //var street = address.street.OrderBy(o => o.Length).FirstOrDefault();

            candidates.AddRange(Feature.features_by_street_and_zip(address.street, address.street_parts(), zips.ToArray()));

            //candidates = filter_by_score(candidates, score_threshold, "street_score");

            if (filter_by_score_is_empty(candidates, score_threshold, "street_score") && !String.IsNullOrEmpty(address.zip) &&
                !String.IsNullOrEmpty(address.state))
            {
                if (candidates == null)
                    candidates = new List<Item>();

                var extrazips = Place.zips_by_county(address.zip, address.state);
                if (extrazips != null && extrazips.Count > 0)
                {

                    candidates.AddRange(Feature.features_by_street_and_zip(address.street, address.street_parts(), extrazips.ToArray()));

                    foreach (var zip in extrazips)
                    {
                        places.AddRange(Place.places_by_zip(city, zip));
                    }
                }
            }

            if (filter_by_score_is_empty(candidates, score_threshold, "street_score"))
            {
                if (candidates == null)
                    candidates = new List<Item>();

                candidates.AddRange(Feature.more_features_by_street_and_zip(address.street, address.street_parts(), zips.ToArray()));

            }

            if (candidates == null) return null;

            candidates = merge_rows(candidates, places, new string[] { "zip" });
            return candidates;
        }

        public List<Item> assign_number(int hn, List<Item> candidates)
        {
            if (hn < 0) hn = 0;
            foreach (var candidate in candidates)
            {
                var fromhn = candidate.fromhn;
                var tohn = candidate.tohn;
                if ((hn >= fromhn && hn <= tohn) || (hn <= fromhn && hn >= tohn))
                {
                    candidate.number = hn;
                    candidate.precision = Item.PRECISION_RANGE;
                }
                else
                {
                    candidate.number = (Math.Abs(hn - fromhn) < Math.Abs(hn - tohn) ? candidate.fromhn : candidate.tohn);
                    candidate.precision = Item.PRECISION_STREET;
                }
            }
            return candidates.ToList();
        }

        public List<Item> add_ranges(Address address, List<Item> candidates)
        {
            var number = 0;
            if (Int32.TryParse(address.number, out number))
            {

                var fids = unique_values(candidates, "fid");
                var ranges = FeatureEdgeRange.ranges_by_feature(fids.ToArray(), number, address.prenum);
                if (ranges == null || ranges.Count == 0)
                    ranges = FeatureEdgeRange.ranges_by_feature(fids.ToArray(), number, null);
                candidates = merge_rows(candidates, ranges, new string[] { "fid" });
                candidates = assign_number(number, candidates);
            }
            return candidates;
        }

        public List<string> merge_edges(ref List<Item> candidates)
        {
            var edge_ids = unique_values(candidates, "tlid");
            var records = Edge.edges(edge_ids.ToArray());
            candidates = merge_rows(candidates, records, new string[] { "tlid" });
            candidates = candidates.Where(o => o.tlid != Item.INVALID_TLID).ToList();
            return edge_ids;
        }

        public List<Item> extend_ranges(List<Item> candidates)
        {
            var edge_ids = merge_edges(ref candidates);
            var full_ranges = Range.range_ends(edge_ids.ToArray());
            candidates = merge_rows(candidates, full_ranges, new string[] { "tlid", "side" });
            return candidates;
        }

        /* Score a list of candidates. For each candidate:
         * For each item in the query:
         ** if the query item is blank but the candidate is not, score 0.15;
            otherwise, if both are blank, score 1.0.
         ** If both items are set, compute the scaled Levenshtein-Damerau distance
            between them, and add that value (between 0.0 and 1.0) to the score.
         * Add 0.5 to the score for each numbered end of the range that matches
           the parity of the query number.
         * Add 1.0 if the query number is in the candidate range, otherwise
           add a fractional value for the notional distance between the
           closest candidate corner and the query.
         * Finally, divide the score by the total number of comparisons.
           The result should be between 0.0 and 1.0, with 1.0 indicating a
           perfect match. */

        public void score_candidates(Address address, ref List<Item> candidates)
        {

            foreach (var candidate in candidates)
            {
                candidate.components = new Dictionary<string, object>();
                var compare = new string[3] { "prenum", "state", "zip" };
                double denominator = compare.Length + Street_Weight + City_Weight;

                double street_score = (1.0 - (double)candidate.street_score) * Street_Weight;
                candidate.components["street"] = street_score;
                double city_score = (1.0 - (double)candidate.city_score) * City_Weight;
                candidate.components["city"] = city_score;
                double score = street_score + city_score;

                foreach (var key in compare)
                {

                    string src = (string)address.GetType().GetProperty(key).GetValue(address, null);
                    src = String.IsNullOrEmpty(src) ? "" : src.ToLower();
                    string dest = (string)candidate.GetType().GetProperty(key).GetValue(candidate, null);
                    dest = String.IsNullOrEmpty(dest) ? "" : dest.ToLower();
                    double item_score = (src == dest) ? 1 : 0;
                    candidate.components["key"] = item_score;
                    score += item_score;
                }

                if (!String.IsNullOrEmpty(address.number))
                {
                    double parity = 0.0;
                    double subscore = 0.0;

                    int fromhn = Convert.ToInt32(candidate.fromhn);
                    int tohn = Convert.ToInt32(candidate.tohn);
                    int assigned = Convert.ToInt32(candidate.number);
                    int hn = Convert.ToInt32(address.number);

                    if (candidate.precision == Item.PRECISION_RANGE)
                        subscore += Number_Weight;
                    else if (assigned > 0)
                    {
                        // only credit number subscore if assigned
                        subscore += (double)Math.Abs(Number_Weight / (assigned - hn));
                    }
                    candidate.components["number"] = subscore;

                    if (hn > 0 && assigned > 0)
                    {
                        // only credit parity if a number was given *and* assigned
                        if (fromhn % 2 == hn % 2)
                            parity += Parity_Weight / 2.0;
                        if (tohn % 2 == hn % 2)
                            parity += Parity_Weight / 2.0;
                    }

                    candidate.components["parity"] = parity;
                    score += subscore + parity;
                    denominator += Number_Weight + Parity_Weight;
                }

                candidate.components["total"] = (double)score;
                candidate.components["denominator"] = denominator;
                candidate.score = ((double)score) / denominator;

            }
        }

        public List<Item> best_candidates(List<Item> candidates)
        {
            if (candidates == null || candidates.Count == 0) return null;
            List<Item> newList = candidates.OrderByDescending(o => o.score).ToList();
            return newList.Where(o => o.score == newList[0].score).ToList();
        }

        public double interpolation_distance(Item candidate)
        {
            var fromhn = candidate.fromhn;
            var tohn = candidate.tohn;
            var number = candidate.number;
            if (fromhn > tohn)
            {
                var temp = fromhn;
                fromhn = tohn;
                tohn = temp;
            }
            if (fromhn > number) return 0.0;
            else if (tohn < number) return 1.0;
            else if (tohn == fromhn) return 0.0;
            else return ((double)(number - fromhn)) / ((double)(tohn - fromhn));
        }

        public static double[][] unpack_geometry(string geometry)
        {
            if (!String.IsNullOrEmpty(geometry))
            {

                var numberChars = geometry.Length;
                var bytes = new byte[numberChars / 2];
                for (var i = 0; i < numberChars; i += 2)
                    bytes[i / 2] = Convert.ToByte(geometry.Substring(i, 2), 16);

                WkbShape shape = WkbDecoder.Parse(bytes);

                if (shape.GetType() == typeof(WkbMultiLineString))
                {
                    var lineString = (WkbMultiLineString)shape;
                    if (lineString.LineString.Count() > 0)
                    {
                        var index = 0;
                        var points = new double[lineString.LineString[0].Points.Count()][];
                        foreach (var point in lineString.LineString[0].Points)
                        {
                            points[index] = new[] { point.X, point.Y };
                            index++;
                        }
                        return points;
                    }
                }
            }
            return new double[][] { };

        }

        // Calculate the longitude scaling for the average of two latitudes.
        public double scale_lon(double lat1, double lat2)
        {
            /* an approximation in place of lookup.rst (10e) and (10g)
            = scale longitude distances by the cosine of the latitude
            (or, actually, the mean of two latitudes)
            -- is this even necessary? */
            return Math.Cos((lat1 + lat2) / 2 * Math.PI / 180);
        }

        /* Simple Euclidean distances between two 2-D coordinate pairs, scaled
         along the longitudinal axis by scale_lon. */
        public double distance(double[] a, double[] b)
        {
            var dx = (b[0] - a[0]) * scale_lon(a[1], b[1]);
            var dy = (b[1] - a[1]);
            return Math.Sqrt(Math.Pow(dx, 2) + Math.Pow(dy, 2));
        }

        public double[] street_side_offset(double b, double[] p1, double[] p2)
        {
            // Find a point (x2, y2) that is at a distance b from a line A=(x0, y0)-(x1, y1)
            // along a tangent B passing through (x1,y1)-(x2,y2).
            // Let a = the length of line A
            var a = Math.Sqrt(Math.Pow((p2[0] - p1[0]), 2.0) + Math.Pow((p2[1] - p1[1]), 2.0));
            // theta is the angle between the line A and the x axis
            var theta = Math.Atan2(p2[1] - p1[1], p2[0] - p1[0]);
            // Now lines A and B form a right triangle where the third vertex is (x2, y2).
            // Let c = the length of the hypotenuse line C=(x0,y0)-(x2,y2)
            var c = Math.Sqrt(Math.Pow(a, 2.0) + Math.Pow(b, 2.0));
            // Now alpha is the angle between lines A and C.
            var alpha = Math.Atan2(b, a);
            // Therefore the difference between theta and alpha is the angle between C and
            // the x axis. Since we know the length of C, the lengths of the two lines
            // parallel to the axes that form a right triangle C, and hence the
            // coordinates (x2, y2), fall out.
            return new double[] { p1[0] + c * Math.Cos(theta - alpha), p1[1] + c * Math.Sin(theta - alpha) };
        }

        /* Find an interpolated point along a list of linestring vertices
        proportional to the given fractional distance along the line.
        Offset is in degrees and defaults to ~8 meters. */
        public double[] interpolate(double[][] points, double fraction, int side, double offset = 0.000075)
        {
            if (fraction == 0.0) return points[0];
            if (fraction == 1.0) return points[points.Count() - 1];
            var total = 0.0;
            for (int n = 1; n < points.Count(); n++)
            {
                total += distance(points[n - 1], points[n]);
            }
            var target = total * fraction;
            for (int n = 1; n < points.Count(); n++)
            {
                if (points[n - 1] == points[n]) continue;
                var step = distance(points[n - 1], points[n]);
                if (step < target)
                    target -= step;
                else
                {
                    var scale = scale_lon(points[n][1], points[n - 1][1]);
                    var dx = (points[n][0] - points[n - 1][0]) * (target / step) * scale;
                    var dy = (points[n][1] - points[n - 1][1]) * (target / step);
                    var found = new double[] { points[n - 1][0] + dx, points[n - 1][1] + dy };
                    return street_side_offset(offset * side, points[n - 1], found);
                }
            }
            // in a pathological case, points[n-1] == points[n] for n==-1
            // so *sigh* just forget interpolating and return points[-1]
            return points[points.Count() - 1];
        }

        public List<Item> canonicalize_places(List<Item> candidates)
        {
            var zips_used = unique_values(candidates, "zip");
            var tempPlaces = Place.primary_places(zips_used.ToArray());

            var pri_places = rows_to_h(tempPlaces, new string[] { "zip" });

            foreach (var record in candidates)
            {
                var key = pri_places.Keys.FirstOrDefault(o => Utilities.IsStringListSame(o, new List<string>() { record.zip }));
                var current_places = key != null ? pri_places[key] : null;
                if (current_places == null || current_places.Count == 0) return null;
                var top_priority = current_places.Select(p => Convert.ToInt32(p.priority)).Min();

                // not sure if this is precisely correct..... **********************
                current_places.Where(p => Convert.ToInt32(p.priority) == Convert.ToInt32(top_priority))
                    .ForEach(p =>
                    {
                        record.city = p.city;
                        record.state = p.state;
                        record.fips_county = p.fips_county;
                    });
            }

            return candidates;

        }

        public void clean_record(Place record)
        {
            // skipped formatting score.  its double here, and format should be where display happens.
            // no need to clean up nulls, best handled when display happens.
            // skip delete of components.
            // can't delete properties since this is not a hash.
        }

        public List<Item> best_places(Address address, List<Item> places, bool canonicalize = false)
        {
            if (places == null || places.Count == 0) return null;

            score_candidates(address, ref places);
            places = best_candidates(places);
            if (canonicalize)
                places = canonicalize_places(places);

            var by_name = rows_to_h(places, new string[] { "city", "state" });

            var by_name2 = new Dictionary<List<string>, List<Item>>();

            if (by_name.Count > 0)
            {
                // WHy sort and then grab the first record??????
                foreach (var key in by_name.Keys)
                {
                    by_name2[key] = by_name[key].OrderBy(x => x.zip).ToList();
                }

                places = by_name2.Select(o => (o.Value.Count > 0 ? o.Value[0] : new Item())).ToList();
                //clean_record(places); // see comments in clean_record.

                places.ForEach(o => o.precision = (o.zip == address.zip ? Item.PRECISION_ZIP : Item.PRECISION_CITY));
            }

            return places;
        }

        public List<Item> geocode_place(Address address, bool canonicalize = false)
        {
            List<Item> places = null;

            if (!String.IsNullOrEmpty(address.zip))
                places = Place.places_by_zip(address.text, address.zip);
            if (places == null)
                places = Place.places_by_city(address.text, address.city_parts(), address.state);

            places = best_places(address, places, canonicalize);

            return places;
        }

        public List<Item> geocode_intersection(Address address, bool canonical_place = false, bool use_find_candidates_new = false)
        {
            List<Item> candidates;
            if (use_find_candidates_new)
                candidates = find_candidates_new(address);
            else
                candidates = find_candidates(address);
            if (candidates == null || candidates.Count == 0) return null;
            if (String.IsNullOrEmpty(candidates[0].street)) return best_places(address, candidates, canonical_place);
            var features = rows_to_h(candidates, new string[] { "fid" });
            var temp = features.Keys;
            var intersects = Intersection.intersections_by_fid(features.Keys.SelectMany(x => x).ToArray()); // SelectMany effectively does a flatten.
            foreach (var record in intersects)
            {
                var feat1 = features.Where(k => Convert.ToInt32(k.Key.FirstOrDefault()) == record.fid1).Select(k => k.Value.FirstOrDefault()).FirstOrDefault();
                var feat2 = features.Where(k => Convert.ToInt32(k.Key.FirstOrDefault()) == record.fid2).Select(k => k.Value.FirstOrDefault()).FirstOrDefault();
                record.Merge(feat1);
                record.street1 = record.street;
                record.street = null;
                record.street2 = (feat2 != null ? feat2.street : "");
                var geo = unpack_geometry(record.point)[0];
                record.point = null;
                record.lon = geo[0];
                record.lat = geo[1];
                record.precision = Item.PRECISION_INTERSECTION;
                if (feat1 != null && feat2 != null)
                    record.street_score = ((double)feat1.street_score + (double)feat2.street_score) / 2.0; // not sure these have ever been scored???
            }

            score_candidates(address, ref intersects);
            intersects = best_candidates(intersects);

            var by_point = rows_to_h(intersects, new string[] { "lon", "lat" });
            candidates = by_point.Values.Select(r => r[0]).ToList();

            if (canonical_place)
                candidates = canonicalize_places(candidates);

            //candidates.each {|record| clean_record! record}
            return candidates;
        }

        public List<Item> geocode_address(Address address, bool canonical_place = false, bool use_find_candidates_new = false)
        {
            List<Item> candidates;
            if (use_find_candidates_new)
                candidates = find_candidates_new(address);
            else
                candidates = find_candidates(address);
            if (candidates == null || candidates.Count == 0) return null;
            if (String.IsNullOrEmpty(candidates[0].street)) return best_places(address, candidates, canonical_place);

            score_candidates(address, ref candidates);
            candidates = best_candidates(candidates);

            candidates = add_ranges(address, candidates);
            score_candidates(address, ref candidates);
            candidates = best_candidates(candidates);

            var by_tlid = rows_to_h(candidates, new string[] { "tlid" });
            candidates = by_tlid.Values.Select(o => (o.Count > 0 ? o[0] : null)).ToList();

            if (!String.IsNullOrEmpty(address.number))
                candidates = extend_ranges(candidates);
            else
            {
                var by_street = rows_to_h(candidates, new string[] { "street", "zip" });
                candidates = by_street.Values.Select(o => (o.Count > 0 ? o[0] : null)).ToList();

                /* (This section only runs when street number is not known.) The function below is commented
                 * because it merges based on tlid values.  But no tlid values have been acquired at this point,
                 * which results in all candidates being eliminated.  This doesn't appear to accomplish anything.
                 * Example: "franklin st hagerstown md 21740" will return no results.
                 */
                //merge_edges(ref candidates);
            }

            foreach (var record in candidates)
            {
                var dist = interpolation_distance(record);
                if (!String.IsNullOrEmpty(record.geometry))
                {
                    var points = unpack_geometry(record.geometry);
                    var side = (record.side == "R" ? 1 : -1);
                    if (record.flipped)
                    {
                        side *= -1;
                        points = points.Reverse().ToArray();
                    }

                    var found = interpolate(points, dist, side);
                    record.lon = found[0];
                    record.lat = found[1];
                    // record[:lon], record[:lat] = found.map {|x| format("%.6f", x).to_f} // not a string here...
                }
            }

            if (canonical_place)
                candidates = canonicalize_places(candidates);

            //candidates.ForEach(o => clean_record(o));  // not using clean_record at this time.
            return candidates;
        }

        public string find_city_zip(Address address)
        {

            string zip = null;
            var places = new List<Item>();

            if (address.city != null && address.city.Count > 0)
            {
                foreach (var mCity in address.city)
                {
                    string[] parts = mCity.Split(' ');
                    string tempCity = "";
                    for ( var i = parts.Length - 1; i >= 0; i--)
                    {
                        tempCity = parts[i] + " " + tempCity; // build string backwards.
                        var tempPlaces = Place.places_by_city(mCity, new List<string>() { tempCity }, address.state);
                        if (tempPlaces != null && tempPlaces.Count > 0)
                            places.AddRange(tempPlaces);

                    }
                }

            }

            double bestScore = 1.0;
            foreach (var place in places)
            {
                if (place.city_score < bestScore)
                {
                    bestScore = place.city_score;
                    zip = place.zip;
                }
            }

            return zip;
        }

        public List<Item> geocode(string info_to_geocode, bool canonical_place, bool use_find_candidates_new = false)
        {
            List<Item> result = null;

            var address = new Address(info_to_geocode);

            if (address.city != null && address.city.Count > 0 && String.IsNullOrEmpty(address.zip))
            {
                // we make a shot at getting a zip in the city, and then try to match.
                address.zip = find_city_zip(address);
                if (String.IsNullOrEmpty(address.zip))
                    return null;
            }

            if (address.po_box() && !String.IsNullOrEmpty(address.zip))
                result = geocode_place(address, canonical_place);

            if (address.intersection() && address.street != null && address.street.Count > 0 && String.IsNullOrEmpty(address.number))
                result = geocode_intersection(address, canonical_place, use_find_candidates_new);

            if (result == null && address.street != null && address.street.Count > 0)
                result = geocode_address(address, canonical_place, use_find_candidates_new);

            if (result == null)
                result = geocode_place(address, canonical_place);

            return result;
        }

    }
}


text:
package trust

import (
	"context"
	"crypto/x509"
	"fmt"
	"math/rand"
	"net"
	"time"

	"github.com/patrickmn/go-cache"
	"google.golang.org/protobuf/proto"

	"github.com/scionproto/scion/go/lib/addr"
	libmetrics "github.com/scionproto/scion/go/lib/metrics"
	"github.com/scionproto/scion/go/lib/prom"
	"github.com/scionproto/scion/go/lib/scrypto"
	"github.com/scionproto/scion/go/lib/scrypto/cppki"
	"github.com/scionproto/scion/go/lib/scrypto/signed"
	"github.com/scionproto/scion/go/lib/serrors"
	"github.com/scionproto/scion/go/lib/util"
	cppb "github.com/scionproto/scion/go/pkg/proto/control_plane"
	cryptopb "github.com/scionproto/scion/go/pkg/proto/crypto"
	"github.com/scionproto/scion/go/pkg/trust/internal/metrics"
)

const defaultCacheExpiration = time.Minute

// Verifier is used to verify control plane messages using the AS cert
// stored in the database.
type Verifier struct {
	// BoundIA when non-zero makes sure that only a signature originated from that IA
	// can be valid.
	BoundIA addr.IA
	// BoundServer binds a remote server to ask for missing crypto material.
	BoundServer net.Addr
	// Engine provides verified certificate chains.
	Engine Provider

	// Cache keeps track of recently used certificates. If nil no cache is used.
	// This API is experimental.
	Cache              *cache.Cache
	CacheHits          libmetrics.Counter
	MaxCacheExpiration time.Duration
}

// Verify verifies the signature of the msg.
func (v Verifier) Verify(ctx context.Context, signedMsg *cryptopb.SignedMessage,
	associatedData ...[]byte) (*signed.Message, error) {

	l := metrics.VerifierLabels{}
	hdr, err := signed.ExtractUnverifiedHeader(signedMsg)
	if err != nil {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrValidate)).Inc()
		return nil, err
	}

	var keyID cppb.VerificationKeyID
	if err := proto.Unmarshal(hdr.VerificationKeyID, &keyID); err != nil {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrValidate)).Inc()
		return nil, serrors.WrapStr("parsing verification key ID", err)
	}
	if len(keyID.SubjectKeyId) == 0 {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrValidate)).Inc()
		return nil, serrors.WrapStr("subject key ID must be set", err)
	}
	ia := addr.IA(keyID.IsdAs)
	if !v.BoundIA.IsZero() && !v.BoundIA.Equal(ia) {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrValidate)).Inc()
		return nil, serrors.New("does not match bound ISD-AS", "expected", v.BoundIA, "actual", ia)
	}
	if ia.IsWildcard() {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrValidate)).Inc()
		return nil, serrors.New("ISD-AS must not contain wildcard", "isd_as", ia)
	}
	if v.Engine == nil {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrInternal)).Inc()
		return nil, serrors.New("nil engine that provides cert chains")
	}
	id := cppki.TRCID{ISD: ia.ISD(),
		Base:   scrypto.Version(keyID.TrcBase),
		Serial: scrypto.Version(keyID.TrcSerial),
	}
	if err := v.notifyTRC(ctx, id); err != nil {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrInternal)).Inc()
		return nil, serrors.WrapStr("reporting TRC", err, "id", id)
	}
	query := ChainQuery{
		IA:           ia,
		SubjectKeyID: keyID.SubjectKeyId,
		Date:         time.Now(),
	}
	chains, err := v.getChains(ctx, query)
	if err != nil {
		metrics.Verifier.Verify(l.WithResult(metrics.ErrInternal)).Inc()
		return nil, serrors.WrapStr("getting chains", err,
			"query.isd_as", query.IA,
			"query.subject_key_id", fmt.Sprintf("%x", query.SubjectKeyID),
			"query.date", util.TimeToCompact(query.Date),
		)
	}
	for _, c := range chains {
		signedMsg, err := signed.Verify(signedMsg, c[0].PublicKey, associatedData...)
		if err == nil {
			metrics.Verifier.Verify(l.WithResult(metrics.Success)).Inc()
			return signedMsg, nil
		}
	}
	metrics.Verifier.Verify(l.WithResult(metrics.ErrNotFound)).Inc()
	return nil, serrors.New("no chain in database can verify signature",
		"query.isd_as", query.IA,
		"query.subject_key_id", fmt.Sprintf("%x", query.SubjectKeyID),
		"query.date", util.TimeToCompact(query.Date),
	)
}

func (v *Verifier) notifyTRC(ctx context.Context, id cppki.TRCID) error {
	key := fmt.Sprintf("notify-%s", id)
	_, ok := v.cacheGet(key, "notify_trc")
	if ok {
		return nil
	}
	if err := v.Engine.NotifyTRC(ctx, id, Server(v.BoundServer)); err != nil {
		return err
	}
	v.cacheAdd(key, struct{}{}, time.Minute)
	return nil
}

func (v *Verifier) getChains(ctx context.Context, q ChainQuery) ([][]*x509.Certificate, error) {
	key := fmt.Sprintf("chain-%s-%x", q.IA, q.SubjectKeyID)

	cachedChains, ok := v.cacheGet(key, "chains")
	if ok {
		return cachedChains.([][]*x509.Certificate), nil
	}

	chains, err := v.Engine.GetChains(ctx, q, Server(v.BoundServer))
	if err != nil {
		return nil, err
	}
	if len(chains) != 0 {
		v.cacheAdd(key, chains, v.cacheExpiration(chains))
	}
	return chains, nil
}

func (v *Verifier) cacheGet(key string, reqType string) (interface{}, bool) {
	if v.Cache == nil {
		return nil, false
	}
	result, ok := v.Cache.Get(key)

	resultValue := "hit"
	if !ok {
		resultValue = "miss"
	}
	libmetrics.CounterInc(libmetrics.CounterWith(v.CacheHits,
		"type", reqType,
		prom.LabelResult, resultValue,
	))

	return result, ok
}

func (v *Verifier) cacheAdd(key string, value interface{}, d time.Duration) {
	if v.Cache == nil {
		return
	}
	v.Cache.Add(key, value, d)
}

func (v *Verifier) cacheExpiration(chains [][]*x509.Certificate) time.Duration {
	dur := v.MaxCacheExpiration
	if dur == 0 {
		dur = defaultCacheExpiration
	}
	validity := time.Duration(rand.Int63n(int64(dur-(dur/2))) + int64(dur/2))
	expiration := time.Now().Add(validity)
	for _, chain := range chains {
		if notAfter := chain[0].NotAfter; notAfter.Before(expiration) {
			expiration = notAfter
		}
	}
	return time.Until(expiration)
}


text:
package group5.trackerexpress.test;

import group5.trackerexpress.Claim;
import group5.trackerexpress.ClaimList;
import group5.trackerexpress.Controller;
import group5.trackerexpress.Expense;
import group5.trackerexpress.ExpenseNotFoundException;
import group5.trackerexpress.MainActivity;
import android.app.Instrumentation;
import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;

public class ClaimControllerTest extends ActivityInstrumentationTestCase2<MainActivity> {

	Instrumentation instrumentation;
	Context context;
	ClaimList claims;
	public ClaimControllerTest() {
		super(MainActivity.class);
	}

	protected void setUp() throws Exception {
		super.setUp();
		instrumentation = getInstrumentation();
		context = getActivity();
		claims = Controller.getClaimList(context);
	}

	public void testAddExpense() throws ExpenseNotFoundException{
		Claim claim = new Claim ("Toronto");
		Expense expense = new Expense ("Supper");
		claim.addExpense(context, expense);
		assertTrue("Could not add new expense", claim.getExpenseList().getExpense(expense.getUuid()).getTitle().equals("Supper"));
	}

	public void testRemoveExpense() throws ExpenseNotFoundException{
		Claim claim = new Claim ("Toronto");
		Expense expense = new Expense ("Supper");
		claim.addExpense(context, expense);
		int size = claim.getExpenseList().size();
		claim.removeExpense(context, expense.getUuid());
		assertTrue("Could not remove expense", claim.getExpenseList().size()==size-1);
	}

	public void testAddDestination(){
		Claim claim = new Claim ("Toronto");
		int size = claim.getDestination().size();
		claim.addDestination(context, "Hamilton", "Business");
		assertTrue("Size did not increase", size + 1 == claim.getDestination().size());
		assertTrue("Could not add destination", claim.getDestination().get(claim.getDestination().size()-1)[0] == "Hamilton");
		assertTrue("Could not add destination2", claim.getDestination().get(claim.getDestination().size()-1)[1] == "Business");

	}
}


text:
package org.apache.kafka.connect.runtime.distributed;

import org.apache.kafka.common.protocol.types.ArrayOf;
import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.protocol.types.Schema;
import org.apache.kafka.common.protocol.types.SchemaException;
import org.apache.kafka.common.protocol.types.Struct;
import org.apache.kafka.common.protocol.types.Type;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import static org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocol;
import static org.apache.kafka.common.message.JoinGroupRequestData.JoinGroupRequestProtocolCollection;
import static org.apache.kafka.common.protocol.types.Type.NULLABLE_BYTES;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.ASSIGNMENT_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.CONFIG_OFFSET_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.CONFIG_STATE_V0;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.CONNECTOR_ASSIGNMENT_V0;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.CONNECT_PROTOCOL_HEADER_SCHEMA;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.CONNECT_PROTOCOL_V0;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.ERROR_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.LEADER_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.LEADER_URL_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.URL_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocol.VERSION_KEY_NAME;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocolCompatibility.COMPATIBLE;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocolCompatibility.EAGER;
import static org.apache.kafka.connect.runtime.distributed.ConnectProtocolCompatibility.SESSIONED;

/**
 * This class implements a group protocol for Kafka Connect workers that support incremental and
 * cooperative rebalancing of connectors and tasks. It includes the format of worker state used when
 * joining the group and distributing assignments, and the format of assignments of connectors
 * and tasks to workers.
 */
public class IncrementalCooperativeConnectProtocol {
    public static final String ALLOCATION_KEY_NAME = "allocation";
    public static final String REVOKED_KEY_NAME = "revoked";
    public static final String SCHEDULED_DELAY_KEY_NAME = "delay";
    public static final short CONNECT_PROTOCOL_V1 = 1;
    public static final short CONNECT_PROTOCOL_V2 = 2;
    public static final boolean TOLERATE_MISSING_FIELDS_WITH_DEFAULTS = true;

    /**
     * Connect Protocol Header V1:
     *

     *   Version            => Int16
     *

     */
    private static final Struct CONNECT_PROTOCOL_HEADER_V1 = new Struct(CONNECT_PROTOCOL_HEADER_SCHEMA)
            .set(VERSION_KEY_NAME, CONNECT_PROTOCOL_V1);

    /**
     * Connect Protocol Header V2:
     *

     *   Version            => Int16
     *

     * The V2 protocol is schematically identical to V1, but is used to signify that internal request
     * verification and distribution of session keys is enabled (for more information, see KIP-507:
     * https://cwiki.apache.org/confluence/display/KAFKA/KIP-507%3A+Securing+Internal+Connect+REST+Endpoints)
     */
    private static final Struct CONNECT_PROTOCOL_HEADER_V2 = new Struct(CONNECT_PROTOCOL_HEADER_SCHEMA)
        .set(VERSION_KEY_NAME, CONNECT_PROTOCOL_V2);

    /**
     * Config State V1:
     *

     *   Url                => [String]
     *   ConfigOffset       => Int64
     *

     */
    public static final Schema CONFIG_STATE_V1 = CONFIG_STATE_V0;

    /**
     * Allocation V1
     *

     *   Current Assignment => [Byte]
     *

     */
    public static final Schema ALLOCATION_V1 = new Schema(
            TOLERATE_MISSING_FIELDS_WITH_DEFAULTS,
            new Field(ALLOCATION_KEY_NAME, NULLABLE_BYTES, null, true, null));

    /**
     *
     * Connector Assignment V1:
     *

     *   Connector          => [String]
     *   Tasks              => [Int32]
     *

     *
     *
Assignments for each worker are a set of connectors and tasks. These are categorized by
     * connector ID. A sentinel task ID (CONNECTOR_TASK) is used to indicate the connector itself
     * (i.e. that the assignment includes responsibility for running the Connector instance in
     * addition to any tasks it generates).

     */
    public static final Schema CONNECTOR_ASSIGNMENT_V1 = CONNECTOR_ASSIGNMENT_V0;

    /**
     * Raw (non versioned) assignment V1:
     *

     *   Error              => Int16
     *   Leader             => [String]
     *   LeaderUrl          => [String]
     *   ConfigOffset       => Int64
     *   Assignment         => [Connector Assignment]
     *   Revoked            => [Connector Assignment]
     *   ScheduledDelay     => Int32
     *

     */
    public static final Schema ASSIGNMENT_V1 = new Schema(
            TOLERATE_MISSING_FIELDS_WITH_DEFAULTS,
            new Field(ERROR_KEY_NAME, Type.INT16),
            new Field(LEADER_KEY_NAME, Type.STRING),
            new Field(LEADER_URL_KEY_NAME, Type.STRING),
            new Field(CONFIG_OFFSET_KEY_NAME, Type.INT64),
            new Field(ASSIGNMENT_KEY_NAME, ArrayOf.nullable(CONNECTOR_ASSIGNMENT_V1), null, true, null),
            new Field(REVOKED_KEY_NAME, ArrayOf.nullable(CONNECTOR_ASSIGNMENT_V1), null, true, null),
            new Field(SCHEDULED_DELAY_KEY_NAME, Type.INT32, null, 0));

    /**
     * The fields are serialized in sequence as follows:
     * Subscription V1:
     *

     *   Version            => Int16
     *   Url                => [String]
     *   ConfigOffset       => Int64
     *   Current Assignment => [Byte]
     *

     */
    public static ByteBuffer serializeMetadata(ExtendedWorkerState workerState, boolean sessioned) {
        Struct configState = new Struct(CONFIG_STATE_V1)
                .set(URL_KEY_NAME, workerState.url())
                .set(CONFIG_OFFSET_KEY_NAME, workerState.offset());
        // Not a big issue if we embed the protocol version with the assignment in the metadata
        Struct allocation = new Struct(ALLOCATION_V1)
                .set(ALLOCATION_KEY_NAME, serializeAssignment(workerState.assignment(), sessioned));
        Struct connectProtocolHeader = sessioned ? CONNECT_PROTOCOL_HEADER_V2 : CONNECT_PROTOCOL_HEADER_V1;
        ByteBuffer buffer = ByteBuffer.allocate(connectProtocolHeader.sizeOf()
                                                + CONFIG_STATE_V1.sizeOf(configState)
                                                + ALLOCATION_V1.sizeOf(allocation));
        connectProtocolHeader.writeTo(buffer);
        CONFIG_STATE_V1.write(buffer, configState);
        ALLOCATION_V1.write(buffer, allocation);
        buffer.flip();
        return buffer;
    }

    /**
     * Returns the collection of Connect protocols that are supported by this version along
     * with their serialized metadata. The protocols are ordered by preference.
     *
     * @param workerState the current state of the worker metadata
     * @param sessioned whether the {@link ConnectProtocolCompatibility#SESSIONED} protocol should
     *                  be included in the collection of supported protocols
     * @return the collection of Connect protocol metadata
     */
    public static JoinGroupRequestProtocolCollection metadataRequest(ExtendedWorkerState workerState, boolean sessioned) {
        // Order matters in terms of protocol preference
        List<JoinGroupRequestProtocol> joinGroupRequestProtocols = new ArrayList<>();
        if (sessioned) {
            joinGroupRequestProtocols.add(new JoinGroupRequestProtocol()
                .setName(SESSIONED.protocol())
                .setMetadata(IncrementalCooperativeConnectProtocol.serializeMetadata(workerState, true).array())
            );
        }
        joinGroupRequestProtocols.add(new JoinGroupRequestProtocol()
                        .setName(COMPATIBLE.protocol())
                        .setMetadata(IncrementalCooperativeConnectProtocol.serializeMetadata(workerState, false).array())
        );
        joinGroupRequestProtocols.add(new JoinGroupRequestProtocol()
                        .setName(EAGER.protocol())
                        .setMetadata(ConnectProtocol.serializeMetadata(workerState).array())
        );
        return new JoinGroupRequestProtocolCollection(joinGroupRequestProtocols.iterator());
    }

    /**
     * Given a byte buffer that contains protocol metadata return the deserialized form of the
     * metadata.
     *
     * @param buffer A buffer containing the protocols metadata
     * @return the deserialized metadata
     * @throws SchemaException on incompatible Connect protocol version
     */
    public static ExtendedWorkerState deserializeMetadata(ByteBuffer buffer) {
        Struct header = CONNECT_PROTOCOL_HEADER_SCHEMA.read(buffer);
        Short version = header.getShort(VERSION_KEY_NAME);
        checkVersionCompatibility(version);
        Struct configState = CONFIG_STATE_V1.read(buffer);
        long configOffset = configState.getLong(CONFIG_OFFSET_KEY_NAME);
        String url = configState.getString(URL_KEY_NAME);
        Struct allocation = ALLOCATION_V1.read(buffer);
        // Protocol version is embedded with the assignment in the metadata
        ExtendedAssignment assignment = deserializeAssignment(allocation.getBytes(ALLOCATION_KEY_NAME));
        return new ExtendedWorkerState(url, configOffset, assignment);
    }

    /**
     * The fields are serialized in sequence as follows:
     * Complete Assignment V1:
     *

     *   Version            => Int16
     *   Error              => Int16
     *   Leader             => [String]
     *   LeaderUrl          => [String]
     *   ConfigOffset       => Int64
     *   Assignment         => [Connector Assignment]
     *   Revoked            => [Connector Assignment]
     *   ScheduledDelay     => Int32
     *

     */
    public static ByteBuffer serializeAssignment(ExtendedAssignment assignment, boolean sessioned) {
        // comparison depends on reference equality for now
        if (assignment == null || ExtendedAssignment.empty().equals(assignment)) {
            return null;
        }
        Struct struct = assignment.toStruct();
        Struct protocolHeader = sessioned ? CONNECT_PROTOCOL_HEADER_V2 : CONNECT_PROTOCOL_HEADER_V1;
        ByteBuffer buffer = ByteBuffer.allocate(protocolHeader.sizeOf()
                                                + ASSIGNMENT_V1.sizeOf(struct));
        protocolHeader.writeTo(buffer);
        ASSIGNMENT_V1.write(buffer, struct);
        buffer.flip();
        return buffer;
    }

    /**
     * Given a byte buffer that contains an assignment as defined by this protocol, return the
     * deserialized form of the assignment.
     *
     * @param buffer the buffer containing a serialized assignment
     * @return the deserialized assignment
     * @throws SchemaException on incompatible Connect protocol version
     */
    public static ExtendedAssignment deserializeAssignment(ByteBuffer buffer) {
        if (buffer == null) {
            return null;
        }
        Struct header = CONNECT_PROTOCOL_HEADER_SCHEMA.read(buffer);
        Short version = header.getShort(VERSION_KEY_NAME);
        checkVersionCompatibility(version);
        Struct struct = ASSIGNMENT_V1.read(buffer);
        return ExtendedAssignment.fromStruct(version, struct);
    }

    private static void checkVersionCompatibility(short version) {
        // check for invalid versions
        if (version < CONNECT_PROTOCOL_V0)
            throw new SchemaException("Unsupported subscription version: " + version);

        // otherwise, assume versions can be parsed
    }

}


text:
            NOMBRE
            CATEGORIA
            PESO
            ESTADO SALUD

            {{item.name}}
            {{item.category}}
            {{item.weight}} kg.

SALUDABLE

ENFERMA

SACRIFICADA

                open_in_new

                edit


text:
package com.portfolioeffect.quant.client.result;

import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TLongArrayList;

import java.io.IOException;

import com.portfolioeffect.quant.client.model.ComputeErrorException;

public class SavedMetric extends AbstractMethodResult{

	private String description="";
	public SavedMetric(double[] value, long[] time) throws IOException {
		setValue(value);
		setTime(time);
	}

	public SavedMetric(TDoubleArrayList value, TLongArrayList time) throws IOException {
		setValue(value.toArray());
		setTime(time.toArray());
	}

	@Override
	protected void computeMetric() throws ComputeErrorException {

	}

	@Override
	public void compute() {

	}

	public void setDescription(String description){
		this.description = description;
	}
	public String getDescription(){
		return description;
	}

}


text:
void check(IntPtr address, DirectoryState::dstate_t dstate, core_id_t owner, unsigned int num_sharers, int tracked_sharers_list, int cached_val, int memory_val);
bool isSharer(core_id_t i, int tracked_sharers_list);

Core** core;
int* core_val;
IntPtr address_0 = (IntPtr) 0x800;
IntPtr address_1 = (IntPtr) 0x400;

enum
{
   CORE1 = 1 << 1,
   CORE2 = 1 << 2,
   CORE3 = 1 << 3
};

int main(int argc, char *argv[])
{
   CarbonStartSim(argc, argv);

   unsigned int total_cores = Sim()->getConfig()->getTotalCores();
   core = new Core*[total_cores];
   core_val = new int[total_cores];

   // Let have 4 application cores for now
   for (core_id_t i = 0; i < total_cores; i++)
   {
      core[i] = Sim()->getCoreManager()->getTileFromID(i)->getCore();
      core_val[i] = i * 100;
   }

   int buf = 0;

   core[1]->accessMemory(Core::NONE, Core::WRITE, address_0, (char*) &core_val[1], sizeof(core_val[1]));
   // Core1 writes address_0
   // Assertions:
   // [[address_0]]
   // State -> MODIFIED
   // num sharers -> 1
   // Owner -> Core1
   sleep(1);
   check(address_0, DirectoryState::MODIFIED, 1, 1, CORE1, 100, 0);
   printf("Test1 Passed\n");

   core[2]->accessMemory(Core::NONE, Core::READ, address_0, (char*) &buf, sizeof(buf));
   // Core2 reads address_0
   // Assertions:
   // [[address_0]]
   // State -> OWNED
   // num sharers -> 2
   // Owner -> Core1
   sleep(1);
   check(address_0, DirectoryState::OWNED, 1, 2, CORE1, 100, 0);
   printf("Test2 Passed\n");

   core[3]->accessMemory(Core::NONE, Core::READ, address_0, (char*) &buf, sizeof(buf));
   // Core3 reads address_0
   // Assertions:
   // [[address_0]]
   // State -> OWNED
   // num sharers -> 3
   // Owner -> Core1
   sleep(1);
   check(address_0, DirectoryState::OWNED, 1, 3, CORE1, 100, 0);
   printf("Test3 Passed\n");

   core[1]->accessMemory(Core::NONE, Core::READ, address_1, (char*) &buf, sizeof(buf));
   // Core1 reads address_1
   // Assertions:
   // [[address_0]]
   // State -> SHARED
   // num sharers -> 2
   // Owner -> INVALID_CORE_ID
   // [[address_1]]
   // State -> SHARED
   // num sharers -> 1
   // Owner -> INVALID_CORE_ID
   sleep(1);
   check(address_0, DirectoryState::SHARED, INVALID_CORE_ID, 2, 0, 100, 100);
   check(address_1, DirectoryState::SHARED, INVALID_CORE_ID, 1, CORE1, 0, 0);
   printf("Test4 Passed\n");

   core[2]->accessMemory(Core::NONE, Core::WRITE, address_0, (char*) &core_val[2], sizeof(core_val[2]));
   // Core2 writes address_0
   // Assertions:
   // [[address_0]]
   // State -> MODIFIED
   // num sharers -> 1
   // Owner -> Core2
   sleep(1);
   check(address_0, DirectoryState::MODIFIED, 2, 1, CORE2, 200, 100);
   printf("Test5 Passed\n");

   core[2]->accessMemory(Core::NONE, Core::READ, address_1, (char*) &buf, sizeof(buf));
   // Core2 reads address_1
   // Assertions:
   // [[address_0]]
   // State -> UNCACHED
   // num sharers -> 0
   // Owner -> INVALID_CORE_ID
   // [[address_1]]
   // State -> SHARED
   // num sharers -> 2
   // Owner -> INVALID_CORE_ID
   sleep(1);
   check(address_0, DirectoryState::UNCACHED, INVALID_CORE_ID, 0, 0, 0, 200);
   check(address_1, DirectoryState::SHARED, INVALID_CORE_ID, 2, CORE1, 0, 0);
   printf("Test6 Passed\n");

   core[3]->accessMemory(Core::NONE, Core::WRITE, address_1, (char*) &core_val[3], sizeof(core_val[3]));
   // Core3 writes address_1
   // Assertions:
   // [[address_1]]
   // State -> MODIFIED
   // num sharers -> 1
   // Owner -> Core3
   sleep(1);
   check(address_1, DirectoryState::MODIFIED, 3, 1, CORE3, 300, 0);
   printf("Test7 Passed\n");

   core[1]->accessMemory(Core::NONE, Core::READ, address_0, (char*) &buf, sizeof(buf));
   // Core1 reads address_0
   // Assertions:
   // [[address_0]]
   // State -> SHARED
   // num sharers -> 1
   // Owner -> INVALID_CORE_ID
   sleep(1);
   check(address_0, DirectoryState::SHARED, INVALID_CORE_ID, 1, CORE1, 200, 200);
   printf("Test8 Passed\n");

   core[1]->accessMemory(Core::NONE, Core::WRITE, address_0, (char*) &core_val[1], sizeof(core_val[1]));
   // Core1 writes address_0
   // Assertions:
   // [[address_0]]
   // State -> MODIFIED
   // num sharers -> 1
   // Owner -> Core1
   sleep(1);
   check(address_0, DirectoryState::MODIFIED, 1, 1, CORE1, 100, 200);
   printf("Test9 Passed\n");

   core[3]->accessMemory(Core::NONE, Core::READ, address_0, (char*) &buf, sizeof(buf));
   // Core3 reads address_0
   // Assertions:
   // [[address_0]]
   // State -> OWNED
   // num sharers -> 2
   // Owner -> Core1
   sleep(1);
   check(address_0, DirectoryState::OWNED, 1, 2, CORE1, 100, 200);
   check(address_1, DirectoryState::UNCACHED, INVALID_CORE_ID, 0, 0, 0, 300);
   printf("Test10 Passed\n");
   printf("All Tests Passed\n");

   CarbonStopSim();
   return 0;
}

void check(IntPtr address, DirectoryState::dstate_t dstate, core_id_t owner, unsigned int num_sharers, int tracked_sharers_list, int cached_val, int memory_val)
{
   printf("--> Checking address(0x%x)\n", address);

   for (core_id_t i = 1; i <= 3; i++)
   {
      PrL1PrL2DramDirectoryMOSI::MemoryManager* memory_manager = (PrL1PrL2DramDirectoryMOSI::MemoryManager*) core[i]->getMemoryManager();
      Cache* pr_l1_dcache = memory_manager->getL1DCache();
      Cache* pr_l2_cache = memory_manager->getL2Cache();

      CacheState::cstate_t actual_l1d_cstate;
      CacheState::cstate_t actual_l2_cstate;
      int actual_l1d_cached_val;
      int actual_l2_cached_val;
      int actual_cached_val;

      PrL1CacheBlockInfo* pr_l1_cache_block_info = (PrL1CacheBlockInfo*) pr_l1_dcache->accessSingleLine(address, CacheBase::LOAD, (Byte*) &actual_l1d_cached_val, sizeof(int));
      PrL2CacheBlockInfo* pr_l2_cache_block_info = (PrL2CacheBlockInfo*) pr_l2_cache->accessSingleLine(address, CacheBase::LOAD, (Byte*) &actual_l2_cached_val, sizeof(int));

      assert((pr_l1_cache_block_info == NULL) == (pr_l2_cache_block_info == NULL));

      if (pr_l1_cache_block_info)
      {
         actual_l1d_cstate = pr_l1_cache_block_info->getCState();
         actual_l2_cstate = pr_l2_cache_block_info->getCState();
         assert(pr_l2_cache_block_info->getCachedLoc() == MemComponent::L1_DCACHE);

         assert(actual_l1d_cached_val == actual_l2_cached_val);
         actual_cached_val = actual_l1d_cached_val;
      }
      else
      {
         actual_l1d_cstate = CacheState::INVALID;
         actual_l2_cstate = CacheState::INVALID;

         actual_cached_val = 0;
      }

      switch(dstate)
      {
         case DirectoryState::MODIFIED:
            if (owner == i)
            {
               assert(actual_l1d_cstate == CacheState::MODIFIED);
               assert(actual_l2_cstate == CacheState::MODIFIED);
               assert(actual_cached_val == cached_val);
            }
            else
            {
               assert(actual_l1d_cstate == CacheState::INVALID);
               assert(actual_l2_cstate == CacheState::INVALID);
            }
            break;

         case DirectoryState::OWNED:
            if (owner == i)
            {
               assert(actual_l1d_cstate == CacheState::OWNED);
               assert(actual_l2_cstate == CacheState::OWNED);
               assert(actual_cached_val == cached_val);
            }
            else
            {
               if (isSharer(i, tracked_sharers_list))
               {
                  assert(actual_l1d_cstate == CacheState::SHARED);
                  assert(actual_l2_cstate == CacheState::SHARED);
                  assert(actual_cached_val == cached_val);
               }
               else
               {
                  assert((actual_l1d_cstate == CacheState::INVALID) || (actual_l1d_cstate == CacheState::SHARED));
                  assert((actual_l2_cstate == CacheState::INVALID) || (actual_l2_cstate == CacheState::SHARED));
                  if (actual_l1d_cstate == CacheState::SHARED)
                     assert(actual_cached_val == cached_val);
               }
            }
            break;

         case DirectoryState::SHARED:
            if (isSharer(i, tracked_sharers_list))
            {
               assert(actual_l1d_cstate == CacheState::SHARED);
               assert(actual_l2_cstate == CacheState::SHARED);
               assert(actual_cached_val == cached_val);
            }
            else
            {
               assert((actual_l1d_cstate == CacheState::INVALID) || (actual_l1d_cstate == CacheState::SHARED));
               assert((actual_l2_cstate == CacheState::INVALID) || (actual_l2_cstate == CacheState::SHARED));
               if (actual_l1d_cstate == CacheState::SHARED)
                  assert(actual_cached_val == cached_val);
            }
            break;

         case DirectoryState::UNCACHED:
            assert(actual_l1d_cstate == CacheState::INVALID);
            assert(actual_l2_cstate == CacheState::INVALID);
            break;

         default:
            assert(false);
            break;
      }
   }

   PrL1PrL2DramDirectoryMOSI::MemoryManager* memory_manager = (PrL1PrL2DramDirectoryMOSI::MemoryManager*) core[0]->getMemoryManager();
   AddressHomeLookup* dram_dir_home_lookup = memory_manager->getDramDirectoryHomeLookup();
   core_id_t home = dram_dir_home_lookup->getHome(address);

   PrL1PrL2DramDirectoryMOSI::MemoryManager* home_memory_manager = (PrL1PrL2DramDirectoryMOSI::MemoryManager*) core[home]->getMemoryManager();
   PrL1PrL2DramDirectoryMOSI::DramDirectoryCache* dram_dir_cache = home_memory_manager->getDramDirectoryCache();

   DirectoryEntryLimitedBroadcast* dir_entry = (DirectoryEntryLimitedBroadcast*) dram_dir_cache->getDirectoryEntry(address);
   DirectoryBlockInfo* dir_block_info = dir_entry->getDirectoryBlockInfo();

   LOG_ASSERT_ERROR(dir_block_info->getDState() == dstate, "expected state(%u), actual state(%u)",
         dstate, dir_block_info->getDState());
   assert(dir_entry->getOwner() == owner);
   LOG_ASSERT_ERROR(dir_entry->getNumSharers() == num_sharers, "dir_entry->numSharers(%u), num_sharers(%u)", dir_entry->getNumSharers(), num_sharers);
   for (core_id_t i = 1; i <= 3; i++)
   {
      assert(dir_entry->hasSharer(i) == isSharer(i, tracked_sharers_list));
   }

   PrL1PrL2DramDirectoryMOSI::DramCntlr* home_dram_cntlr = (PrL1PrL2DramDirectoryMOSI::DramCntlr*) home_memory_manager->getDramCntlr();
   UInt32 cache_block_size = home_memory_manager->getCacheBlockSize();
   Byte data_buf[cache_block_size];
   home_dram_cntlr->getDataFromDram(address, Sim()->getCoreManager()->getCurrentCore()->getId(), data_buf);
   int actual_memory_val = *((int*) &data_buf[address & (cache_block_size-1)]);
   assert(actual_memory_val == memory_val);
}

bool isSharer(core_id_t i, int tracked_sharers_list)
{
   if (tracked_sharers_list & (1 << i))
      return true;
   else
      return false;
}


text:
from flask import render_template, redirect, url_for, abort, flash
from flask_login import login_required, current_user
from . import main
from .forms import EditProfileForm, EditProfileAdminForm
from .. import db
from ..models import Role, User
from ..decorators import admin_required

@main.route('/')
def index():
    return render_template('index.html')

@main.route('/user/<username>')
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    return render_template('user.html', user=user)

@main.route('/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user)
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)

@main.route('/edit-profile/<int:id>', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
    user = User.query.get_or_404(id)
    form = EditProfileAdminForm(user=user)
    if form.validate_on_submit():
        user.email = form.email.data
        user.username = form.username.data
        user.confirmed = form.confirmed.data
        user.role = Role.query.get(form.role.data)
        user.name = form.name.data
        user.location = form.location.data
        user.about_me = form.about_me.data
        db.session.add(user)
        flash('The profile has been updated.')
        return redirect(url_for('.user', username=user.username))
    form.email.data = user.email
    form.username.data = user.username
    form.confirmed.data = user.confirmed
    form.role.data = user.role_id
    form.name.data = user.name
    form.location.data = user.location
    form.about_me.data = user.about_me
    return render_template('edit_profile.html', form=form, user=user)


text:
namespace ClosedXML.Excel
{
    public interface IXLPivotStyleFormat
    {
        XLPivotStyleFormatElement AppliesTo { get; }
        IXLPivotField PivotField { get; }
        IXLStyle Style { get; set; }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. natn. Sci. Mus. , Tokyo, B 1: 44 (1975)

#### Original name
Parmelia schistacea Kurok. & Filson

### Remarks
null


text:
<?php

/*
 * This file is part of the Symcloud Distributed-Storage.
 *
 * (c) Symcloud and Johannes Wachter
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symcloud\Component\Database\Metadata;

use Symcloud\Component\Database\Model\ModelInterface;

interface MetadataManagerInterface
{
    /**
     * @param ModelInterface $object
     *
     * @return ClassMetadataInterface
     */
    public function loadByModel(ModelInterface $object);

    /**
     * @param string $className
     *
     * @return ClassMetadataInterface
     */
    public function loadByClassname($className);
}


text:
package io.quarkus.arquillian.test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.testng.AssertJUnit.assertNotNull;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Qualifier;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit5.ArquillianExtension;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

/**
 * Tests injection of parameter values into @Test methods.
 */
@ExtendWith(ArquillianExtension.class)
@Disabled
public class MethodParameterInjectionTest {

    @Deployment
    public static JavaArchive createTestArchive() {
        return ShrinkWrap.create(JavaArchive.class).addClasses(AppScopedBean1.class, AppScopedBean2.class);
    }

    @Test
    public void injectOneApplicationScopedBean(AppScopedBean1 param) {
        assertNotNull("Method param was not injected", param);
        assertNotNull("@Inject did not work", injected);
        assertEquals(injected, param);
    }

    @Test
    public void injectTwoApplicationScopedBeans(AppScopedBean1 param1, AppScopedBean2 param2) {
        assertNotNull("Method param was not injected", param1);
        assertNotNull("Method param was not injected", param2);
    }

    @Test
    public void injectFromProducer(OtherBean param1, OtherBean param2) {
        assertNotNull(param1);
        assertNotNull(param2);
        assertNotSame(param1, param2);
    }

    @Test
    public void injectWithQualifier(@Good X param) {
        assertNotNull(param);
        assertTrue(Y.class.isAssignableFrom(param.getClass()));
        assertFalse(Z.class.isAssignableFrom(param.getClass()));
    }

    public interface X {

    }

    @Good
    @ApplicationScoped
    public static class Y implements X {

    }

    @Bad
    @ApplicationScoped
    public static class Z implements X {

    }

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
    public @interface Good {
    }

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
    public @interface Bad {
    }

    @Inject
    AppScopedBean1 injected;

    @Inject
    AppScopedBean2 injected2;

    @Inject
    @Good
    X yInstance;

    @Inject
    @Bad
    X zInstance;

    @Produces
    @Dependent
    OtherBean producer() {
        return new OtherBean();
    }

    @ApplicationScoped
    public static class AppScopedBean1 {

    }

    @ApplicationScoped
    public static class AppScopedBean2 {

    }

    public static class OtherBean {

    }

}


text:
package test

import (
	. "github.com/divan/depscheck/test/sample"
)

func Xtest() {
	SampleFunc()
	var foo Foo
	foo.Bar()
}


text:
<?php

/**
 * VideoRecordingFormatType filter form base class.
 *
 * @package    mediaSCORE
 * @subpackage filter
 * @author     Nouman Tayyab
 * @version    SVN: $Id: sfDoctrineFormFilterGeneratedInheritanceTemplate.php 29570 2010-05-21 14:49:47Z Kris.Wallsmith $
 */
abstract class BaseVideoRecordingFormatTypeFormFilter extends FormatTypeFormFilter
{
  protected function setupInheritance()
  {
    parent::setupInheritance();

    $this->widgetSchema->setNameFormat('video_recording_format_type_filters[%s]');
  }

  public function getModelName()
  {
    return 'VideoRecordingFormatType';
  }
}


text:
<?php

// Start of AMQPQueue from php-amqp v.1.4.0beta2

/**
 * stub class representing AMQPQueue from pecl-amqp
 * @jms-builtin
 */
class AMQPQueue
{
    /**
     * Acknowledge the receipt of a message.
     *
     * This method allows the acknowledgement of a message that is retrieved
     * without the AMQP_AUTOACK flag through AMQPQueue::get() or
     * AMQPQueue::consume()
     *
     * @param string  $delivery_tag The message delivery tag of which to
     *                              acknowledge receipt.
     * @param integer $flags        The only valid flag that can be passed is
     *                              AMQP_MULTIPLE.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function ack($delivery_tag, $flags = AMQP_NOPARAM)
    {
    }

    /**
     * Bind the given queue to a routing key on an exchange.
     *
     * @param string $exchange_name Name of the exchange to bind to.
     * @param string $routing_key   Pattern or routing key to bind with.
     * @param array  $arguments     Additional binding arguments.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function bind($exchange_name, $routing_key = null, array $arguments = array())
    {
    }

    /**
     * Cancel a queue that is already bound to an exchange and routing key.
     *
     * @param string $consumer_tag The queue name to cancel, if the queue
     *                             object is not already representative of
     *                             a queue.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return bool;
     */
    public function cancel($consumer_tag = '')
    {
    }

    /**
     * Create an instance of an AMQPQueue object.
     *
     * @param AMQPChannel $amqp_channel The amqp channel to use.
     *
     * @throws AMQPQueueException      When amqp_channel is not connected to a
     *                                 broker.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     */
    public function __construct(AMQPChannel $amqp_channel)
    {
    }

    /**
     * Consume messages from a queue.
     *
     * Blocking function that will retrieve the next message from the queue as
     * it becomes available and will pass it off to the callback.
     *
     * @param callable $callback    A callback function to which the
     *                              consumed message will be passed. The
     *                              function must accept at a minimum
     *                              one parameter, an AMQPEnvelope object,
     *                              and an optional second parameter
     *                              the AMQPQueue from which the message was
     *                              consumed. The AMQPQueue::consume() will
     *                              not return the processing thread back to
     *                              the PHP script until the callback
     *                              function returns FALSE.
     * @param integer  $flags       A bitmask of any of the flags: AMQP_AUTOACK.
     * @param string   $consumerTag A string describing this consumer. Used
     *                              for canceling subscriptions with cancel().
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return void
     */
    public function consume(
        callable $callback,
        $flags = AMQP_NOPARAM,
        $consumerTag = null
    ) {
    }

    /**
     * Declare a new queue on the broker.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return integer the message count.
     */
    public function declareQueue()
    {
    }

    /**
     * Delete a queue from the broker.
     *
     * This includes its entire contents of unread or unacknowledged messages.
     *
     * @param integer $flags        Optionally AMQP_IFUNUSED can be specified
     *                              to indicate the queue should not be
     *                              deleted until no clients are connected to
     *                              it.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return integer The number of deleted messages.
     */
    public function delete($flags = AMQP_NOPARAM)
    {
    }

    /**
     * Retrieve the next message from the queue.
     *
     * Retrieve the next available message from the queue. If no messages are
     * present in the queue, this function will return FALSE immediately. This
     * is a non blocking alternative to the AMQPQueue::consume() method.
     * Currently, the only supported flag for the flags parameter is
     * AMQP_AUTOACK. If this flag is passed in, then the message returned will
     * automatically be marked as acknowledged by the broker as soon as the
     * frames are sent to the client.
     *
     * @param integer $flags A bitmask of supported flags for the
     *                       method call. Currently, the only the
     *                       supported flag is AMQP_AUTOACK. If this
     *                       value is not provided, it will use the
     *                       value of ini-setting amqp.auto_ack.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return AMQPEnvelope|boolean
     */
    public function get($flags = AMQP_NOPARAM)
    {
    }

    /**
     * Get the argument associated with the given key.
     *
     * @param string $key The key to look up.
     *
     * @return string|integer|boolean The string or integer value associated
     *                                with the given key, or false if the key
     *                                is not set.
     */
    public function getArgument($key)
    {
    }

    /**
     * Get all set arguments as an array of key/value pairs.
     *
     * @return array An array containing all of the set key/value pairs.
     */
    public function getArguments()
    {
    }

    /**
     * Get all the flags currently set on the given queue.
     *
     * @return int An integer bitmask of all the flags currently set on this
     *             exchange object.
     */
    public function getFlags()
    {
    }

    /**
     * Get the configured name.
     *
     * @return string The configured name as a string.
     */
    public function getName()
    {
    }

    /**
     * Mark a message as explicitly not acknowledged.
     *
     * Mark the message identified by delivery_tag as explicitly not
     * acknowledged. This method can only be called on messages that have not
     * yet been acknowledged, meaning that messages retrieved with by
     * AMQPQueue::consume() and AMQPQueue::get() and using the AMQP_AUTOACK
     * flag are not eligible. When called, the broker will immediately put the
     * message back onto the queue, instead of waiting until the connection is
     * closed. This method is only supported by the RabbitMQ broker. The
     * behavior of calling this method while connected to any other broker is
     * undefined.
     *
     * @param string  $delivery_tag Delivery tag of last message to reject.
     * @param integer $flags        AMQP_REQUEUE to requeue the message(s),
     *                              AMQP_MULTIPLE to nack all previous
     *                              unacked messages as well.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function nack($delivery_tag, $flags = AMQP_NOPARAM)
    {
    }

    /**
     * Mark one message as explicitly not acknowledged.
     *
     * Mark the message identified by delivery_tag as explicitly not
     * acknowledged. This method can only be called on messages that have not
     * yet been acknowledged, meaning that messages retrieved with by
     * AMQPQueue::consume() and AMQPQueue::get() and using the AMQP_AUTOACK
     * flag are not eligible.
     *
     * @param string  $delivery_tag Delivery tag of the message to reject.
     * @param integer $flags        AMQP_REQUEUE to requeue the message(s).
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function reject($delivery_tag, $flags = AMQP_NOPARAM)
    {
    }

    /**
     * Purge the contents of a queue.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function purge()
    {
    }

    /**
     * Set a queue argument.
     *
     * @param string $key   The key to set.
     * @param mixed  $value The value to set.
     *
     * @return boolean
     */
    public function setArgument($key, $value)
    {
    }

    /**
     * Set all arguments on the given queue.
     *
     * All other argument settings will be wiped.
     *
     * @param array $arguments An array of key/value pairs of arguments.
     *
     * @return boolean
     */
    public function setArguments(array $arguments)
    {
    }

    /**
     * Set the flags on the queue.
     *
     * @param integer $flags A bitmask of flags:
     *                       AMQP_DURABLE, AMQP_PASSIVE,
     *                       AMQP_EXCLUSIVE, AMQP_AUTODELETE.
     *
     * @return boolean
     */
    public function setFlags($flags)
    {
    }

    /**
     * Set the queue name.
     *
     * @param string $queue_name The name of the queue.
     *
     * @return boolean
     */
    public function setName($queue_name)
    {
    }

    /**
     * Remove a routing key binding on an exchange from the given queue.
     *
     * @param string $exchange_name The name of the exchange on which the
     *                              queue is bound.
     * @param string $routing_key   The binding routing key used by the
     *                              queue.
     * @param array  $arguments     Additional binding arguments.
     *
     * @throws AMQPChannelException    If the channel is not open.
     * @throws AMQPConnectionException If the connection to the broker was lost.
     *
     * @return boolean
     */
    public function unbind($exchange_name, $routing_key = null, array $arguments = array())
    {
    }

    /**
     * Get the AMQPChannel object in use
     *
     * @return AMQPChannel
     */
    public function getChannel()
    {
    }

    /**
     * Get the AMQPConnection object in use
     *
     * @return AMQPConnection
     */
    public function getConnection()
    {
    }
}

// End of AMQPQueue from php-amqp v.1.4.0beta2
?>


text:
package org.ovirt.engine.core.bll;

import java.util.List;

import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.hostinstall.IVdsInstallerCallback;
import org.ovirt.engine.core.utils.hostinstall.VdsInstallerSSH;
import org.ovirt.engine.core.utils.linq.LinqUtils;
import org.ovirt.engine.core.utils.linq.Predicate;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;

/**
 * Class designed to provide connectivity to host and retrieval of its unique-id in order to validate host status before
 * starting the installation flow.
 */
public class VdsInstallHelper{

    private VdsInstallerSSH wrapper;
    private SimpleCallback callback;
    private String server;

    public VdsInstallHelper() {
        callback = new SimpleCallback();
        wrapper = new VdsInstallerSSH();
        wrapper.setCallback(callback);
    }

    public boolean connectToServer(String server, String passwd, long timeout) {
        this.server = server;
        return wrapper.connect(server, passwd, timeout);
    }

    public String getServerUniqueId() {
        wrapper.executeCommand(
            Config.<String> GetValue(ConfigValues.BootstrapNodeIDCommand)
        );
        String serverUniqueId = callback.serverUniqueId.trim();
        if (serverUniqueId.isEmpty()) {
            throw new RuntimeException(
                String.format(
                    "Got empty unique id from host '%1$s'",
                    server
                )
            );
        }
        return serverUniqueId;
    }

    public void shutdown() {
        wrapper.shutdown();
        wrapper = null;
        callback = null;
    }

    public static List<VDS> getVdssByUniqueId(final Guid vdsId, String uniqueIdToCheck) {
        List<VDS> list = DbFacade.getInstance().getVdsDao().getAllWithUniqueId(uniqueIdToCheck);
        return LinqUtils.filter(list, new Predicate<VDS>() {
            @Override
            public boolean eval(VDS vds) {
                return !vds.getId().equals(vdsId);
            }
        });
    }

    public static boolean isVdsUnique(final Guid vdsId, String uniqueIdToCheck) {
        return getVdssByUniqueId(vdsId, uniqueIdToCheck).isEmpty();
    }

    private class SimpleCallback implements IVdsInstallerCallback {

        String serverUniqueId;

        @Override
        public void addError(String error) {
        }

        @Override
        public void addMessage(String message) {
            serverUniqueId = message;
        }

        @Override
        public void connected() {
        }

        @Override
        public void endTransfer() {
        }

        @Override
        public void failed(String error) {
        }

    }
}