text:
from __future__ import division
from __future__ import print_function

import sys

import os as os
import numpy as np

# can be sentence or word
input_mask_mode = "sentence"

# adapted from https://github.com/YerevaNN/Dynamic-memory-networks-in-Theano/
def init_babi(fname):

    print("==> Loading test from %s" % fname)
    tasks = []
    task = None
    for i, line in enumerate(open(fname)):
        id = int(line[0:line.find(' ')])
        if id == 1:
            task = {"C": "", "Q": "", "A": "", "S": ""}
            counter = 0
            id_map = {}

        line = line.strip()
        line = line.replace('.', ' . ')
        line = line[line.find(' ')+1:]
        # if not a question
        if line.find('?') == -1:
            task["C"] += line
            id_map[id] = counter
            counter += 1

        else:
            idx = line.find('?')
            tmp = line[idx+1:].split('\t')
            task["Q"] = line[:idx]
            task["A"] = tmp[1].strip()
            task["S"] = []
            for num in tmp[2].split():
                task["S"].append(id_map[int(num.strip())])
            tasks.append(task.copy())

    return tasks

def get_babi_raw(id, test_id):
    babi_map = {
        "1": "qa1_single-supporting-fact",
        "2": "qa2_two-supporting-facts",
        "3": "qa3_three-supporting-facts",
        "4": "qa4_two-arg-relations",
        "5": "qa5_three-arg-relations",
        "6": "qa6_yes-no-questions",
        "7": "qa7_counting",
        "8": "qa8_lists-sets",
        "9": "qa9_simple-negation",
        "10": "qa10_indefinite-knowledge",
        "11": "qa11_basic-coreference",
        "12": "qa12_conjunction",
        "13": "qa13_compound-coreference",
        "14": "qa14_time-reasoning",
        "15": "qa15_basic-deduction",
        "16": "qa16_basic-induction",
        "17": "qa17_positional-reasoning",
        "18": "qa18_size-reasoning",
        "19": "qa19_path-finding",
        "20": "qa20_agents-motivations",
        "MCTest": "MCTest",
        "19changed": "19changed",
        "joint": "all_shuffled",
        "sh1": "../shuffled/qa1_single-supporting-fact",
        "sh2": "../shuffled/qa2_two-supporting-facts",
        "sh3": "../shuffled/qa3_three-supporting-facts",
        "sh4": "../shuffled/qa4_two-arg-relations",
        "sh5": "../shuffled/qa5_three-arg-relations",
        "sh6": "../shuffled/qa6_yes-no-questions",
        "sh7": "../shuffled/qa7_counting",
        "sh8": "../shuffled/qa8_lists-sets",
        "sh9": "../shuffled/qa9_simple-negation",
        "sh10": "../shuffled/qa10_indefinite-knowledge",
        "sh11": "../shuffled/qa11_basic-coreference",
        "sh12": "../shuffled/qa12_conjunction",
        "sh13": "../shuffled/qa13_compound-coreference",
        "sh14": "../shuffled/qa14_time-reasoning",
        "sh15": "../shuffled/qa15_basic-deduction",
        "sh16": "../shuffled/qa16_basic-induction",
        "sh17": "../shuffled/qa17_positional-reasoning",
        "sh18": "../shuffled/qa18_size-reasoning",
        "sh19": "../shuffled/qa19_path-finding",
        "sh20": "../shuffled/qa20_agents-motivations",
    }
    if (test_id == ""):
        test_id = id
    babi_name = babi_map[id]
    babi_test_name = babi_map[test_id]
    babi_train_raw = init_babi(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/en-10k/%s_train.txt' % babi_name))
    babi_test_raw = init_babi(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data/en-10k/%s_test.txt' % babi_test_name))
    return babi_train_raw, babi_test_raw

def load_glove(dim):
    word2vec = {}

    print("==> loading glove")
    with open(("./data/glove/glove.6B/glove.6B." + str(dim) + "d.txt")) as f:
        for line in f:
            l = line.split()
            word2vec[l[0]] = map(float, l[1:])

    print("==> glove is loaded")

    return word2vec

def create_vector(word, word2vec, word_vector_size, silent=True):
    # if the word is missing from Glove, create some fake vector and store in glove!
    vector = np.random.uniform(0.0,1.0,(word_vector_size,))
    word2vec[word] = vector
    if (not silent):
        print("utils.py::create_vector => %s is missing" % word)
    return vector

def process_word(word, word2vec, vocab, ivocab, word_vector_size, to_return="word2vec", silent=True):
    if not word in word2vec:
        create_vector(word, word2vec, word_vector_size, silent)
    if not word in vocab:
        next_index = len(vocab)
        vocab[word] = next_index
        ivocab[next_index] = word

    if to_return == "word2vec":
        return word2vec[word]
    elif to_return == "index":
        return vocab[word]
    elif to_return == "onehot":
        raise Exception("to_return = 'onehot' is not implemented yet")

def process_input(data_raw, floatX, word2vec, vocab, ivocab, embed_size, split_sentences=False):
    questions = []
    inputs = []
    answers = []
    input_masks = []
    for x in data_raw:
        if split_sentences:
            inp = x["C"].lower().split(' . ')
            inp = [w for w in inp if len(w) > 0]
            inp = [i.split() for i in inp]
        else:
            inp = x["C"].lower().split(' ')
            inp = [w for w in inp if len(w) > 0]

        q = x["Q"].lower().split(' ')
        q = [w for w in q if len(w) > 0]

        if split_sentences:
            inp_vector = [[process_word(word = w,
                                        word2vec = word2vec,
                                        vocab = vocab,
                                        ivocab = ivocab,
                                        word_vector_size = embed_size,
                                        to_return = "index") for w in s] for s in inp]
        else:
            inp_vector = [process_word(word = w,
                                        word2vec = word2vec,
                                        vocab = vocab,
                                        ivocab = ivocab,
                                        word_vector_size = embed_size,
                                        to_return = "index") for w in inp]

        q_vector = [process_word(word = w,
                                    word2vec = word2vec,
                                    vocab = vocab,
                                    ivocab = ivocab,
                                    word_vector_size = embed_size,
                                    to_return = "index") for w in q]

        if split_sentences:
            inputs.append(inp_vector)
        else:
            inputs.append(np.vstack(inp_vector).astype(floatX))
        questions.append(np.vstack(q_vector).astype(floatX))
        answers.append(process_word(word = x["A"],
                                        word2vec = word2vec,
                                        vocab = vocab,
                                        ivocab = ivocab,
                                        word_vector_size = embed_size,
                                        to_return = "index"))
        # NOTE: here we assume the answer is one word!

        if not split_sentences:
            if input_mask_mode == 'word':
                input_masks.append(np.array([index for index, w in enumerate(inp)], dtype=np.int32))
            elif input_mask_mode == 'sentence':
                input_masks.append(np.array([index for index, w in enumerate(inp) if w == '.'], dtype=np.int32))
            else:
                raise Exception("invalid input_mask_mode")

    return inputs, questions, answers, input_masks

def get_lens(inputs, split_sentences=False):
    lens = np.zeros((len(inputs)), dtype=int)
    for i, t in enumerate(inputs):
        lens[i] = t.shape[0]
    return lens

def get_sentence_lens(inputs):
    lens = np.zeros((len(inputs)), dtype=int)
    sen_lens = []
    max_sen_lens = []
    for i, t in enumerate(inputs):
        sentence_lens = np.zeros((len(t)), dtype=int)
        for j, s in enumerate(t):
            sentence_lens[j] = len(s)
        lens[i] = len(t)
        sen_lens.append(sentence_lens)
        max_sen_lens.append(np.max(sentence_lens))
    return lens, sen_lens, max(max_sen_lens)

def pad_inputs(inputs, lens, max_len, mode="", sen_lens=None, max_sen_len=None):
    if mode == "mask":
        padded = [np.pad(inp, (0, max_len - lens[i]), 'constant', constant_values=0) for i, inp in enumerate(inputs)]
        return np.vstack(padded)

    elif mode == "split_sentences":
        padded = np.zeros((len(inputs), max_len, max_sen_len))
        for i, inp in enumerate(inputs):
            padded_sentences = [np.pad(s, (0, max_sen_len - sen_lens[i][j]), 'constant', constant_values=0) for j, s in enumerate(inp)]
            # trim array according to max allowed inputs
            if len(padded_sentences) > max_len:
                padded_sentences = padded_sentences[(len(padded_sentences)-max_len):]
                lens[i] = max_len
            padded_sentences = np.vstack(padded_sentences)
            padded_sentences = np.pad(padded_sentences, ((0, max_len - lens[i]),(0,0)), 'constant', constant_values=0)
            padded[i] = padded_sentences
        return padded

    padded = [np.pad(np.squeeze(inp, axis=1), (0, max_len - lens[i]), 'constant', constant_values=0) for i, inp in enumerate(inputs)]
    return np.vstack(padded)

def create_embedding(word2vec, ivocab, embed_size):
    embedding = np.zeros((len(ivocab), embed_size))
    for i in range(len(ivocab)):
        word = ivocab[i]
        embedding[i] = word2vec[word]
    return embedding

def load_babi(config, split_sentences=False):
    vocab = {}
    ivocab = {}

    babi_train_raw, babi_test_raw = get_babi_raw(config.babi_id, config.babi_test_id)

    if config.word2vec_init:
        assert config.embed_size == 100
        word2vec = load_glove(config.embed_size)
    else:
        word2vec = {}

    # set word at index zero to be end of sentence token so padding with zeros is consistent
    process_word(word = "<eos>",
                word2vec = word2vec,
                vocab = vocab,
                ivocab = ivocab,
                word_vector_size = config.embed_size,
                to_return = "index")

    print('==> get train inputs')
    train_data = process_input(babi_train_raw, config.floatX, word2vec, vocab, ivocab, config.embed_size, split_sentences)
    print('==> get test inputs')
    test_data = process_input(babi_test_raw, config.floatX, word2vec, vocab, ivocab, config.embed_size, split_sentences)

    if config.word2vec_init:
        assert config.embed_size == 100
        word_embedding = create_embedding(word2vec, ivocab, config.embed_size)
    else:
        word_embedding = np.random.uniform(-config.embedding_init, config.embedding_init, (len(ivocab), config.embed_size))

    inputs, questions, answers, input_masks = train_data if config.train_mode else test_data

    if split_sentences:
        input_lens, sen_lens, max_sen_len = get_sentence_lens(inputs)
        max_mask_len = max_sen_len
    else:
        input_lens = get_lens(inputs)
        mask_lens = get_lens(input_masks)
        max_mask_len = np.max(mask_lens)

    q_lens = get_lens(questions)

    max_q_len = np.max(q_lens)
    max_input_len = min(np.max(input_lens), config.max_allowed_inputs)

    #pad out arrays to max
    if split_sentences:
        inputs = pad_inputs(inputs, input_lens, max_input_len, "split_sentences", sen_lens, max_sen_len)
        input_masks = np.zeros(len(inputs))
    else:
        inputs = pad_inputs(inputs, input_lens, max_input_len)
        input_masks = pad_inputs(input_masks, mask_lens, max_mask_len, "mask")

    questions = pad_inputs(questions, q_lens, max_q_len)

    answers = np.stack(answers)

    if config.train_mode:
        train = questions[:config.num_train], inputs[:config.num_train], q_lens[:config.num_train], input_lens[:config.num_train], input_masks[:config.num_train], answers[:config.num_train]

        valid = questions[config.num_train:], inputs[config.num_train:], q_lens[config.num_train:], input_lens[config.num_train:], input_masks[config.num_train:], answers[config.num_train:]
        return train, valid, word_embedding, max_q_len, max_input_len, max_mask_len, len(vocab)

    else:
        test = questions, inputs, q_lens, input_lens, input_masks, answers
        return test, word_embedding, max_q_len, max_input_len, max_mask_len, len(vocab)


text:
import unittest

from EXRReader import *
from TIFFReader import *
from ImagePrimitive import *
from JPEGReader import *
from CINReader import *

redpajama_set_name: RedPajamaGithub


text:
package com.hazelcast.internal.config.yaml;

import com.hazelcast.internal.yaml.YamlMapping;
import com.hazelcast.internal.yaml.YamlNode;

/**
 * An ordered view of a {@link YamlMapping}
 */
interface YamlOrderedMapping extends YamlMapping {

    /**
     * Gets a child node by its index
     *
     * @param index the index of the child node
     * @return the child node with the given index if exists,
     * {@code null} otherwise
     */
    YamlNode child(int index);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/background_light">

    <TextView
        android:id="@+id/chooseStyleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/choose_style_text"
        app:layout_constraintBottom_toTopOf="@+id/radioGroup"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chooseStyleTextView">

        <RadioButton
            android:id="@+id/webStyleRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:text="@string/web_style" />

        <RadioButton
            android:id="@+id/styleFileRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/style_file" />

    </RadioGroup>

</androidx.constraintlayout.widget.ConstraintLayout>


text:
<?php

namespace ER\CantineBundle\Admin;

use Blast\CoreBundle\Admin\CoreAdmin;

class CourseAdmin extends CoreAdmin
{

}


text:
import { module } from 'angular';

import 'bootstrap/dist/css/bootstrap.css';
import 'jquery-ui';
// Must come after jquery-ui - we want the bootstrap tooltip, JavaScript is fun
import 'bootstrap/dist/js/bootstrap.js';

import 'font-awesome/css/font-awesome.css';
import 'react-select/dist/react-select.css';
import 'react-virtualized/styles.css'
import 'react-virtualized-select/styles.css'
import 'ui-select/dist/select.css';
import './styleguide/src/styles/app.css';

import UI_ROUTER from '@uirouter/angularjs';
const UI_ROUTER_STATE_EVENTS_SHIM = 'ui.router.state.events';
require('@uirouter/angularjs/release/stateEvents');
import { UI_ROUTER_REACT_HYBRID } from '@uirouter/react-hybrid';

// use require instead of import to ensure insertion order is preserved
require('Select2/select2.css');
require('select2-bootstrap-css/select2-bootstrap.css');
import 'source-sans-pro';
require('root/app/fonts/spinnaker/icons.css');

import { ANALYTICS_MODULE } from './analytics/analytics.module';
import { APPLICATION_BOOTSTRAP_MODULE } from './bootstrap';
import { APPLICATION_MODULE } from './application/application.module';
import { AUTHENTICATION_MODULE } from './authentication/authentication.module';
import { CANCEL_MODAL_MODULE } from './cancelModal/cancelModal.module';
import { CLOUD_PROVIDER_MODULE } from './cloudProvider/cloudProvider.module';
import { CLUSTER_MODULE } from './cluster/cluster.module';
import { CONFIG_MODULE } from './config/config.module';

import { DEBUG_WINDOW } from './utils/consoleDebug';
import { DEPLOYMENT_STRATEGY_MODULE } from './deploymentStrategy/deploymentStrategy.module';
import { DIFF_MODULE } from './diffs';
import { ENTITY_TAGS_MODULE } from './entityTag/entityTags.module';
import { HEALTH_COUNTS_MODULE } from './healthCounts/healthCounts.module';
import { HELP_MODULE } from './help/help.module';
import { INSIGHT_NGMODULE } from './insight/insight.module';
import { INTERCEPTOR_MODULE } from './interceptor/interceptor.module';
import { LOAD_BALANCER_MODULE } from './loadBalancer/loadBalancer.module';
import { PAGE_TITLE_MODULE } from './pageTitle/pageTitle.module';
import { PIPELINE_TEMPLATE_MODULE } from './pipeline/config/templates/pipelineTemplate.module';
import { REACT_MODULE } from './reactShims';
import { REGION_MODULE } from './region/region.module';
import { SUBNET_MODULE } from './subnet/subnet.module';
import { WHATS_NEW_MODULE } from './whatsNew/whatsNew.module';
import { WIDGETS_MODULE } from './widgets/widgets.module';
import { STYLEGUIDE_MODULE } from './styleguide/styleguide.module';

// load all templates into the $templateCache
const templates = require.context('./', true, /\.html$/);
templates.keys().forEach(function(key) {
  templates(key);
});

export const CORE_MODULE = 'spinnaker.core';
module(CORE_MODULE, [
  require('angular-messages'),
  require('angular-sanitize'),
  UI_ROUTER,
  UI_ROUTER_STATE_EVENTS_SHIM,
  UI_ROUTER_REACT_HYBRID,
  REACT_MODULE, // must precede modules which register states
  require('angular-ui-bootstrap'),
  require('ui-select'),
  require('angular-spinner').angularSpinner.name,

  ANALYTICS_MODULE,
  APPLICATION_MODULE,
  APPLICATION_BOOTSTRAP_MODULE,
  AUTHENTICATION_MODULE,

  require('./cache/caches.module'),
  CANCEL_MODAL_MODULE,
  CLOUD_PROVIDER_MODULE,
  CONFIG_MODULE,
  CLUSTER_MODULE,

  DEBUG_WINDOW,
  DEPLOYMENT_STRATEGY_MODULE,
  require('./delivery/delivery.module'),
  DIFF_MODULE,

  ENTITY_TAGS_MODULE,

  require('./forms/forms.module'),

  HEALTH_COUNTS_MODULE,
  HELP_MODULE,

  INSIGHT_NGMODULE.name,
  require('./instance/instance.module'),
  INTERCEPTOR_MODULE,

  LOAD_BALANCER_MODULE,

  require('./modal/modal.module'),

  require('./notification/notifications.module'),

  PAGE_TITLE_MODULE,
  PIPELINE_TEMPLATE_MODULE,
  require('./pipeline/pipelines.module'),
  require('./presentation/presentation.module'),
  require('./projects/projects.module'),

  REGION_MODULE,

  require('./search/search.module'),
  require('./securityGroup/securityGroup.module'),
  require('./serverGroup/serverGroup.module'),
  SUBNET_MODULE,

  require('./task/task.module'),

  require('./utils/utils.module'),

  WHATS_NEW_MODULE,
  WIDGETS_MODULE,

  require('./validation/validation.module'),
  STYLEGUIDE_MODULE
]);


text:
FROM node:alpine
COPY lib /docker-langserver/lib
COPY bin /docker-langserver/bin
COPY package.json /docker-langserver/package.json
WORKDIR /docker-langserver/
RUN npm install --ignore-scripts --production && \
    chmod +x /docker-langserver/bin/docker-langserver
ENTRYPOINT [ "/docker-langserver/bin/docker-langserver" ]


text:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class League extends Model {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'leagues';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['league_id', 'name', 'location_id', 'format_id', 'start_date', 'end_date', 'start_time', 'end_time', 'fee', 'detail' ,'img_logo'];

	public $primaryKey = 'league_id';
	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	// protected $hidden = ['password', 'remember_token'];

	public function players() {

		return $this->hasManyThrough('App\Player', 'App\LeaguePlayer', 'league_id', 'player_id');
	}

	public function getPlayers($league_id) {

		$p = \DB::table('leagues')
			->join('league_players', 'leagues.league_id', '=', 'league_players.league_id')
			->join('players', 'players.player_id', '=', 'league_players.player_id')
			->where('leagues.league_id', '=', $league_id)
			->select( '*')
			->distinct();

		return $p;
	}

	public function matches() {

		return $this->hasManyThrough('App\Match', 'App\LeagueMatch', 'league_id', 'tournament_id');
	}

	public function getMatches($league_id, $player_id) {

		$m = \DB::table('matches')
			->join('leagues', 'leagues.league_id', '=', 'matches.tournament_id')
			->join('players as winner', 'winner.player_id', '=', 'matches.player1_id')
			->join('players as loser', 'loser.player_id', '=', 'matches.player2_id')
			->where('matches.tournament_id', '=', $league_id)
			->where(
				function($q)use($player_id) {
					$q->where('player1_id', '=', $player_id)
						->orWhere('player2_id', '=', $player_id);
			})
			->orderBy('match_division')
			->orderBy('round')
			->select( '*',
				'winner.first_name as winner_first_name',
			 	'winner.last_name as winner_last_name' ,
				'loser.first_name as loser_first_name',
				'loser.last_name as loser_last_name',
				'loser.player_id as loser_id',
				'leagues.name as league'
				)
			->distinct()
			->get();

		return $m;
	}
}


text:
//
//  KGLPinNode.h
//
//  Created by Kevin Li on 3/2/15.
//  Copyright (c) 2015 Kevin Li. All rights reserved.
//

#import <SceneKit/SceneKit.h>
#import "KGLEarthCommonMath.h"

@interface KGLPinNode : SCNNode

/*!
 * @discussion Convenience method for creating a pin, with internal nodes set up, at a specified location, assuming an Earth at the center of the scene with a radius of 50 units.
 * @param latitude The pin's latitude, in degrees.
 * @param longitude The pin's longitude, in degrees.
 * @return An instance of the KGLPinNode class.
 */
+ (KGLPinNode *)pinAtLatitude:(float)latitude andLongitude:(float)longitude;

/// @brief The string identifier for the pin. This will be returned by the KGLEarthSceneView delegate if the user taps on the pin.
/// @warning If no identifier is provided, the pin will never respond to a tap event.
@property (nonatomic, copy) NSString *identifier;
/// @brief The latitude of the pin, in degrees.
@property float latitude;
/// @brief The longitude of the pin, in degrees.
@property float longitude;

@end


text:
package status

import (
	"fmt"
	"net"
	"os"
	"sort"
	"sync"
	"time"

	"github.com/golang/glog"

	v1 "k8s.io/api/core/v1"
	extensions "k8s.io/api/extensions/v1beta1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/util/wait"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/leaderelection"
	"k8s.io/client-go/tools/leaderelection/resourcelock"
	"k8s.io/client-go/tools/record"

	"k8s.io/ingress/core/pkg/ingress/annotations/class"
	"k8s.io/ingress/core/pkg/ingress/store"
	"k8s.io/ingress/core/pkg/k8s"
	"k8s.io/ingress/core/pkg/strings"
	"k8s.io/ingress/core/pkg/task"
)

const (
	updateInterval = 30 * time.Second
)

// Sync ...
type Sync interface {
	Run(stopCh <-chan struct{})
	Shutdown()
}

// Config ...
type Config struct {
	Client         clientset.Interface
	PublishService string
	IngressLister  store.IngressLister

	ElectionID string

	UpdateStatusOnShutdown bool

	DefaultIngressClass string
	IngressClass        string

	// CustomIngressStatus allows to set custom values in Ingress status
	CustomIngressStatus func(*extensions.Ingress) []v1.LoadBalancerIngress
}

// statusSync keeps the status IP in each Ingress rule updated executing a periodic check
// in all the defined rules. To simplify the process leader election is used so the update
// is executed only in one node (Ingress controllers can be scaled to more than one)
// If the controller is running with the flag --publish-service (with a valid service)
// the IP address behind the service is used, if not the source is the IP/s of the node/s
type statusSync struct {
	Config
	// pod contains runtime information about this pod
	pod *k8s.PodInfo

	elector *leaderelection.LeaderElector
	// workqueue used to keep in sync the status IP/s
	// in the Ingress rules
	syncQueue *task.Queue

	runLock *sync.Mutex
}

// Run starts the loop to keep the status in sync
func (s statusSync) Run(stopCh <-chan struct{}) {
	go wait.Forever(s.elector.Run, 0)
	go s.syncQueue.Run(time.Second, stopCh)
	<-stopCh
}

// Shutdown stop the sync. In case the instance is the leader it will remove the current IP
// if there is no other instances running.
func (s statusSync) Shutdown() {
	go s.syncQueue.Shutdown()
	// remove IP from Ingress
	if !s.elector.IsLeader() {
		return
	}

	if !s.UpdateStatusOnShutdown {
		glog.Warningf("skipping update of status of Ingress rules")
		return
	}

	glog.Infof("updating status of Ingress rules (remove)")

	addrs, err := s.runningAddresses()
	if err != nil {
		glog.Errorf("error obtaining running IPs: %v", addrs)
		return
	}

	if len(addrs) > 1 {
		// leave the job to the next leader
		glog.Infof("leaving status update for next leader (%v)", len(addrs))
		return
	}

	if s.isRunningMultiplePods() {
		glog.V(2).Infof("skipping Ingress status update (multiple pods running - another one will be elected as master)")
		return
	}

	glog.Infof("removing address from ingress status (%v)", addrs)
	s.updateStatus([]v1.LoadBalancerIngress{})
}

func (s *statusSync) sync(key interface{}) error {
	s.runLock.Lock()
	defer s.runLock.Unlock()

	if s.syncQueue.IsShuttingDown() {
		glog.V(2).Infof("skipping Ingress status update (shutting down in progress)")
		return nil
	}

	if !s.elector.IsLeader() {
		glog.V(2).Infof("skipping Ingress status update (I am not the current leader)")
		return nil
	}

	addrs, err := s.runningAddresses()
	if err != nil {
		return err
	}
	s.updateStatus(sliceToStatus(addrs))

	return nil
}

// callback invoked function when a new leader is elected
func (s *statusSync) callback(leader string) {
	if s.syncQueue.IsShuttingDown() {
		return
	}

	glog.V(2).Infof("new leader elected (%v)", leader)
	if leader == s.pod.Name {
		glog.V(2).Infof("I am the new status update leader")
	}
}

func (s statusSync) keyfunc(input interface{}) (interface{}, error) {
	return input, nil
}

// NewStatusSyncer returns a new Sync instance
func NewStatusSyncer(config Config) Sync {
	pod, err := k8s.GetPodDetails(config.Client)
	if err != nil {
		glog.Fatalf("unexpected error obtaining pod information: %v", err)
	}

	st := statusSync{
		pod:     pod,
		runLock: &sync.Mutex{},
		Config:  config,
	}
	st.syncQueue = task.NewCustomTaskQueue(st.sync, st.keyfunc)

	// we need to use the defined ingress class to allow multiple leaders
	// in order to update information about ingress status
	electionID := fmt.Sprintf("%v-%v", config.ElectionID, config.DefaultIngressClass)
	if config.IngressClass != "" {
		electionID = fmt.Sprintf("%v-%v", config.ElectionID, config.IngressClass)
	}

	callbacks := leaderelection.LeaderCallbacks{
		OnStartedLeading: func(stop <-chan struct{}) {
			st.callback(pod.Name)
		},
		OnStoppedLeading: func() {
			st.callback("")
		},
	}

	broadcaster := record.NewBroadcaster()
	hostname, _ := os.Hostname()

	recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{
		Component: "ingress-leader-elector",
		Host:      hostname,
	})

	lock := resourcelock.ConfigMapLock{
		ConfigMapMeta: meta_v1.ObjectMeta{Namespace: pod.Namespace, Name: electionID},
		Client:        config.Client.Core(),
		LockConfig: resourcelock.ResourceLockConfig{
			Identity:      electionID,
			EventRecorder: recorder,
		},
	}

	le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{
		Lock:          &lock,
		LeaseDuration: 30 * time.Second,
		RenewDeadline: 15 * time.Second,
		RetryPeriod:   5 * time.Second,
		Callbacks:     callbacks,
	})

	if err != nil {
		glog.Fatalf("unexpected error starting leader election: %v", err)
	}

	st.elector = le
	return st
}

// runningAddresses returns a list of IP addresses and/or FQDN where the
// ingress controller is currently running
func (s *statusSync) runningAddresses() ([]string, error) {
	if s.PublishService != "" {
		ns, name, _ := k8s.ParseNameNS(s.PublishService)
		svc, err := s.Client.Core().Services(ns).Get(name, meta_v1.GetOptions{})
		if err != nil {
			return nil, err
		}

		addrs := []string{}
		for _, ip := range svc.Status.LoadBalancer.Ingress {
			if ip.IP == "" {
				addrs = append(addrs, ip.Hostname)
			} else {
				addrs = append(addrs, ip.IP)
			}
		}

		return addrs, nil
	}

	// get information about all the pods running the ingress controller
	pods, err := s.Client.Core().Pods(s.pod.Namespace).List(meta_v1.ListOptions{
		LabelSelector: labels.SelectorFromSet(s.pod.Labels).String(),
	})
	if err != nil {
		return nil, err
	}

	addrs := []string{}
	for _, pod := range pods.Items {
		name := k8s.GetNodeIP(s.Client, pod.Spec.NodeName)
		if !strings.StringInSlice(name, addrs) {
			addrs = append(addrs, name)
		}
	}
	return addrs, nil
}

func (s *statusSync) isRunningMultiplePods() bool {
	pods, err := s.Client.Core().Pods(s.pod.Namespace).List(meta_v1.ListOptions{
		LabelSelector: labels.SelectorFromSet(s.pod.Labels).String(),
	})
	if err != nil {
		return false
	}

	return len(pods.Items) > 1
}

// sliceToStatus converts a slice of IP and/or hostnames to LoadBalancerIngress
func sliceToStatus(endpoints []string) []v1.LoadBalancerIngress {
	lbi := []v1.LoadBalancerIngress{}
	for _, ep := range endpoints {
		if net.ParseIP(ep) == nil {
			lbi = append(lbi, v1.LoadBalancerIngress{Hostname: ep})
		} else {
			lbi = append(lbi, v1.LoadBalancerIngress{IP: ep})
		}
	}

	sort.Sort(loadBalancerIngressByIP(lbi))
	return lbi
}

// updateStatus changes the status information of Ingress rules
// If the backend function CustomIngressStatus returns a value different
// of nil then it uses the returned value or the newIngressPoint values
func (s *statusSync) updateStatus(newIngressPoint []v1.LoadBalancerIngress) {
	ings := s.IngressLister.List()
	var wg sync.WaitGroup
	wg.Add(len(ings))
	for _, cur := range ings {
		ing := cur.(*extensions.Ingress)

		if !class.IsValid(ing, s.Config.IngressClass, s.Config.DefaultIngressClass) {
			wg.Done()
			continue
		}

		go func(wg *sync.WaitGroup, ing *extensions.Ingress) {
			defer wg.Done()
			ingClient := s.Client.Extensions().Ingresses(ing.Namespace)
			currIng, err := ingClient.Get(ing.Name, meta_v1.GetOptions{})
			if err != nil {
				glog.Errorf("unexpected error searching Ingress %v/%v: %v", ing.Namespace, ing.Name, err)
				return
			}

			addrs := newIngressPoint
			ca := s.CustomIngressStatus(currIng)
			if ca != nil {
				addrs = ca
			}

			curIPs := currIng.Status.LoadBalancer.Ingress
			sort.Sort(loadBalancerIngressByIP(curIPs))
			if ingressSliceEqual(addrs, curIPs) {
				glog.V(3).Infof("skipping update of Ingress %v/%v (no change)", currIng.Namespace, currIng.Name)
				return
			}

			glog.Infof("updating Ingress %v/%v status to %v", currIng.Namespace, currIng.Name, addrs)
			currIng.Status.LoadBalancer.Ingress = addrs
			_, err = ingClient.UpdateStatus(currIng)
			if err != nil {
				glog.Warningf("error updating ingress rule: %v", err)
			}
		}(&wg, ing)
	}

	wg.Wait()
}

func ingressSliceEqual(lhs, rhs []v1.LoadBalancerIngress) bool {
	if len(lhs) != len(rhs) {
		return false
	}

	for i := range lhs {
		if lhs[i].IP != rhs[i].IP {
			return false
		}
		if lhs[i].Hostname != rhs[i].Hostname {
			return false
		}
	}
	return true
}

// loadBalancerIngressByIP sorts LoadBalancerIngress using the field IP
type loadBalancerIngressByIP []v1.LoadBalancerIngress

func (c loadBalancerIngressByIP) Len() int      { return len(c) }
func (c loadBalancerIngressByIP) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c loadBalancerIngressByIP) Less(i, j int) bool {
	return c[i].IP < c[j].IP
}


text:
class CreateSplashLogs < ActiveRecord::Migration[4.2]
  def change
    create_table :splash_logs do |t|
      t.string :destination
      t.timestamps
    end
  end
end


text:
[![Build Status](https://travis-ci.org/tamccall/moconvey.svg?branch=master)](https://travis-ci.org/tamccall/moconvey)
[![Go Report Card](https://goreportcard.com/badge/github.com/tamccall/moconvey)](https://goreportcard.com/report/github.com/tamccall/moconvey)
[![GoDoc](https://godoc.org/github.com/tamccall/moconvey?status.svg)](https://godoc.org/github.com/tamccall/moconvey/assertions)

moconvey is a package that aims to better integrate the [mocks](https://godoc.org/github.com/stretchr/testify/mock)
of [stretchr/testify](https://github.com/stretchr/testify) and the testing framework that is [goconvey](https://github.com/smartystreets/goconvey)

This package currently defines all of the assertions provided by the [mock struct](https://godoc.org/github.com/stretchr/testify/mock#Mock)
as [convey style assertions](https://github.com/smartystreets/goconvey/wiki/Custom-Assertions) so you will still be able
to get those fancy green check marks for your mock assertions too.

This package was originally designed to work with mocks generated by [mockery](https://github.com/vektra/mockery) but should
work with any mock using testify's mock package

## Example
Here is an example test function testing a piece of code that operates on a mock called `Foo`.
The test function can setup expectations (testify) for `Foo` and assert that they indeed happened:

```go
package convey

import (
	"testing"

	. "github.com/tamccall/moconvey/assertions"
	. "github.com/smartystreets/goconvey/convey"

	"github.com/tamccall/moconvey/mocks"
)

func TestExampleMock(t *testing.T)	{
	Convey( "Given the example mock" , t, func() {
		mock := new(mocks.Foo)
		mock.On("Bar").Return("Hello World")
		Convey("When Bar is called", func() {
			mock.Bar()
			Convey("Assert Bar is called", func() {
				So(mock, ShouldHaveReceived, "Bar")
			})
		})
	})
}
```


text:
package producer

import (
	"fmt"
	"sync"
	"time"

	pb "github.com/hyperledger/fabric/protos/peer"
)

//---- event hub framework ----

//handlerListi uses map to implement a set of handlers. use mutex to access
//the map. Note that we don't have lock/unlock wrapper methods as the lock
//of handler list has to be done under the eventProcessor lock. See
//registerHandler, deRegisterHandler. register/deRegister methods
//will be called only when a new consumer chat starts/ends respectively
//and the big lock should have no performance impact
//
type handlerList interface {
	add(ie *pb.Interest, h *handler) (bool, error)
	del(ie *pb.Interest, h *handler) (bool, error)
	foreach(ie *pb.Event, action func(h *handler))
}

type genericHandlerList struct {
	sync.RWMutex
	handlers map[*handler]bool
}

type chaincodeHandlerList struct {
	sync.RWMutex
	handlers map[string]map[string]map[*handler]bool
}

func (hl *chaincodeHandlerList) add(ie *pb.Interest, h *handler) (bool, error) {
	hl.Lock()
	defer hl.Unlock()

	//chaincode registration info must be non-nil
	if ie.GetChaincodeRegInfo() == nil {
		return false, fmt.Errorf("chaincode information not provided for registering")
	}
	//chaincode registration info must be for a non-empty chaincode ID (even if the chaincode does not exist)
	if ie.GetChaincodeRegInfo().ChaincodeID == "" {
		return false, fmt.Errorf("chaincode ID not provided for registering")
	}
	//is there a event type map for the chaincode
	emap, ok := hl.handlers[ie.GetChaincodeRegInfo().ChaincodeID]
	if !ok {
		emap = make(map[string]map[*handler]bool)
		hl.handlers[ie.GetChaincodeRegInfo().ChaincodeID] = emap
	}

	//create handler map if this is the first handler for the type
	var handlerMap map[*handler]bool
	if handlerMap, _ = emap[ie.GetChaincodeRegInfo().EventName]; handlerMap == nil {
		handlerMap = make(map[*handler]bool)
		emap[ie.GetChaincodeRegInfo().EventName] = handlerMap
	} else if _, ok = handlerMap[h]; ok {
		return false, fmt.Errorf("handler exists for event type")
	}

	//the handler is added to the map
	handlerMap[h] = true

	return true, nil
}
func (hl *chaincodeHandlerList) del(ie *pb.Interest, h *handler) (bool, error) {
	hl.Lock()
	defer hl.Unlock()

	//chaincode registration info must be non-nil
	if ie.GetChaincodeRegInfo() == nil {
		return false, fmt.Errorf("chaincode information not provided for de-registering")
	}

	//chaincode registration info must be for a non-empty chaincode ID (even if the chaincode does not exist)
	if ie.GetChaincodeRegInfo().ChaincodeID == "" {
		return false, fmt.Errorf("chaincode ID not provided for de-registering")
	}

	//if there's no event type map, nothing to do
	emap, ok := hl.handlers[ie.GetChaincodeRegInfo().ChaincodeID]
	if !ok {
		return false, fmt.Errorf("chaincode ID not registered")
	}

	//if there are no handlers for the event type, nothing to do
	var handlerMap map[*handler]bool
	if handlerMap, _ = emap[ie.GetChaincodeRegInfo().EventName]; handlerMap == nil {
		return false, fmt.Errorf("event name %s not registered for chaincode ID %s", ie.GetChaincodeRegInfo().EventName, ie.GetChaincodeRegInfo().ChaincodeID)
	} else if _, ok = handlerMap[h]; !ok {
		//the handler is not registered for the event type
		return false, fmt.Errorf("handler not registered for event name %s for chaincode ID %s", ie.GetChaincodeRegInfo().EventName, ie.GetChaincodeRegInfo().ChaincodeID)
	}
	//remove the handler from the map
	delete(handlerMap, h)

	//if the last handler has been removed from handler map for a chaincode's event,
	//remove the event map.
	//if the last map of events have been removed for the chaincode UUID
	//remove the chaincode UUID map
	if len(handlerMap) == 0 {
		delete(emap, ie.GetChaincodeRegInfo().EventName)
		if len(emap) == 0 {
			delete(hl.handlers, ie.GetChaincodeRegInfo().ChaincodeID)
		}
	}

	return true, nil
}

func (hl *chaincodeHandlerList) foreach(e *pb.Event, action func(h *handler)) {
	hl.Lock()
	defer hl.Unlock()

	//if there's no chaincode event in the event... nothing to do (why was this event sent ?)
	if e.GetChaincodeEvent() == nil || e.GetChaincodeEvent().ChaincodeID == "" {
		return
	}

	//get the event map for the chaincode
	if emap := hl.handlers[e.GetChaincodeEvent().ChaincodeID]; emap != nil {
		//get the handler map for the event
		if handlerMap := emap[e.GetChaincodeEvent().EventName]; handlerMap != nil {
			for h := range handlerMap {
				action(h)
			}
		}
		//send to handlers who want all events from the chaincode, but only if
		//EventName is not already "" (chaincode should NOT send nameless events though)
		if e.GetChaincodeEvent().EventName != "" {
			if handlerMap := emap[""]; handlerMap != nil {
				for h := range handlerMap {
					action(h)
				}
			}
		}
	}
}

func (hl *genericHandlerList) add(ie *pb.Interest, h *handler) (bool, error) {
	hl.Lock()
	if _, ok := hl.handlers[h]; ok {
		hl.Unlock()
		return false, fmt.Errorf("handler exists for event type")
	}
	hl.handlers[h] = true
	hl.Unlock()
	return true, nil
}

func (hl *genericHandlerList) del(ie *pb.Interest, h *handler) (bool, error) {
	hl.Lock()
	if _, ok := hl.handlers[h]; !ok {
		hl.Unlock()
		return false, fmt.Errorf("handler does not exist for event type")
	}
	delete(hl.handlers, h)
	hl.Unlock()
	return true, nil
}

func (hl *genericHandlerList) foreach(e *pb.Event, action func(h *handler)) {
	hl.Lock()
	for h := range hl.handlers {
		action(h)
	}
	hl.Unlock()
}

//eventProcessor has a map of event type to handlers interested in that
//event type. start() kicks of the event processor where it waits for Events
//from producers. We could easily generalize the one event handling loop to one
//per handlerMap if necessary.
//
type eventProcessor struct {
	sync.RWMutex
	eventConsumers map[pb.EventType]handlerList

	//we could generalize this with mutiple channels each with its own size
	eventChannel chan *pb.Event

	//milliseconds timeout for producer to send an event.
	//if < 0, if buffer full, unblocks immediately and not send
	//if 0, if buffer full, will block and guarantee the event will be sent out
	//if > 0, if buffer full, blocks till timeout
	timeout int
}

//global eventProcessor singleton created by initializeEvents. Openchain producers
//send events simply over a reentrant static method
var gEventProcessor *eventProcessor

func (ep *eventProcessor) start() {
	producerLogger.Info("event processor started")
	for {
		//wait for event
		e := <-ep.eventChannel

		var hl handlerList
		eType := getMessageType(e)
		ep.Lock()
		if hl, _ = ep.eventConsumers[eType]; hl == nil {
			producerLogger.Errorf("Event of type %s does not exist", eType)
			ep.Unlock()
			continue
		}
		//lock the handler map lock
		ep.Unlock()

		hl.foreach(e, func(h *handler) {
			if e.Event != nil {
				h.SendMessage(e)
			}
		})

	}
}

//initialize and start
func initializeEvents(bufferSize uint, tout int) {
	if gEventProcessor != nil {
		panic("should not be called twice")
	}

	gEventProcessor = &eventProcessor{eventConsumers: make(map[pb.EventType]handlerList), eventChannel: make(chan *pb.Event, bufferSize), timeout: tout}

	addInternalEventTypes()

	//start the event processor
	go gEventProcessor.start()
}

//AddEventType supported event
func AddEventType(eventType pb.EventType) error {
	gEventProcessor.Lock()
	producerLogger.Debugf("registering %s", pb.EventType_name[int32(eventType)])
	if _, ok := gEventProcessor.eventConsumers[eventType]; ok {
		gEventProcessor.Unlock()
		return fmt.Errorf("event type exists %s", pb.EventType_name[int32(eventType)])
	}

	switch eventType {
	case pb.EventType_BLOCK:
		gEventProcessor.eventConsumers[eventType] = &genericHandlerList{handlers: make(map[*handler]bool)}
	case pb.EventType_CHAINCODE:
		gEventProcessor.eventConsumers[eventType] = &chaincodeHandlerList{handlers: make(map[string]map[string]map[*handler]bool)}
	case pb.EventType_REJECTION:
		gEventProcessor.eventConsumers[eventType] = &genericHandlerList{handlers: make(map[*handler]bool)}
	}
	gEventProcessor.Unlock()

	return nil
}

func registerHandler(ie *pb.Interest, h *handler) error {
	producerLogger.Debugf("registerHandler %s", ie.EventType)

	gEventProcessor.Lock()
	defer gEventProcessor.Unlock()
	if hl, ok := gEventProcessor.eventConsumers[ie.EventType]; !ok {
		return fmt.Errorf("event type %s does not exist", ie.EventType)
	} else if _, err := hl.add(ie, h); err != nil {
		return fmt.Errorf("error registering handler for  %s: %s", ie.EventType, err)
	}

	return nil
}

func deRegisterHandler(ie *pb.Interest, h *handler) error {
	producerLogger.Debugf("deRegisterHandler %s", ie.EventType)

	gEventProcessor.Lock()
	defer gEventProcessor.Unlock()
	if hl, ok := gEventProcessor.eventConsumers[ie.EventType]; !ok {
		return fmt.Errorf("event type %s does not exist", ie.EventType)
	} else if _, err := hl.del(ie, h); err != nil {
		return fmt.Errorf("error deregistering handler for %s: %s", ie.EventType, err)
	}

	return nil
}

//------------- producer API's -------------------------------

//Send sends the event to interested consumers
func Send(e *pb.Event) error {
	if e.Event == nil {
		producerLogger.Error("event not set")
		return fmt.Errorf("event not set")
	}

	if gEventProcessor == nil {
		return nil
	}

	if gEventProcessor.timeout < 0 {
		select {
		case gEventProcessor.eventChannel <- e:
		default:
			return fmt.Errorf("could not send the blocking event")
		}
	} else if gEventProcessor.timeout == 0 {
		gEventProcessor.eventChannel <- e
	} else {
		select {
		case gEventProcessor.eventChannel <- e:
		case <-time.After(time.Duration(gEventProcessor.timeout) * time.Millisecond):
			return fmt.Errorf("could not send the blocking event")
		}
	}

	return nil
}


text:
/*
 * input is queryBuild (knex object) and args object
 * with field joinClauses: [{joinClause}, ...]
 * where joinClause is:
 *  - type (optional, default:"join"): "join", "inner", "left", "leftOuter", "right", "rightOuter", "outer", "fullOuter"
 *  - table (required)
 *  - args (required, variable) see knex docs
 */
export default function joinBuilder(queryBuilder, args) {
  let { joins } = args;

  // add group by
  if (joins) {
    for (let clause of joins) {
      if (clause) {
        if (clause.applyWhen && !clause.applyWhen(args)) {
          continue;
        }
        let table = clause.table;
        let joinArgs = clause.args;
        let join = clause.type;
        if (!join) {
          join = 'join';
        }

        if (join === 'join') {
          queryBuilder.join(table, ...joinArgs);
        }
        if (join === 'inner') {
          queryBuilder.innerJoin(table, ...joinArgs);
        }
        if (join === 'left') {
          queryBuilder.leftJoin(table, ...joinArgs);
        }
        if (join === 'leftOuter') {
          queryBuilder.leftOuterJoin(table, ...joinArgs);
        }
        if (join === 'right') {
          queryBuilder.rightJoin(table, ...joinArgs);
        }
        if (join === 'rightOuter') {
          queryBuilder.rightOuterJoin(table, ...joinArgs);
        }
        if (join === 'outer') {
          queryBuilder.outerJoin(table, ...joinArgs);
        }
        if (join === 'fullOuter') {
          queryBuilder.fullOuterJoin(table, ...joinArgs);
        }
      }
    }
  }

  return queryBuilder;
}


text:
(function(IIS) {
	"use strict";

	IIS.Slider.prototype.addCaptions = function() {
		IIS._addClass(this._attributes.container, 'iis-has-captions');

		Array.prototype.forEach.call(this._attributes.slides, function(slide, i){
			var caption = document.createElement('div');
			IIS._addClass(caption, 'iis-caption');

			var captionContent = '';
			if(slide.getAttribute('title')){
				captionContent += '
'+ slide.getAttribute('title') +'
';
			}
			if(slide.getAttribute('data-caption')){
				var dataCaption = slide.getAttribute('data-caption');
				if(dataCaption.substring(0,1) == '#' || dataCaption.substring(0,1) == '.'){
					var external = document.querySelector(dataCaption);
					if(external){
						captionContent += '
'+ external.innerHTML +'
';
					}
				} else {
					captionContent += '
'+ slide.getAttribute('data-caption') +'
';
				}
			} else {
				if(slide.innerHTML){
					captionContent += '
'+ slide.innerHTML +'
';
				}
			}

			slide.innerHTML = '';
			if(captionContent){
				caption.innerHTML = captionContent;
				slide.appendChild(caption);
			}
		}.bind(this));
	};

	return IIS;

})(IdealImageSlider);


text:
package com.sequenceiq.cloudbreak.cloud.azure;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.validation.constraints.NotNull;

import org.assertj.core.api.Assertions;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ReflectionUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.microsoft.azure.CloudError;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.PolicyViolation;
import com.microsoft.azure.management.compute.VirtualMachine;
import com.sequenceiq.cloudbreak.cloud.azure.client.AzureClient;
import com.sequenceiq.cloudbreak.cloud.azure.validator.AzurePremiumValidatorService;
import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.context.CloudContext;
import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException;
import com.sequenceiq.cloudbreak.cloud.exception.CloudExceptionConverter;
import com.sequenceiq.cloudbreak.cloud.model.CloudInstance;
import com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus;
import com.sequenceiq.cloudbreak.cloud.model.InstanceStatus;
import com.sequenceiq.cloudbreak.cloud.model.generic.DynamicModel;
import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException;
import com.sequenceiq.cloudbreak.service.Retry;

import rx.Completable;
import rx.plugins.RxJavaHooks;
import rx.schedulers.Schedulers;

@ExtendWith(MockitoExtension.class)
public class AzureUtilsTest {

    private static final Long WORKSPACE_ID = 1L;

    private static final int MAX_RESOURCE_NAME_LENGTH = 50;

    private static final int MAX_DISK_ENCRYPTION_SET_NAME_LENGTH = 80;

    @Mock
    private AzurePremiumValidatorService azurePremiumValidatorService;

    @Mock
    private AzureVirtualMachineService azureVirtualMachineService;

    @Mock
    private AzureResourceGroupMetadataProvider azureResourceGroupMetadataProvider;

    @Mock
    private CloudExceptionConverter cloudExceptionConverter;

    @InjectMocks
    private AzureUtils underTest;

    @BeforeEach
    public void setUp() {
        ReflectionTestUtils.setField(underTest, "maxResourceNameLength", MAX_RESOURCE_NAME_LENGTH);
        RxJavaHooks.setOnIOScheduler(current -> Schedulers.immediate());
    }

    @AfterEach
    public void tearDown() {
        RxJavaHooks.reset();
    }

    @Test
    public void shouldAdjustResourceNameLengthIfItsTooLong() {
        //GIVEN
        CloudContext context = CloudContext.Builder.builder()
                .withId(7899L)
                .withName("thisisaverylongazureresourcenamewhichneedstobeshortened")
                .withCrn("crn")
                .withPlatform("dummy1")
                .withWorkspaceId(WORKSPACE_ID)
                .build();

        //WHEN
        String testResult = underTest.getStackName(context);

        //THEN
        assertNotNull(testResult, "The generated name must not be null!");
        assertEquals("thisisaverylongazureresourcenamewhichneedstobe7899", testResult, "The resource name is not the excepted one!");
        assertEquals(MAX_RESOURCE_NAME_LENGTH, testResult.length(), "The resource name length is wrong");

    }

    @Test
    public void validateStorageTypeForGroupWhenPremiumStorageConfiguredAndFlavorNotPremiumThenShouldThrowCloudConnectorException() {
        String flavor = "Standard_A10";
        AzureDiskType azureDiskType = AzureDiskType.PREMIUM_LOCALLY_REDUNDANT;

        when(azurePremiumValidatorService.premiumDiskTypeConfigured(azureDiskType)).thenReturn(true);
        when(azurePremiumValidatorService.validPremiumConfiguration(flavor)).thenReturn(false);

        assertThrows(
                CloudConnectorException.class,
                () -> underTest.validateStorageTypeForGroup(azureDiskType, flavor));

        verify(azurePremiumValidatorService, times(1)).premiumDiskTypeConfigured(azureDiskType);
        verify(azurePremiumValidatorService, times(1)).validPremiumConfiguration(flavor);
    }

    @Test
    public void validateStorageTypeForGroupWhenPremiumStorageNotConfiguredThenShouldNotCallInstanceValidation() {
        String flavor = "Standard_A10";
        AzureDiskType azureDiskType = AzureDiskType.GEO_REDUNDANT;

        when(azurePremiumValidatorService.premiumDiskTypeConfigured(azureDiskType)).thenReturn(false);

        underTest.validateStorageTypeForGroup(azureDiskType, flavor);

        verify(azurePremiumValidatorService, times(1)).premiumDiskTypeConfigured(azureDiskType);
        verify(azurePremiumValidatorService, times(0)).validPremiumConfiguration(flavor);
    }

    @Test
    public void validateStorageTypeForGroupWhenPremiumStorageConfiguredAndFlavorIsPremiumThenShouldEverythinGoesFine() {
        String flavor = "Standard_DS10";
        AzureDiskType azureDiskType = AzureDiskType.PREMIUM_LOCALLY_REDUNDANT;

        when(azurePremiumValidatorService.premiumDiskTypeConfigured(azureDiskType)).thenReturn(true);
        when(azurePremiumValidatorService.validPremiumConfiguration(flavor)).thenReturn(true);

        underTest.validateStorageTypeForGroup(azureDiskType, flavor);

        verify(azurePremiumValidatorService, times(1)).validPremiumConfiguration(flavor);
        verify(azurePremiumValidatorService, times(1)).premiumDiskTypeConfigured(azureDiskType);
    }

    @Test
    public void deallocateInstancesShouldSucceed() {
        when(azureResourceGroupMetadataProvider.getResourceGroupName(any(), any(DynamicModel.class))).thenReturn("resourceGroup");
        when(azureVirtualMachineService.getVmsAndVmStatusesFromAzureWithoutRetry(any(), anyList()))
                .thenReturn(new AzureVirtualMachinesWithStatuses(new HashMap<>(),
                        List.of(
                                new CloudVmInstanceStatus(createCloudInstance("instance1"), InstanceStatus.STARTED),
                                new CloudVmInstanceStatus(createCloudInstance("instance2"), InstanceStatus.STARTED))));
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deallocateVirtualMachineAsync(anyString(), anyString())).thenReturn(Completable.complete());

        List<CloudVmInstanceStatus> statusesAfterDeallocate = underTest.deallocateInstances(ac,
                List.of(createCloudInstance("instance1"), createCloudInstance("instance2")));

        verify(azureClient, times(2)).deallocateVirtualMachineAsync(anyString(), anyString());
        assertEquals(2, statusesAfterDeallocate.size());
        statusesAfterDeallocate.forEach(status -> assertEquals(InstanceStatus.STOPPED, status.getStatus()));
    }

    @Test
    public void deallocateStoppedInstanceShouldBeSkippedFromDeallocation() {
        when(azureResourceGroupMetadataProvider.getResourceGroupName(any(), any(DynamicModel.class))).thenReturn("resourceGroup");
        when(azureVirtualMachineService.getVmsAndVmStatusesFromAzureWithoutRetry(any(), anyList()))
                .thenReturn(new AzureVirtualMachinesWithStatuses(new HashMap<>(),
                        List.of(
                                new CloudVmInstanceStatus(createCloudInstance("instance1"), InstanceStatus.STARTED),
                                new CloudVmInstanceStatus(createCloudInstance("instance2"), InstanceStatus.STOPPED))));
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deallocateVirtualMachineAsync(anyString(), anyString())).thenReturn(Completable.complete());

        List<CloudVmInstanceStatus> statusesAfterDeallocate = underTest.deallocateInstances(ac,
                List.of(createCloudInstance("instance1"), createCloudInstance("instance2")));

        verify(azureClient, times(1)).deallocateVirtualMachineAsync(anyString(), anyString());
        assertEquals(2, statusesAfterDeallocate.size());
        statusesAfterDeallocate.forEach(status -> assertEquals(InstanceStatus.STOPPED, status.getStatus()));
    }

    @Test
    public void deallocateInstancesShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        when(azureResourceGroupMetadataProvider.getResourceGroupName(any(), any(DynamicModel.class))).thenReturn("resourceGroup");
        when(azureVirtualMachineService.getVmsAndVmStatusesFromAzureWithoutRetry(any(), anyList()))
                .thenReturn(new AzureVirtualMachinesWithStatuses(new HashMap<>(),
                        List.of(
                                new CloudVmInstanceStatus(createCloudInstance("instance1"), InstanceStatus.STARTED),
                                new CloudVmInstanceStatus(createCloudInstance("instance2"), InstanceStatus.IN_PROGRESS),
                                new CloudVmInstanceStatus(createCloudInstance("instance3"), InstanceStatus.DELETE_REQUESTED))));
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deallocateVirtualMachineAsync(anyString(), eq("instance1"))).thenReturn(Completable.complete());
        when(azureClient.deallocateVirtualMachineAsync(anyString(), eq("instance2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deallocateVirtualMachineAsync(anyString(), eq("instance3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deallocateInstances(ac,
                        List.of(createCloudInstance("instance1"), createCloudInstance("instance2"),
                                createCloudInstance("instance3"))));

        verify(azureClient, times(3)).deallocateVirtualMachineAsync(anyString(), anyString());
    }

    @Test
    public void deleteInstancesShouldSucceed() {
        when(azureResourceGroupMetadataProvider.getResourceGroupName(any(), any(DynamicModel.class))).thenReturn("resourceGroup");
        when(azureVirtualMachineService.getVmsAndVmStatusesFromAzure(any(), anyList()))
                .thenReturn(new AzureVirtualMachinesWithStatuses(createVirtualMachineMap("instance1", "instance2"),
                        List.of(
                                new CloudVmInstanceStatus(createCloudInstance("instance1"), InstanceStatus.STARTED),
                                new CloudVmInstanceStatus(createCloudInstance("instance2"), InstanceStatus.STARTED))));
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deleteVirtualMachine(anyString(), anyString())).thenReturn(Completable.complete());

        List<CloudVmInstanceStatus> statusesAfterDelete = underTest.deleteInstances(ac,
                List.of(createCloudInstance("instance1"), createCloudInstance("instance2")));

        verify(azureClient, times(2)).deleteVirtualMachine(anyString(), anyString());
        assertEquals(2, statusesAfterDelete.size());
        statusesAfterDelete.forEach(status -> assertEquals(InstanceStatus.TERMINATED, status.getStatus()));
    }

    @Test
    public void deleteTerminatedInstancesShouldBeSkippedFromDeletion() {
        when(azureResourceGroupMetadataProvider.getResourceGroupName(any(), any(DynamicModel.class))).thenReturn("resourceGroup");
        when(azureVirtualMachineService.getVmsAndVmStatusesFromAzure(any(), anyList()))
                .thenReturn(new AzureVirtualMachinesWithStatuses(createVirtualMachineMap("instance1", "instance2", "instance3"),
                        List.of(
                                new CloudVmInstanceStatus(createCloudInstance("instance1"), InstanceStatus.STARTED),
                                new CloudVmInstanceStatus(createCloudInstance("instance2"), InstanceStatus.TERMINATED),
                                new CloudVmInstanceStatus(createCloudInstance("instance3"), InstanceStatus.TERMINATED_BY_PROVIDER))));
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deleteVirtualMachine(anyString(), anyString())).thenReturn(Completable.complete());

        List<CloudVmInstanceStatus> statusesAfterDelete = underTest.deleteInstances(ac,
                List.of(createCloudInstance("instance1"), createCloudInstance("instance2"), createCloudInstance("instance4")));

        verify(azureClient, times(1)).deleteVirtualMachine(anyString(), anyString());
        assertEquals(3, statusesAfterDelete.size());

        statusesAfterDelete.forEach(status -> Assertions.assertThat(status.getStatus()).isIn(InstanceStatus.TERMINATED, InstanceStatus.TERMINATED_BY_PROVIDER));
    }

    @Test
    public void deleteInstancesShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        when(azureResourceGroupMetadataProvider.getResourceGroupName(any(), any(DynamicModel.class))).thenReturn("resourceGroup");
        when(azureVirtualMachineService.getVmsAndVmStatusesFromAzure(any(), anyList()))
                .thenReturn(new AzureVirtualMachinesWithStatuses(createVirtualMachineMap("instance1", "instance2", "instance3"),
                        List.of(
                                new CloudVmInstanceStatus(createCloudInstance("instance1"), InstanceStatus.STARTED),
                                new CloudVmInstanceStatus(createCloudInstance("instance2"), InstanceStatus.IN_PROGRESS),
                                new CloudVmInstanceStatus(createCloudInstance("instance3"), InstanceStatus.DELETE_REQUESTED))));
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deleteVirtualMachine(anyString(), eq("instance1"))).thenReturn(Completable.complete());
        when(azureClient.deleteVirtualMachine(anyString(), eq("instance2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deleteVirtualMachine(anyString(), eq("instance3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deleteInstances(ac,
                        List.of(createCloudInstance("instance1"), createCloudInstance("instance2"),
                                createCloudInstance("instance3"))));

        verify(azureClient, times(3)).deleteVirtualMachine(anyString(), anyString());
    }

    @Test
    public void deleteInstancesByNameShouldSucceed() {
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deleteVirtualMachine(anyString(), anyString())).thenReturn(Completable.complete());

        underTest.deleteInstancesByName(ac, "resourceGroup", List.of("instance1", "instance2"));

        verify(azureClient, times(2)).deleteVirtualMachine(anyString(), anyString());
    }

    @Test
    public void deleteInstancesByNameShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        AuthenticatedContext ac = Mockito.mock(AuthenticatedContext.class);
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(ac.getParameter(AzureClient.class)).thenReturn(azureClient);
        when(azureClient.deleteVirtualMachine(anyString(), eq("instance1"))).thenReturn(Completable.complete());
        when(azureClient.deleteVirtualMachine(anyString(), eq("instance2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deleteVirtualMachine(anyString(), eq("instance3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deleteInstancesByName(ac, "resourceGroup", List.of("instance1", "instance2", "instance3")));

        verify(azureClient, times(3)).deleteVirtualMachine(anyString(), anyString());
    }

    @Test
    public void deleteNetworkInterfacesShouldSucceed() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteNetworkInterfaceAsync(anyString(), anyString())).thenReturn(Completable.complete());

        underTest.deleteNetworkInterfaces(azureClient, "resourceGroup", List.of("network1", "network2"));

        verify(azureClient, times(2)).deleteNetworkInterfaceAsync(anyString(), anyString());
    }

    @Test
    public void deleteNetworkInterfacesShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteNetworkInterfaceAsync(anyString(), eq("network1"))).thenReturn(Completable.complete());
        when(azureClient.deleteNetworkInterfaceAsync(anyString(), eq("network2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deleteNetworkInterfaceAsync(anyString(), eq("network3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deleteNetworkInterfaces(azureClient, "resourceGroup", List.of("network1", "network2", "network3")));

        verify(azureClient, times(3)).deleteNetworkInterfaceAsync(anyString(), anyString());
    }

    @Test
    public void deletePublicIpsShouldSucceed() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deletePublicIpAddressByNameAsync(anyString(), anyString())).thenReturn(Completable.complete());

        underTest.deletePublicIps(azureClient, "resourceGroup", List.of("ip1", "ip2"));

        verify(azureClient, times(2)).deletePublicIpAddressByNameAsync(anyString(), anyString());
    }

    @Test
    public void deletePublicIpsShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deletePublicIpAddressByNameAsync(anyString(), eq("ip1"))).thenReturn(Completable.complete());
        when(azureClient.deletePublicIpAddressByNameAsync(anyString(), eq("ip2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deletePublicIpAddressByNameAsync(anyString(), eq("ip3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deletePublicIps(azureClient, "resourceGroup", List.of("ip1", "ip2", "ip3")));

        verify(azureClient, times(3)).deletePublicIpAddressByNameAsync(anyString(), anyString());
    }

    @Test
    public void deleteLoadBalancersShouldSucceed() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteLoadBalancerAsync(anyString(), anyString())).thenReturn(Completable.complete());

        underTest.deleteLoadBalancers(azureClient, "resourceGroup", List.of("loadbalancer1", "loadbalancer2"));

        verify(azureClient, times(2)).deleteLoadBalancerAsync(anyString(), anyString());
    }

    @Test
    public void deleteLoadBalancersShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestsFinish() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteLoadBalancerAsync(anyString(), eq("loadbalancer1"))).thenReturn(Completable.complete());
        when(azureClient.deleteLoadBalancerAsync(anyString(), eq("loadbalancer2"))).thenReturn(Completable.error(new RuntimeException("failure message 1")));
        when(azureClient.deleteLoadBalancerAsync(anyString(), eq("loadbalancer3"))).thenReturn(Completable.error(new RuntimeException("failure message 2")));

        assertThrows(CloudbreakServiceException.class,
                () -> underTest.deleteLoadBalancers(azureClient, "resourceGroup", List.of("loadbalancer1", "loadbalancer2", "loadbalancer3")));

        verify(azureClient, times(3)).deleteLoadBalancerAsync(anyString(), anyString());
    }

    @Test
    public void deleteAvailabilitySetsShouldSucceed() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteAvailabilitySetAsync(anyString(), anyString())).thenReturn(Completable.complete());

        underTest.deleteAvailabilitySets(azureClient, "resourceGroup", List.of("availabilitySet1", "availabilitySet2"));

        verify(azureClient, times(2)).deleteAvailabilitySetAsync(anyString(), anyString());
    }

    @Test
    public void deleteAvailabilitySetsShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteAvailabilitySetAsync(anyString(), eq("availabilitySet1"))).thenReturn(Completable.complete());
        when(azureClient.deleteAvailabilitySetAsync(anyString(), eq("availabilitySet2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deleteAvailabilitySetAsync(anyString(), eq("availabilitySet3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deleteAvailabilitySets(azureClient, "resourceGroup",
                        List.of("availabilitySet1", "availabilitySet2", "availabilitySet3")));

        verify(azureClient, times(3)).deleteAvailabilitySetAsync(anyString(), anyString());
    }

    @Test
    public void deleteGenericResourcesShouldSucceed() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteGenericResourceByIdAsync(anyString())).thenReturn(Completable.complete());

        underTest.deleteGenericResources(azureClient, List.of("genericResource1", "genericResource2"));

        verify(azureClient, times(2)).deleteGenericResourceByIdAsync(anyString());
    }

    @Test
    public void deleteGenericResourcesShouldHandleAzureErrorsAndThrowCloudbreakServiceExceptionAfterAllRequestFinished() {
        AzureClient azureClient = Mockito.mock(AzureClient.class);
        when(azureClient.deleteGenericResourceByIdAsync(eq("genericResource1"))).thenReturn(Completable.complete());
        when(azureClient.deleteGenericResourceByIdAsync(eq("genericResource2"))).thenReturn(Completable.error(new RuntimeException("failed1")));
        when(azureClient.deleteGenericResourceByIdAsync(eq("genericResource3"))).thenReturn(Completable.error(new RuntimeException("failed2")));

        assertThrows(
                CloudbreakServiceException.class,
                () -> underTest.deleteGenericResources(azureClient, List.of("genericResource1", "genericResource2", "genericResource3")));

        verify(azureClient, times(3)).deleteGenericResourceByIdAsync(anyString());
    }

    @Test
    public void shouldAdjustDesNameLengthIfItsTooLong() {
        String name = "aVeryVeryVeryLoooooooooooooooooooooooooooooooooooooongNaaaaaaaaaaaaaaaaaaaaame";
        String id = UUID.randomUUID().toString();
        String desName = underTest.generateDesNameByNameAndId(name, id);

        assertNotNull(desName, "The generated name must not be null!");
        assertNotEquals(
                desName, "The resource name is not the excepted one!", "aVeryVeryVeryLoooooooooooooooooooooooooooooooooooooongNaaaaaaaaaaaaaaaaaaaaame");
        assertEquals(MAX_DISK_ENCRYPTION_SET_NAME_LENGTH, desName.length(), "The resource name length is wrong");

    }

    @Test
    void convertToCloudConnectorExceptionTestWhenCloudExceptionAndDetails() {
        CloudError cloudError = new CloudError()
                .withCode("123")
                .withMessage("foobar");
        cloudError.details().add(new CloudError().withCode("123").withMessage("detail1"));
        cloudError.details().add(new CloudError().withCode("123").withMessage("detail2"));
        CloudException e = new CloudException("Serious problem", null, cloudError);

        CloudConnectorException result = underTest.convertToCloudConnectorException(e, "Checking resources");

        verifyCloudConnectorException(result,
                "Checking resources failed, status code 123, error message: foobar, details: detail1, detail2");
    }

    @Test
    void convertToCloudConnectorExceptionTestWhenDetailCloudErrorsHaveRequestDisallowedByPolicyCode() throws IOException, NoSuchFieldException {
        CloudError cloudError = new CloudError()
                .withCode("InvalidTemplateDeployment")
                .withMessage("The template deployment failed with multiple errors. Please see details for more information.");

        PolicyViolation policyViolation = new PolicyViolation("PolicyViolation",
                new ObjectMapper().createObjectNode().put("policyDefinitionDisplayName", "dbajzath-azure-restricted-policy"));
        CloudError detail1 = new CloudError()
                .withCode("RequestDisallowedByPolicy")
                .withMessage("Resource 'cbimgwu29d62091481040a03' was disallowed by policy. Reasons: 'West US 2 location is disabled'. " +
                        "See error details for policy resource IDs.");
        Field field = CloudError.class.getDeclaredField("additionalInfo");
        field.setAccessible(true);
        ReflectionUtils.setField(field, detail1, List.of(policyViolation));
        cloudError.details().add(detail1);
        CloudError detail2 = new CloudError()
                .withCode("RequestDisallowedByPolicy")
                .withMessage("Resource 'cbimgwu29d62091481040a03/default' was disallowed by policy. Reasons: 'West US 2 location is disabled'. " +
                        "See error details for policy resource IDs.");
        ReflectionUtils.setField(field, detail2, List.of(policyViolation));
        cloudError.details().add(detail2);

        CloudException e = new CloudException("The template deployment failed with multiple errors. Please see details for more information.", null, cloudError);

        CloudConnectorException result = underTest.convertToCloudConnectorException(e, "Storage account creation");

        verifyCloudConnectorException(result,
                "Storage account creation failed, status code InvalidTemplateDeployment, error message: The template deployment failed with multiple errors. " +
                        "Please see details for more information., details: Resource 'cbimgwu29d62091481040a03' was disallowed by policy. " +
                        "Reasons: 'West US 2 location is disabled'. Policy definition name: dbajzath-azure-restricted-policy, " +
                        "Resource 'cbimgwu29d62091481040a03/default' was disallowed by policy. Reasons: 'West US 2 location is disabled'. " +
                        "Policy definition name: dbajzath-azure-restricted-policy");
    }

    private void verifyCloudConnectorException(CloudConnectorException cloudConnectorException, String messageExpected) {
        assertThat(cloudConnectorException).isNotNull();
        assertThat(cloudConnectorException).hasMessage(messageExpected);
        assertThat(cloudConnectorException).hasNoCause();
    }

    private static CloudException createCloudExceptionWithNoDetails(boolean withBody) {
        CloudException e;
        if (withBody) {
            CloudError cloudError = new CloudError();
            ReflectionTestUtils.setField(cloudError, "details", null);
            e = new CloudException("Serious problem", null, cloudError);
        } else {
            e = new CloudException("Serious problem", null);
        }
        return e;
    }

    static Object[][] convertToCloudConnectorExceptionTestWhenCloudExceptionAndNoDetailsDataProvider() {
        return new Object[][]{
                // testCaseName e
                {"CloudException without body", createCloudExceptionWithNoDetails(false)},
                {"CloudException with body but null details", createCloudExceptionWithNoDetails(true)},
        };
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("convertToCloudConnectorExceptionTestWhenCloudExceptionAndNoDetailsDataProvider")
    void convertToCloudConnectorExceptionTestWhenCloudExceptionAndNoDetails(String testCaseName, CloudException e) {
        CloudConnectorException result = underTest.convertToCloudConnectorException(e, "Checking resources");

        verifyCloudConnectorException(result,
                "Checking resources failed: 'com.microsoft.azure.CloudException: Serious problem', please go to Azure Portal for detailed message");
    }

    @Test
    void convertToCloudConnectorExceptionTestWhenThrowableAndCloudException() {
        Throwable e = createCloudExceptionWithNoDetails(false);

        CloudConnectorException result = underTest.convertToCloudConnectorException(e, "Checking resources");

        verifyCloudConnectorException(result,
                "Checking resources failed: 'com.microsoft.azure.CloudException: Serious problem', please go to Azure Portal for detailed message");
    }

    @Test
    void convertToCloudConnectorExceptionTestWhenThrowableAndNotCloudException() {
        Throwable e = new UnsupportedOperationException("Serious problem");
        CloudConnectorException cloudConnectorException = new CloudConnectorException("foobar");
        when(cloudExceptionConverter.convertToCloudConnectorException(e, "Checking resources")).thenReturn(cloudConnectorException);

        CloudConnectorException result = underTest.convertToCloudConnectorException(e, "Checking resources");

        assertThat(result).isSameAs(cloudConnectorException);
    }

    @Test
    void convertToActionFailedExceptionCausedByCloudConnectorExceptionTest() {
        Throwable e = new UnsupportedOperationException("Serious problem");
        CloudConnectorException cloudConnectorException = new CloudConnectorException("foobar");
        when(cloudExceptionConverter.convertToCloudConnectorException(e, "Checking resources")).thenReturn(cloudConnectorException);

        Retry.ActionFailedException result = underTest.convertToActionFailedExceptionCausedByCloudConnectorException(e, "Checking resources");

        assertThat(result).isNotNull();
        assertThat(result.getCause()).isSameAs(cloudConnectorException);
    }

    @NotNull
    private CloudInstance createCloudInstance(String instanceId) {
        return new CloudInstance(instanceId, null, null, "subnet-1", "az1");
    }

    private Map<String, VirtualMachine> createVirtualMachineMap(String... instanceIds) {
        Map<String, VirtualMachine> virtualMachineMap = new HashMap<>();
        if (instanceIds != null) {
            for (String instanceId : instanceIds) {
                virtualMachineMap.put(instanceId, null);
            }
        }
        return virtualMachineMap;
    }

    /**
     * Expected outputs are copied from the <a href="https://md5calc.com/hash/adler32">online calculator</a> referenced in
     * <a href="https://docs.cloudera.com/cdp/latest/requirements-azure/topics/mc-azure-adls-images.html">the docs</a>.
     * Leading zeroes are trimmed to match the actual output.
     */
    @Test
    void encodeString() {
        Map<String, String> inputAndOutput = Map.of(
                "062d53231d9c48449a2540abe7df2f61", "8301085c",
                "cdppoc", "089d027a",
                "a", "00620062"
        );
        SoftAssertions softly = new SoftAssertions();
        inputAndOutput.forEach((input, output) ->
                softly.assertThat(underTest.encodeString(input))
                        .as(input)
                        .isEqualTo(output.replaceAll("^0+", "")));
        softly.assertAll();
    }
}


text:
title:  Pumziko la Sabato
date:  28/08/2021
---

### Somo la Juma Hili
Mwa. 1:26, 27; Mwa. 9:6; 2 Pet. 2:19; Rum. 6:1—7 Kut. 19:6; Yn 5:7—16.

>
Fungu la Kukariri

> "Mtafanya kazi siku sita; lakini siku ya saba ni Sabato ya kustarehe kabisa, kusanyiko takatifu; msifanye kazi ya namna yo yote; ni Sabato kwa Bwana katika makao yenu yote" (Mambo ya Walawi 23:3).

Tunasikia namna zote za hoja dhidi ya utunzaji wa Sabato ya siku ya saba, au sio? Tunasikia kila kitu kutoka kwa, Yesu aliibadili Sabato kuwa Jumapili, au kwamba Yesu aliikomesha Sabato, au kwamba Paulo alifanya, au kwamba mitume walibadilisha Sabato kuwa Jumapili kwa kuheshimu ufufuo, na kadhalika. Kwa miaka ya karibuni, baadhi ya hoja zimekuwa za kisasa zaidi, zikidai, kwa mfano, kwamba Yesu ndiye pumziko letu la Sabato, na hivyo basi, hatuhitaji kuitunza siku au kuitakasa siku yoyote. Na, bila shaka, daima kutakuwapo hoja, ya ajabu kama ilivyo, kwamba kwa kupumzika katika siku ya saba kwa namna fulani tunatafuta kwenda mbinguni kwa nguvu zetu wenyewe.

Kwa upande mwingine, baadhi ya Wakristo wamependezwa zaidi na wazo la pumziko, la siku ya pumziko, na ingawa wanatoa hoja kwamba siku hiyo ni Jumapili au kwamba haidhuru, wamechukua dhana ya kibiblia ya pumziko na kwa nini ni muhimu.

Bila shaka. kama Waadventista wa Sabato tunaelewa kudumu kwa sheria ya Mungu ya maadili na kwamba utii kwa amri ya nne, kama inavyosomeka, si kutafuta kwenda mbinguni kwa nguvu zetu kuliko ambavyo ingekuwa utii kwa amri ya tano, ya sita, ya kwanza, au amri nyingine yoyote.

Juma hili tutaangalia zaidi katika pumziko ambalo Mungu ametupatia katika amri ya Sabato na kwa nini ni muhimu.

*Jifunze somo la juma hili kwa maandalizi ya Sabato ya Septemba 4.*


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ConceptIndexer
</TITLE>

<META NAME="date" CONTENT="2010-07-28">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.unc.ils.mrc.hive.ir.lucene.indexing

Class ConceptIndexer

java.lang.Object
  edu.unc.ils.mrc.hive.ir.lucene.indexing.ConceptIndexer

All Implemented Interfaces:
Indexer

public class ConceptIndexer
extends java.lang.Object
implements Indexer

Field Summary

private  org.apache.lucene.index.IndexWriter
writer

Constructor Summary

ConceptIndexer(java.lang.String indexDir,
               boolean create)

Method Summary

 void
close()

 void
indexConcept(org.openrdf.concepts.skos.core.Concept concept)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

writer

private org.apache.lucene.index.IndexWriter writer

Constructor Detail

ConceptIndexer

public ConceptIndexer(java.lang.String indexDir,
                      boolean create)

Method Detail

indexConcept

public void indexConcept(org.openrdf.concepts.skos.core.Concept concept)

Specified by:
indexConcept in interface Indexer

close

public void close()

Specified by:
close in interface Indexer

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
elation.require(['elements.elements', 'elements.ui.label'], function() {
  elation.requireCSS('ui.toggle');

  elation.elements.define('ui.toggle', class extends elation.elements.base {
    init() {
      super.init();
      this.defineAttributes({
        checked: { type: 'boolean', default: false },
        disabled: { type: 'boolean', default: false },
        hover: { type: 'boolean', default: false },
        label: { type: 'string', default: '' }
      });
      if (this.checked === '') this.checked = true; // FIXME - type hinting should handle this

      if (this.preview) {
        this.label = 'Toggle';
      }
    }
    create() {
      var checked = this.checked || this.checked === '';
      if (this.bindvar && this.bindvar[0][this.bindvar[1]]) {
        checked = true;
      }

      if (!this.checkbox) {
        this.checkbox = elation.elements.create('input', {
          append: this,
          type: 'checkbox',
          name: this.formname,
          checked: checked
        });
        this.createlabel(this.label);
        this.toggleelement = elation.elements.create('div', {
          append: this,
        });

        elation.events.add(this, 'click', (ev) => { this.toggle(); ev.stopPropagation(); });
        elation.events.add(this, 'mouseover', (ev) => { this.hover = true; });
        elation.events.add(this, 'mouseout', (ev) => { this.hover = false; });
      }
      this.refresh();
    }
    createlabel(value) {
      if (!this.formlabel) {
        this.formlabel = elation.elements.create('ui.label', {
          label: value,
          append: this,
        });
        this.formlabel.setLabel(value);
      } else {
        this.formlabel.setLabel(value);
      }
    }
    toggle() {
      if (this.disabled === false) {
        this.setstate(!(this.checked || this.checked === ''));
      }
    }
    setlabel(newlabel) {
      this.label = newlabel;
      if (this.formlabel) {
        this.formlabel.setLabel(newlabel);
      } else {
        this.createlabel(newlabel);
      }
    }
    setstate(newstate) {
      this.checked = newstate;

      // If a bindvar is passed in, automatically update the specified object property
      if (this.bindvar) {
        this.bindvar[0][this.bindvar[1]] = this.checked;
      }

      var evname = "toggle_" + (this.checked ? "on" : "off");
      // Fire two events - separate toggle_on/toggle_off events, plus a general toggle event
      elation.events.fire({type: evname, element: this, data: this.checked});
      elation.events.fire({type: 'toggle', element: this, data: this.checked});

      this.refresh();
    }
    render() {
      super.render();
      if (this.checkbox) {
        this.checkbox.checked = (this.checked || this.checked === '');
      }
    }
    focus() {
      this.toggle();
      this.checkbox.focus();
    }
  });
});


text:
<!doctype>

        <meta charset="UTF-8">

Attila dans Venus

        [précédent]

        Pour commencer avec Attila, vous pouvez regarder la documentation officielle de l'outil que vous trouverez ici :
        [documentation Attila]

        Par défaut, le modèle appelée dans Venus est l'entité qui porte le même nom que le controlleur afin de vous
        accélérer le travail. Cela ne correspond pas toujours au besoin et vous pouvez donc choisir d'appeler une
        nouvelle entité dans votre contrôleur.

        Nous allons supposer la création de cette table (profitez en pour utiliser le scaffolding qui va créer la table,
        l'entité et le modèle associés) dans /bundles/conf/Db.conf :

"news": {
    "fields": {
    "id": {
        "type": "int",
        "key": "primary",
        "null": false,
        "undefined": true,
        "autoincrement": true
    },
    "title": {
        "type": "varchar",
            "null": false
        }
    }
}

        Lançons le scaffolding :

            php bin/console  scaffolding:run -v -p HomeBundle -c -e

        Après le lancement du scaffolding, vous aurez les fichiers de l'entité et du modèle de cette nouvelle table dans
        votre framework

        A présent nous allons ajouter l'utilisation de ce modèle dans notre controller afin de bien comprendre la
        rapidité et l'efficacité du framework (c'est notre méthode recommandée mais ce n'est pas la seule méthode
        possible). Nous allons dans notre controller /src/Demo/app/Controller/Exemple1.php.

namespace Venus\src\Demo\Controller;

use \Venus\src\Demo\common\Controller as Controller;
use \Venus\src\Demo\Model\news as news;

# ... #

    public function __construct() {

		$this->modelNews = function() { return new news; }; //création de notre raccourcis directement dans le constructeur
		parent::__construct();
	}

# ... #

    public function show() {

		$aExemple = $this->modelNews->get(); # nous rajoutons notre action ici avec un get automatique
		var_dump($aExemple);
	}

        Si vous testez ces lignes, vous verrez que chaque ligne insérée en base de données apparait dans le var_dump.

        [suivant]


text:
namespace FeedbackSystem.Models.Enums
{
    public enum UserStatusType
    {
        Regular,
        // Has been a client of the company for an
        // extended period of time
        Seniour,
        // A client who makes a major contribution
        // to the company's profit
        Lucrative
    }
}


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.KubernetesConfiguration.Models
{
    public partial class GitRepositoryDefinition : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Uri))
            {
                if (Uri != null)
                {
                    writer.WritePropertyName("url");
                    writer.WriteStringValue(Uri.AbsoluteUri);
                }
                else
                {
                    writer.WriteNull("url");
                }
            }
            if (Optional.IsDefined(TimeoutInSeconds))
            {
                if (TimeoutInSeconds != null)
                {
                    writer.WritePropertyName("timeoutInSeconds");
                    writer.WriteNumberValue(TimeoutInSeconds.Value);
                }
                else
                {
                    writer.WriteNull("timeoutInSeconds");
                }
            }
            if (Optional.IsDefined(SyncIntervalInSeconds))
            {
                if (SyncIntervalInSeconds != null)
                {
                    writer.WritePropertyName("syncIntervalInSeconds");
                    writer.WriteNumberValue(SyncIntervalInSeconds.Value);
                }
                else
                {
                    writer.WriteNull("syncIntervalInSeconds");
                }
            }
            if (Optional.IsDefined(RepositoryRef))
            {
                if (RepositoryRef != null)
                {
                    writer.WritePropertyName("repositoryRef");
                    writer.WriteObjectValue(RepositoryRef);
                }
                else
                {
                    writer.WriteNull("repositoryRef");
                }
            }
            if (Optional.IsDefined(SshKnownHosts))
            {
                if (SshKnownHosts != null)
                {
                    writer.WritePropertyName("sshKnownHosts");
                    writer.WriteStringValue(SshKnownHosts);
                }
                else
                {
                    writer.WriteNull("sshKnownHosts");
                }
            }
            if (Optional.IsDefined(HttpsUser))
            {
                if (HttpsUser != null)
                {
                    writer.WritePropertyName("httpsUser");
                    writer.WriteStringValue(HttpsUser);
                }
                else
                {
                    writer.WriteNull("httpsUser");
                }
            }
            if (Optional.IsDefined(HttpsCACert))
            {
                if (HttpsCACert != null)
                {
                    writer.WritePropertyName("httpsCACert");
                    writer.WriteStringValue(HttpsCACert);
                }
                else
                {
                    writer.WriteNull("httpsCACert");
                }
            }
            if (Optional.IsDefined(LocalAuthRef))
            {
                if (LocalAuthRef != null)
                {
                    writer.WritePropertyName("localAuthRef");
                    writer.WriteStringValue(LocalAuthRef);
                }
                else
                {
                    writer.WriteNull("localAuthRef");
                }
            }
            writer.WriteEndObject();
        }

        internal static GitRepositoryDefinition DeserializeGitRepositoryDefinition(JsonElement element)
        {
            Optional<Uri> url = default;
            Optional<long?> timeoutInSeconds = default;
            Optional<long?> syncIntervalInSeconds = default;
            Optional<RepositoryRefDefinition> repositoryRef = default;
            Optional<string> sshKnownHosts = default;
            Optional<string> httpsUser = default;
            Optional<string> httpsCACert = default;
            Optional<string> localAuthRef = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("url"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        url = null;
                        continue;
                    }
                    url = new Uri(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("timeoutInSeconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        timeoutInSeconds = null;
                        continue;
                    }
                    timeoutInSeconds = property.Value.GetInt64();
                    continue;
                }
                if (property.NameEquals("syncIntervalInSeconds"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        syncIntervalInSeconds = null;
                        continue;
                    }
                    syncIntervalInSeconds = property.Value.GetInt64();
                    continue;
                }
                if (property.NameEquals("repositoryRef"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        repositoryRef = null;
                        continue;
                    }
                    repositoryRef = RepositoryRefDefinition.DeserializeRepositoryRefDefinition(property.Value);
                    continue;
                }
                if (property.NameEquals("sshKnownHosts"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        sshKnownHosts = null;
                        continue;
                    }
                    sshKnownHosts = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("httpsUser"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        httpsUser = null;
                        continue;
                    }
                    httpsUser = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("httpsCACert"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        httpsCACert = null;
                        continue;
                    }
                    httpsCACert = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("localAuthRef"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        localAuthRef = null;
                        continue;
                    }
                    localAuthRef = property.Value.GetString();
                    continue;
                }
            }
            return new GitRepositoryDefinition(url.Value, Optional.ToNullable(timeoutInSeconds), Optional.ToNullable(syncIntervalInSeconds), repositoryRef.Value, sshKnownHosts.Value, httpsUser.Value, httpsCACert.Value, localAuthRef.Value);
        }
    }
}


text:
Create a Sponsorship For {{children.firstName}} {{children.lastName}}

      <form name="sponsorshipForm" class="form-horizontal" ng-submit="createsponsorship(sponsorshipForm.$valid)">

        <fieldset>

            Payment Type

            <input name="paymentType" type="radio" ng-model="sponsorship.paymentType" id="Payment Type"  placeholder="Payment Type" value="1" required>"Payment Type 1"

            <input name="paymentType" type="radio" ng-model="sponsorship.paymentType" id="Payment Type"  placeholder="Payment Type" value="2" >"Payment Type 2"

Payment Type is Required

            Monthly Subscription

              <input name="name" type="radio" ng-model="sponsorship.monthlySubscription" id="Monthly Subscription" value="true" required>Yes

              <input name="name" type="radio" ng-model="sponsorship.monthlySubscription" id="Monthly Subscription" value="false">No

This field is Required

            Sponsorship Type
	    Already fully sponsored

 Full Sponsorship

            <input ng-show="children.sponsorshipType===0" name="sponsorshipType" type="radio" ng-model="sponsorship.sponsorshipType" id="Sponsorship Type" value="full" required>

 Half Sponsorship

            <input ng-hide="children.sponsorshipType===2" name="sponsorshipType" type="radio" ng-model="sponsorship.sponsorshipType" id="Sponsorship Type" value="half">

This field is Required

            <input type="submit" name="submit" class="btn btn-default">

        </fieldset>
      </form>


text:
<bill session="111" type="s" number="368" updated="2009-03-07T14:17:20-05:00">
	<status><introduced date="1233637200" datetime="2009-02-03"/></status>

	<introduced date="1233637200" datetime="2009-02-03"/>
	<titles>
		<title type="official" as="introduced">A bill for the relief of Alemseghed Mussie Tesfamical.</title>
	</titles>
	<sponsor id="300087"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1233637200" datetime="2009-02-03"><text>Read twice and referred to the Committee on the Judiciary.</text></action>
	</actions>
	<committees>
		<committee name="Senate Judiciary" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>
		<term name="Private legislation"/>
	</subjects>
	<amendments>

	</amendments>

	2/3/2009--Introduced.
Provides for the relief of Alemseghed Mussie Tesfamical.

</bill>