text:
"""
This module encapsulates the access of sws term data
"""

from django.conf import settings
from uw_sws.term import (
    get_term_by_year_and_quarter, get_term_by_date, get_term_before,
    get_term_after)
from course_grader.dao import current_datetime
from course_grader.exceptions import InvalidTerm
from datetime import timedelta
from logging import getLogger
import re

logger = getLogger(__name__)

def submission_deadline_warning(term):
    hours = getattr(settings, "SUBMISSION_DEADLINE_WARNING_HOURS", 48)
    warning_start = term.grade_submission_deadline - timedelta(hours=hours)
    return (current_datetime() >= warning_start)

def is_grading_period_open(term_or_section):
    return term_or_section.is_grading_period_open(current_datetime())

def is_grading_period_past(term):
    return term.is_grading_period_past(current_datetime())

def term_from_param(param):
    valid = re.compile(r"^2\d{3}-(?:winter|spring|summer|autumn)$", re.I)
    if not valid.match(param):
        raise InvalidTerm()
    (year, quarter) = param.split("-")
    return get_term_by_year_and_quarter(year, quarter)

def term_from_date(date):
    return get_term_by_date(date)

def current_term():
    return term_from_date(current_datetime().date())

def next_gradable_term():
    term = current_term()
    if current_datetime() > term.grade_submission_deadline:
        return get_term_after(term)
    else:
        return term

def previous_gradable_term():
    term = current_term()
    if current_datetime() > term.grade_submission_deadline:
        return term
    else:
        return get_term_before(term)

def all_viewable_terms():
    term = current_term()
    terms = []
    for i in range(-1, getattr(settings, "PAST_TERMS_VIEWABLE", 4)):
        terms.append(term)
        term = get_term_before(term)
    return terms

def is_graderoster_available_for_term(section):
    if is_grading_period_open(section):
        return True

    # Return True if the current date is after term.grade_submission_deadline,
    # but on or before the following term.last_day_instruction
    curr_dt = current_datetime()
    if (curr_dt > section.term.grade_submission_deadline and
            curr_dt.date() <= get_term_after(
                section.term).last_day_instruction):
        return True

    return False


text:
@implementation Video

- (instancetype)initWithTitle:(NSString *)title
                    thumbnail:(UIImage *)thumbnail
                        video:(NSString *)video
                          tag:(NSString *)tag
                     language:(NSString *)language {
  self = [super init];
  if (self) {
    _title = [title copy];
    _thumbnail = [thumbnail copy];
    _video = [video copy];
    _tag = [tag copy];
    _language = [language copy];
  }
  return self;
}

@end

redpajama_set_name: RedPajamaGithub


text:
function reset ({state}) {
  state.merge('debugger', {
    isExecuting: false,
    currentPage: 'signals',
    lastMutationCount: 0,
    currentSignalExecutionId: null,
    currentRememberedSignalExecutionId: null,
    expandedSignalGroups: [],
    currentMutationPath: null,
    mutationsError: false
  })
  // Do update correctly
  state.set('debugger.signals', {})
  state.set('debugger.mutations', [])
  state.set('debugger.model', state.get('debugger.initialModel'))
}

export default reset


text:
package libsecrets

import (
	"github.com/keybase/client/go/client"
	"github.com/keybase/client/go/libkb"
	"github.com/keybase/client/go/protocol/keybase1"
)

// NewStreamFilter creates a new StreamFilter
func NewStreamFilter(source client.Source, sink client.Sink) *StreamFilter {
	return &StreamFilter{
		source: source,
		sink:   sink,
	}
}

// StreamFilter manages the input and output streams.
type StreamFilter struct {
	source client.Source
	sink   client.Sink
}

// Open the streams for read and write
func (s *StreamFilter) Open() error {
	err := s.sink.Open()
	if err == nil {
		err = s.source.Open()
	}
	return err
}

// Close the streams
func (s *StreamFilter) Close(inerr error) error {
	e1 := s.source.CloseWithError(inerr)
	e2 := s.sink.Close()
	e3 := s.sink.HitError(inerr)
	return libkb.PickFirstError(e1, e2, e3)
}

// ClientOpen Connect the input and output streams with the Keybase client
func (s *StreamFilter) ClientOpen() (snk, src keybase1.Stream, err error) {
	if err = s.Open(); err != nil {
		return
	}

	snk = libkb.G.XStreams.ExportWriter(s.sink)
	src = libkb.G.XStreams.ExportReader(s.source)
	return
}


text:
FROM nginx

MAINTAINER Gianpaolo Macario <gmacario@gmail.com>

# Setup Nginx Server Blocks
# See http://www.unixmen.com/setup-nginx-server-blocks-virtual-hosts-on-ubuntu-15-10/

RUN echo "
Welcome to gmoffice.solarma.it Website
" >/usr/share/nginx/html/index.html

# EOF


text:
class AddSearchtermToImage < ActiveRecord::Migration
  def change
    add_column :images, :search_term, :string
  end
end


text:
package CXGN::Trial::TrialLayoutDownload;

=head1 NAME

CXGN::Trial::TrialLayoutDownload

=head1 SYNOPSIS

Module to format layout info for trial based on which columns user wants to see. Selected columns can be:
- for plot level layout: 'plot_name','plot_id','accession_name','accession_id','plot_number','block_number','is_a_control','rep_number','range_number','row_number','col_number','seedlot_name','seed_transaction_operator','num_seed_per_plot','pedigree','location_name','trial_name','year','synonyms','tier','plot_geo_json'
- for plant level layout: 'plant_name','plant_id','subplot_name','subplot_id','plot_name','plot_id','accession_name','accession_id','plot_number','block_number','is_a_control','range_number','rep_number','row_number','col_number','seedlot_name','seed_transaction_operator','num_seed_per_plot','subplot_number','plant_number','pedigree','location_name','trial_name','year','synonyms','tier','plot_geo_json'
- for subplot level layout:
'subplot_name','subplot_id','plot_name','plot_id','accession_name','accession_id','plot_number','block_number','is_a_control','rep_number','range_number','row_number','col_number','seedlot_name','seed_transaction_operator','num_seed_per_plot','subplot_number','pedigree','location_name','trial_name','year','synonyms','tier','plot_geo_json'
- for tissue sample field trial level layout:
'tissue_sample_name','tissue_sample_id','plant_name','plant_id','subplot_name','subplot_id','plot_name','plot_id','accession_name','accession_id','plot_number','block_number','is_a_control','range_number','rep_number','row_number','col_number','seedlot_name','seed_transaction_operator','num_seed_per_plot','subplot_number','plant_number','tissue_sample_number','pedigree','location_name','trial_name','year','synonyms','tier','plot_geo_json'

This module can also optionally include treatments into the output.
This module can also optionally include accession trait performace summaries into the output.

This module is used from CXGN::Trial::Download::Plugin::TrialLayoutExcel, CXGN::Trial::Download::Plugin::TrialLayoutCSV, CXGN::Fieldbook::DownloadFile, CXGN::Trial->get_plots, CXGN::Trial->get_plants, CXGN::Trial->get_subplots, CXGN::Trial->get_tissue_samples

my $trial_layout_download = CXGN::Trial::TrialLayoutDownload->new({
    schema => $schema,
    trial_id => $trial_id,
    data_level => 'plots',
    treatment_project_ids => [1,2],
    selected_columns => {"plot_name"=>1,"plot_number"=>1,"block_number"=>1},
    selected_trait_ids => [1,2,3],
});
my $output = $trial_layout_download->get_layout_output();

Output is an ArrayRef or ArrayRefs where the first entry is the Header and subsequent entries are the layout entries.

If you don't need treatments or phenotype summaries included you can ignore those keys like:

my $trial_layout_download = CXGN::Trial::TrialLayoutDownload->new({
    schema => $schema,
    trial_id => $trial_id,
    data_level => 'plots',
    selected_columns => {"plot_name"=>1,"plot_number"=>1,"block_number"=>1},
});
my $output = $trial_layout_download->get_layout_output();

Data Level can be plots, plants, subplots (for splitplot design), field_trial_tissue_samples (for seeing tissue_samples linked to plants in a field trial), plate (for seeing genotyping_layout plate tissue_samples)

=head1 AUTHORS

=cut

use Moose;
use Moose::Util::TypeConstraints;
use Try::Tiny;
use Data::Dumper;
use CXGN::Trial;
use CXGN::Trial::TrialLayout;
use SGN::Model::Cvterm;
use CXGN::Stock;
use CXGN::Stock::Accession;
use JSON;
use CXGN::List::Transform;
use CXGN::Phenotypes::Summary;
use CXGN::Phenotypes::Exact;
use CXGN::Trial::TrialLayoutDownload::PlotLayout;
use CXGN::Trial::TrialLayoutDownload::PlantLayout;
use CXGN::Trial::TrialLayoutDownload::SubplotLayout;
use CXGN::Trial::TrialLayoutDownload::TissueSampleLayout;
use CXGN::Trial::TrialLayoutDownload::GenotypingPlateLayout;
use CXGN::Trial::TrialLayoutDownload::SamplingTrialLayout;

has 'schema' => (
    is       => 'rw',
    isa      => 'DBIx::Class::Schema',
    required => 1,
);

has 'trial_id'   => (
    isa => "Int",
    is => 'ro',
    required => 1,
);

has 'data_level' => (
    is => 'ro',
    isa => 'Str',
    default => 'plots',
);

has 'treatment_project_ids' => (
    isa => 'ArrayRef[Int]|Undef',
    is => 'rw'
);

has 'selected_columns' => (
    is => 'ro',
    isa => 'HashRef',
    default => sub { {"plot_name"=>1, "plot_number"=>1} }
);

has 'include_measured'=> (
    is => 'rw',
    isa => 'Str',
    default => 'false',
);

has 'all_stats'=> (
    is => 'rw',
    isa => 'Str',
    default => 'true',
);

has 'use_synonyms'=> (
    is => 'rw',
    isa => 'Str',
    default => 'true',
);

has 'selected_trait_ids'=> (
    is => 'ro',
    isa => 'ArrayRef[Int]|Undef',
);

has 'trial_stock_type'=> (
    is => 'rw',
    isa => 'Str',
    required => 0,
    default => 'accession',
);

#The attributes below are populated when get_layout_output is run, so should not be instantiatied
#----------------------

#This is a hashref of the cached trial_layout_json that comes from CXGN::Trial::TrialLayout
has 'design' => (
    isa => 'HashRef',
    is => 'rw',
);

subtype 'Trial',
  as 'Ref',
    where { $_ =~ /CXGN::Trial/ || $_ =~ /CXGN::PhenotypingTrial/ || $_ =~  /CXGN::GenotypingTrial/ || $_ =~ /CXGN::Folder/ || $_ =~ /CXGN::CrossingTrial/ || $_ =~ /CXGN::ManagementFactor/ || $_ =~ /CXGN::SamplingTrial/},
  message { "The string, $_, was not a valid trial object type"};

has 'trial' => (
    isa => 'Trial',
    is => 'rw',
);

#This treatment_info_hash contains all the info needed to make and fill the columns for the various treatments (management factors). All of these lists are in the same order.
#A key called treatment_trial_list that is a arrayref of the CXGN::Trial entries that represent the treatments (management factors) in this trial
#A key called treatment_trial_names_list that is an arrayref of just the treatment (management factor) names
#A key called treatment_units_hash_list that is a arrayref of hashrefs where the hashrefs indicate the stocks that the treatment was applied to.
has 'treatment_info_hash' => (
    isa => 'HashRef',
    is => 'rw',
);

has 'trait_header'=> (
    is => 'rw',
    isa => 'ArrayRef[Str]|Undef',
);

has 'exact_performance_hash' => (
    isa => 'HashRef',
    is => 'rw',
);

has 'overall_performance_hash' => (
    isa => 'HashRef',
    is => 'rw',
);

sub get_layout_output {
    my $self = shift;
    my $trial_id = $self->trial_id();
    my $schema = $self->schema();
    my $data_level = $self->data_level();
    my $include_measured = $self->include_measured();
    my $all_stats = $self->all_stats();
    my $use_synonyms = $self->use_synonyms();
    my %selected_cols = %{$self->selected_columns};
    my $treatments = $self->treatment_project_ids();
    my @selected_traits = $self->selected_trait_ids() ? @{$self->selected_trait_ids} : ();
    my %errors;
    my @error_messages;
    my $trial_stock_type = $self->trial_stock_type();
    print STDERR "TrialLayoutDownload for Trial id: ($trial_id) ".localtime()."\n";

    my $trial_layout;
    try {
        my %param = ( schema => $schema, trial_id => $trial_id );
        if ($data_level eq 'plate'){
            $param{experiment_type} = 'genotyping_layout';
        } else {
            $param{experiment_type} = 'field_layout';
        }
        $trial_layout = CXGN::Trial::TrialLayout->new(\%param);
    };
    if (!$trial_layout) {
        #print STDERR "Trial does not have valid field design.\n";
        push @error_messages, "Trial does not have valid field design.";
        $errors{'error_messages'} = \@error_messages;
        return \%errors;
    }
    print STDERR "TrialLayoutDownload retrieving deisgn ".localtime."\n";
    my $design = $trial_layout->get_design();
    if (!$design){
        push @error_messages, "Trial does not have valid field design. Please contact us.";
        $errors{'error_messages'} = \@error_messages;
        return \%errors;
    }

    if ($data_level eq 'plot_fieldMap' ) {
        my %hash;
        my @rows;
        my @cols;
        foreach my $key (keys %$design) {
            my $design_info = $design->{$key};
            my $row_num = $design_info->{row_number};
            my $col_num = $design_info->{col_number};
            my $accession = $design_info->{accession_name};
            $hash{$row_num}->{$col_num} = $accession;
            push @rows, $row_num;
            push @cols, $col_num;
        }
        print STDERR "TrialLayoutDownload End for Trial id: ($trial_id) ".localtime()."\n";
        return {output => \%hash, rows => \@rows, cols => \@cols};
    }

    print STDERR "TrialLayoutDownload running stock type checks ".localtime."\n";

    my $selected_trial = CXGN::Trial->new({bcs_schema => $schema, trial_id => $trial_id});
    my $has_plants = $selected_trial->has_plant_entries();
    my $has_subplots = $selected_trial->has_subplot_entries();
    my $has_tissue_samples = $selected_trial->has_tissue_sample_entries();

    print STDERR "TrialLayoutDownload retrieving accessions ".localtime."\n";

    my $accessions = $selected_trial->get_accessions();
    my @accession_ids;
    foreach (@$accessions){
        push @accession_ids, $_->{stock_id};
    }
    print STDERR "TrialLayoutDownload retrieving trait performance if requested ".localtime."\n";
    my $summary_values = [];
    if (scalar(@selected_traits)>0){
        my $summary = CXGN::Phenotypes::Summary->new({
            bcs_schema=>$schema,
            trait_list=>\@selected_traits,
            accession_list=>\@accession_ids
        });
        $summary_values = $summary->search();
    }
    my %overall_performance_hash;
    foreach (@$summary_values){
        $overall_performance_hash{$_->[0]}->{$_->[8]} = $_;
    }

    my @treatment_trials;
    my @treatment_names;
    my @treatment_units_array;
    if ($treatments){
        foreach (@$treatments){
            my $treatment_trial = CXGN::Trial->new({bcs_schema => $schema, trial_id => $_});
            my $treatment_name = $treatment_trial->get_name();
            push @treatment_trials, $treatment_trial;
            push @treatment_names, $treatment_name;
        }
    }
    my $exact_performance_hash;
    if ($data_level eq 'plots') {
        if ($include_measured eq 'true') {
            print STDERR "Getting exact trait values\n";
            my $exact = CXGN::Phenotypes::Exact->new({
                bcs_schema=>$schema,
                trial_id=>$trial_id,
                data_level=>'plot'
            });
            $exact_performance_hash = $exact->search();
            #print STDERR "Exact Performance hash is ".Dumper($exact_performance_hash)."\n";
        }
        foreach (@treatment_trials){
            my $treatment_units = $_ ? $_->get_observation_units_direct('plot', ['treatment_experiment']) : [];
            push @treatment_units_array, $treatment_units;
        }
    } elsif ($data_level eq 'plants') {
        if (!$has_plants){
            push @error_messages, "Trial does not have plants, so you should not try to download a plant level layout.";
            $errors{'error_messages'} = \@error_messages;
            return \%errors;
        }
        if ($include_measured eq 'true') {
            my $exact = CXGN::Phenotypes::Exact->new({
                bcs_schema=>$schema,
                trial_id=>$trial_id,
                data_level=>'plant'
            });
            $exact_performance_hash = $exact->search();
        }
        foreach (@treatment_trials){
            my $treatment_units = $_ ? $_->get_observation_units_direct('plant', ['treatment_experiment']) : [];
            push @treatment_units_array, $treatment_units;
        }
    } elsif ($data_level eq 'subplots') {
        if (!$has_subplots){
            push @error_messages, "Trial does not have subplots, so you should not try to download a subplot level layout.";
            $errors{'error_messages'} = \@error_messages;
            return \%errors;
        }
        if ($include_measured eq 'true') {
            my $exact = CXGN::Phenotypes::Exact->new({
                bcs_schema=>$schema,
                trial_id=>$trial_id,
                data_level=>'subplot'
            });
            $exact_performance_hash = $exact->search();
        }
        foreach (@treatment_trials){
            my $treatment_units = $_ ? $_->get_observation_units_direct('subplot', ['treatment_experiment']) : [];
            push @treatment_units_array, $treatment_units;
        }
    } elsif ($data_level eq 'field_trial_tissue_samples') {
        if (!$has_tissue_samples){
            push @error_messages, "Trial does not have tissue samples, so you should not try to download a tissue sample level layout.";
            $errors{'error_messages'} = \@error_messages;
            return \%errors;
        }
        if ($include_measured eq 'true') {
            my $exact = CXGN::Phenotypes::Exact->new({
                bcs_schema=>$schema,
                trial_id=>$trial_id,
                data_level=>'tissue_sample'
            });
            $exact_performance_hash = $exact->search();
        }
        foreach (@treatment_trials){
            my $treatment_units = $_ ? $_->get_observation_units_direct('tissue_sample', ['treatment_experiment']) : [];
            push @treatment_units_array, $treatment_units;
        }
    } elsif ($data_level eq 'plate') {
        #to make the download in the header for genotyping trials more easily understood, the terms change here
        if (exists($selected_cols{'plot_name'})){
            $selected_cols{'tissue_sample_name'} = 1;
            delete $selected_cols{'plot_name'};
        }
        if (exists($selected_cols{'plot_number'})){
            $selected_cols{'well_A01'} = 1;
            delete $selected_cols{'plot_number'};
        }
        $selected_cols{'exported_tissue_sample_name'} = 1;
    }

    print STDERR "Treatment stock hashes\n";
    my @treatment_stock_hashes;
    foreach my $u (@treatment_units_array){
        my %treatment_stock_hash;
        foreach (@$u){
            $treatment_stock_hash{$_->[1]}++;
        }
        push @treatment_stock_hashes, \%treatment_stock_hash;
    }

    my %treatment_info_hash = (
        treatment_trial_list => \@treatment_trials,
        treatment_trial_names_list => \@treatment_names,
        treatment_units_hash_list => \@treatment_stock_hashes
    );

    #combine sorted exact and overall trait names and if requested convert to synonyms
    my @exact_trait_names = sort keys %$exact_performance_hash;
    my @overall_trait_names = sort keys %overall_performance_hash;
    my @traits = (@exact_trait_names, @overall_trait_names);

    if ($use_synonyms eq 'true') {
        print STDERR "Getting synonyms\n";
        my $t = CXGN::List::Transform->new();
        my $trait_id_list = $t->transform($schema, 'traits_2_trait_ids', \@traits);
        my @trait_ids = @{$trait_id_list->{'transform'}};
        my $synonym_list = $t->transform($schema, 'trait_ids_2_synonyms', $trait_id_list->{'transform'});
        my @missing = @{$synonym_list->{'missing'}};

        if (scalar @missing) {
            #print STDERR "Traits @missing don't have synonyms. Sticking with full trait names instead\n";

            #push @error_messages, "Traits @missing don't have synonyms. Please turn off synonym option before proceeding\n";
            #$errors{'error_messages'} = \@error_messages;
            #return \%errors;
        } else {
            @traits = @{$synonym_list->{'transform'}};
        }
    }

    my $layout_build = {
        schema => $schema,
        trial_id => $trial_id,
        data_level => $data_level,
        selected_columns => \%selected_cols,
        treatment_project_ids => $treatments,
        design => $design,
        trial => $selected_trial,
        treatment_info_hash => \%treatment_info_hash,
        trait_header => \@traits,
        exact_performance_hash => $exact_performance_hash,
        overall_performance_hash => \%overall_performance_hash,
        all_stats => $all_stats,
        trial_stock_type => $trial_stock_type
    };
    my $layout_output;

    print STDERR "TrialLayoutDownload getting output object".localtime."\n";

    if ($data_level eq 'plots' ) {
        $layout_output = CXGN::Trial::TrialLayoutDownload::PlotLayout->new($layout_build);
    }
    if ($data_level eq 'plants' ) {
        $layout_output = CXGN::Trial::TrialLayoutDownload::PlantLayout->new($layout_build);
    }
    if ($data_level eq 'subplots' ) {
        $layout_output = CXGN::Trial::TrialLayoutDownload::SubplotLayout->new($layout_build);
    }
    if ($data_level eq 'field_trial_tissue_samples' ) {
        $layout_output = CXGN::Trial::TrialLayoutDownload::TissueSampleLayout->new($layout_build);
    }
    if ($data_level eq 'plate' ) {
        $layout_output = CXGN::Trial::TrialLayoutDownload::GenotypingPlateLayout->new($layout_build);
    }
    if ($data_level eq 'samplingtrial' ) {
        $layout_output = CXGN::Trial::TrialLayoutDownload::SamplingTrialLayout->new($layout_build);
    }

    print STDERR "TrialLayoutDownload retrieving output ".localtime."\n";

    my $output = $layout_output->retrieve();

    print STDERR "TrialLayoutDownload End for Trial id: ($trial_id) ".localtime()."\n";
    return {output => $output};
}

sub _add_treatment_to_line {
    my $self = shift;
    my $treatment_stock_hashes = shift;
    my $line = shift;
    my $design_unit_name = shift;
    foreach (@$treatment_stock_hashes){
        if(exists($_->{$design_unit_name})){
            push @$line, 1;
        } else {
            push @$line, '';
        }
    }
    return $line;
}

sub _add_overall_performance_to_line {
    my $self = shift;
    my $overall_trait_names = shift;
    my $line = shift;
    my $overall_performance_hash = shift;
    my $design_info = shift;
    my $all_stats = shift;
    foreach my $t (@$overall_trait_names){
        my $perf = $overall_performance_hash->{$t}->{$design_info->{"accession_id"}};
        if($perf && $all_stats eq 'true'){
            push @$line, "Avg: ".$perf->[3]." Min: ".$perf->[5]." Max: ".$perf->[4]." Count: ".$perf->[2]." StdDev: ".$perf->[6];
        } elsif($perf) {
            push @$line, "Avg: ".$perf->[3]." Count: ".$perf->[2];
        } else {
            push @$line, '';
        }
    }
    return $line;
}

sub _get_all_pedigrees {
    my $self = shift;
    my $design = shift;
    my $schema = $self->schema();
    my %design = %{$design};

    print STDERR "TrialLayoutDownload running get_all_pedigrees ".localtime()."\n";

    # collect all unique accession ids for pedigree retrieval
    my %accession_id_hash;
    foreach my $key (keys %design) {
        $accession_id_hash{$design{$key}{'accession_id'}} = $design{$key}{'accession_name'};
    }
    my @accession_ids = keys %accession_id_hash;

    my %pedigree_strings;
    if (scalar(@accession_ids)>0) {
        # retrieve pedigree info using batch download (fastest method), then extract pedigree strings from download rows.
        my $stock = CXGN::Stock->new ( schema => $schema);
        my $pedigree_rows = $stock->get_pedigree_rows(\@accession_ids, 'parents_only');
        foreach my $row (@$pedigree_rows) {
            my ($progeny, $female_parent, $male_parent, $cross_type) = split "\t", $row;
            my $string = join ('/', $female_parent ? $female_parent : 'NA', $male_parent ? $male_parent : 'NA');
            $pedigree_strings{$progeny} = $string;
        }
    }

    print STDERR "TrialLayoutDownload get_all_pedigrees finished at ".localtime()."\n";

    return \%pedigree_strings;
}

sub _add_exact_performance_to_line {
    my $self = shift;
    my $exact_trait_names = shift;
    my $line = shift;
    my $exact_performance_hash = shift;
    my $observationunit_name = shift;

    foreach my $trait (@$exact_trait_names){
        my $value = $exact_performance_hash->{$trait}->{$observationunit_name };
        if($value) {
            push @$line, $value
        } else {
            push @$line, '';
        }
    }
    return $line;
}

1;


text:
<!--
Create tabs with an icon and label, using the tabs-positive style.
Each tab's child <ion-nav-view> directive will have its own
navigation history that also transitions its views in and out.
-->
<ion-tabs class="tabs-icon-top tabs-color-active-positive">

  <!-- Dashboard Tab -->
  <ion-tab title="{{'TABS_LIST' | translate}}" icon-off="ion-ios-list-outline" icon-on="ion-ios-list" href="#/tab/list">
    <ion-nav-view name="tab-list"></ion-nav-view>
  </ion-tab>

  <ion-tab title="{{'TABS_ANSWER' | translate}}" icon-off="ion-ios-eye-outline" icon-on="ion-ios-eye" href="#/tab/answer">
    <ion-nav-view name="tab-answer"></ion-nav-view>
  </ion-tab>

  <ion-tab title="{{'TABS_SETTINGS' | translate}}" icon-off="ion-ios-gear-outline" icon-on="ion-ios-gear" href="#/tab/settings">
    <ion-nav-view name="tab-settings"></ion-nav-view>
  </ion-tab>
</ion-tabs>


text:
import { Version } from '@microsoft/sp-core-library';
import {
  BaseClientSideWebPart,
  IPropertyPaneConfiguration,
  PropertyPaneTextField,
  PropertyPaneToggle,
  PropertyPaneSlider,
  PropertyPaneDropdown,
  IWebPartContext
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import { Environment, EnvironmentType	} from '@microsoft/sp-core-library';
import styles from './AngularYammer.module.scss';
import * as strings from 'angularYammerStrings';
import { IAngularYammerWebPartProps } from './IAngularYammerWebPartProps';
import * as angular from 'angular';

export default class AngularYammerWebPart extends BaseClientSideWebPart<IAngularYammerWebPartProps> {

  private $injector: angular.auto.IInjectorService;

  public render(): void {

    if (this.renderedOnce === false) {
      require('./app/home.controller.js');
      this.domElement.innerHTML = `

`;
      this.$injector = angular.bootstrap(this.domElement, ['yammerApp']);
    }

    this.$injector.get('$rootScope').$broadcast('configurationChanged', {
      network : escape(this.properties.network),
      feedType : escape(this.properties.feedType),
      defaultGroupId: this.properties.defaultGroupId,
      showOpenGraphPreview: this.properties.showOpenGraphPreview,
      promptText: escape(this.properties.promptText),
      header: this.properties.header,
      footer: this.properties.footer,
      environment: Environment.type,
      environmentType: EnvironmentType,
      domElement: this.domElement
    });
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('network', {
                  label: strings.NetworkFieldLabel
                }),
                PropertyPaneTextField('feedtype', {
                  label: strings.FeedTypeFieldLabel
                }),
                PropertyPaneTextField('defaultGroupId', {
                  label: strings.DefaultGroupIdFieldLabel
                }),
                PropertyPaneToggle('showOpenGraphPreview', {
                  label: strings.ShowOpenGraphPreviewFieldLabel,
                  onText: 'On',
                  offText: 'Off'
                }),
                PropertyPaneTextField('promptText', {
                  label: strings.PromptTextFieldLabel
                }),
                PropertyPaneToggle('header', {
                  label: strings.HeaderFieldLabel,
                  onText: 'On',
                  offText: 'Off'
                }),
                PropertyPaneToggle('footer', {
                  label: strings.FooterFieldLabel,
                  onText: 'On',
                  offText: 'Off'
                })
              ]
            }
          ]
        }
      ]
    };
  }

  protected get disableReactivePropertyChanges(): boolean {
    return true;
  }
}


text:
import React from 'react';
import Home from './Home';
import fetch from '../../core/fetch';
import Layout from '../../components/Layout';
import Auth from '../../core/Auth';

export default {

  path: '/',

  action() {
    return {
      title: 'Mourakiboun PV editor',
      component: <Layout><Home /></Layout>,
    };
  },

};


text:
using System.ComponentModel;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;

namespace BudgetAnalyser.Engine.Matching
{
    /// <summary>
    ///     A class used to store a criteria value when creating a new <see cref="MatchingRule" />.
    /// </summary>
    /// <typeparam name="T">
    ///     The type used to contain the value to match. Can be a class or a struct. A Null value indicates
    ///     there is no criteria present.
    /// </typeparam>
    public abstract class Criteria<T> : INotifyPropertyChanged
    {
        private bool doNotUseApplicable;
        private T doNotUseValue;

        /// <summary>
        ///     Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        ///     Gets or sets a value indicating whether this <see cref="Criteria{T}" /> will be applied as criteria.
        /// </summary>
        /// <value>
        ///     <c>true</c> if applicable; otherwise, <c>false</c> and will not be used in matching.
        /// </value>
        public bool Applicable
        {
            get { return this.doNotUseApplicable; }
            set
            {
                if (value == this.doNotUseApplicable)
                {
                    return;
                }
                this.doNotUseApplicable = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        ///     Gets or sets the criteria value.
        /// </summary>
        public T Value
        {
            get { return this.doNotUseValue; }
            set
            {
                if (Equals(value, this.doNotUseValue))
                {
                    return;
                }
                this.doNotUseValue = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        ///     Determines whether the value is equal to the <paramref name="operand2" /> but not niether can be blank or null.
        /// </summary>
        public abstract bool IsEqualButNotBlank(T operand2);

        /// <summary>
        ///     Called when a property is changed.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    /// <summary>
    ///     A string criteria value.
    /// </summary>
    /// <seealso cref="string" />
    public class StringCriteria : Criteria<string>
    {
        /// <summary>
        ///     Determines whether the value is equal to the <paramref name="operand2" /> but not niether can be blank or null.
        /// </summary>
        public override bool IsEqualButNotBlank(string operand2)
        {
            if (string.IsNullOrWhiteSpace(Value) || string.IsNullOrWhiteSpace(operand2))
            {
                return false;
            }

            var match = Value == operand2;
            return match;
        }
    }

    /// <summary>
    ///     A decimal criteria value.
    /// </summary>
    /// <seealso cref="decimal" />
    public class DecimalCriteria : Criteria<decimal?>
    {
        /// <summary>
        ///     Determines whether the value is equal to the <paramref name="operand2" /> but not niether can be blank or null.
        /// </summary>
        public override bool IsEqualButNotBlank(decimal? operand2)
        {
            if (Value == default(decimal))
            {
                return false;
            }

            return Value == operand2;
        }
    }
}


text:
package com.github.anno4j.querying;

import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.sparql.algebra.*;
import com.hp.hpl.jena.sparql.algebra.optimize.*;

/**
 *
 */
public class QueryOptimizer {

    private static volatile QueryOptimizer INSTANCE;

    /**
     * private constructor to prevent client from instantiating.
     *
     */
    private QueryOptimizer() {
        //to prevent instantiating by Reflection call
        if(INSTANCE != null)
            throw new IllegalStateException("Already initialized.");
    }

    public static QueryOptimizer getInstance() {
        //local variable increases performance by 25 percent
        //Joshua Bloch "Effective Java, Second Edition", p. 283-284
        QueryOptimizer result = INSTANCE;
        if (result == null) {
            synchronized (QueryOptimizer.class) {
                result = INSTANCE;
                if (result == null) {
                    INSTANCE = result = new QueryOptimizer();
                }
            }
        }
        return result;
    }

    /**
     * Optimizes the join order of the query
     *
     * @param sparql The SPARQL query
     *
     * @return The optimized SPARQL query
     */
    public String optimizeJoinOrder(String sparql) {
        Op op = Algebra.compile(QueryFactory.create(sparql));
        Transform joinReorder = new TransformJoinStrategy();
        op = Transformer.transform(joinReorder, op);

        return OpAsQuery.asQuery(op).serialize();
    }

    /**
     * Optimizes the query in multiple ways:
     *
     *

     *
Redo FILTER (A&&B) as FILTER(A) FILTER(B) (as an expr list)

     *
Optimizes the FILTER disjunctions

     *
Rewrite an algebra expression to put filters as close to their bound variables

     *

     *
     * @param sparql The SPARQL query
     *
     * @return The optimized SPARQL query
     */
    public String optimizeFilters(String sparql) {
        Op op = Algebra.compile(QueryFactory.create(sparql));

        Transform filterConjunction = new TransformFilterConjunction();
        Transform filterDisjunction = new TransformFilterDisjunction();
        Transform filterPlacement = new TransformFilterPlacement();

        op = Transformer.transform(filterConjunction, op);
        op = Transformer.transform(filterDisjunction, op);
        op = Transformer.transform(filterPlacement, op);

        return OpAsQuery.asQuery(op).serialize();
    }

    /**
     * Reformats the SPARQL query for logging purpose
     *
     * @param sparql The generated SPARQL query
     *
     * @return Formatted query
     */
    public String prettyPrint(String sparql) {
        return OpAsQuery.asQuery(Algebra.compile(QueryFactory.create(sparql))).serialize();
    }
}


text:
import React from 'react';
import { View, Text } from 'react-native'

export default ContributorsList = () => <View><Text> Contributors List</Text></View>


text:
def extractPenguTaichou(item):
	"""
	Pengu Taichou
	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol or frag) or 'preview' in item['title'].lower():
		return None
	if item['title'].lower().startswith('sword shisho chapter'):
		return buildReleaseMessageWithType(item, 'I was a Sword when I Reincarnated!', vol, chp, frag=frag, postfix=postfix)
	return False


text:
Frontend API Reference
======================

Javascript/browser client connects to the swindon via websocket. We authorize
websocket by headers (``Cookie``, ``Authorization``, ``request-uri``,
or any other header) and then we keep that authorization data for future
requests via same websocket.

On top of the websockets we implement request-reply pattern from client
to server and multiple patterns from server to client.

Request Format
--------------

.. code-block:: javascript

   [method, request_meta, args_array, kwargs_object]

``method``
   Name of the remote method to call (example: ``"chat.send_message"``).
   Names starting with ``tangle.*`` and ``swindon.*`` are reserved and cannot
   be called from client.

.. _request-meta:

``request_meta``
   A dictionary (technically a Javascript/JSON object) that contains metadata
   of the request. All fields that are passed in this object are returned
   in ``response_meta``.

   Currently there are the following well-known fields:

      ``request_id``
         This field contains request identified. Swindon itself uses the
         field barely for logging purposes. But it's inteded to be used to
         match responses on the frontend. It should be either non-negative
         integer or ascii string up to 36 chars long
         (with valid characters ``a-z``, ``A-Z``, ``0-9``, ``-``, ``_``).
      ``active``
         Time (in seconds) for which session should be considered active.
         This should be positive integer.

``args_array``
   Positional arguments for the remote method. They are passed to the backend
   as is (must be a valid JSON array though).

``kwargs_object``
   Named arguments for the remote method (must be valid JSON object).

.. note:: All four arguments are **required** even if some of them are empty.

Example
~~~~~~~

Request:

.. code-block:: json

   ["chat.send_message",
    {"request_id": 123},
    [{"text": "Arbitrary message"}],
    {"room": "room1"}
    ]

Possible responses:

*Success result:*

.. code-block:: json

   ["result", {"request_id": 123}, {"result": "json", "object": 1}]

*Error results:*

.. code-block:: json

   ["error", {"request_id": 123, "tangle_code": "http_error", "error_code": 400},
    {"result": "json", "object": 1}]

.. code-block:: json

   ["error", {"request_id": 123, "tangle_code": "validation_error"},
    {"result": "json", "object": 1}]

Response Format
---------------

.. code-block:: javascript

   [event_type, response_meta, data]

``event_type``
   Event type (see `Event Types`_)

``response_meta``
   A dictionary (a object in terms of Javascript/JSON) that contains
   auxilliary data about the event.

   For responses this dictionary contains fields from ``request_meta``

``data``
   Event data. Type and format of this value depends on ``event_type``

Event Types
-----------

.. contents::
   :local:

.. _call-result:

Method Call Result (``result``/``error``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:event_type: ``result``

.. code-block:: javascript

   ["result", {"request_id": 123}, json_result_object]

**Error result**

:event_type: ``error``

.. code-block:: javascript

   ["error",
    {"request_id": 123, "error_kind": "http_error", "http_error": 400},
    json_body_object]

   ["error",
    {"request_id": 123, "error_kind": "validation_error"},
    "invalid method"]

In case of error ``response_meta`` always has ``error_kind`` field.
Other fields may contain error details depending on the type of error.

Possible ``error_kind`` values:

   ``http_error``
      HTTP error from backend server. This error contains additional field
      ``http_error`` which contains *HTTP status code*. The ``data`` field
      may contain error data if response has
      ``Content-Type: application/json`` and valid JSON body.

   ``validation_error``
      Error validating request. ``data`` contains addition information.

   ``data_error``
      Error related to decoding response from a backend.
      ``data`` field contains string describing an error.
      Possible causes:

      * wrong (unsupported) ``Content-Type`` header;

      * not a JSON or malformed JSON response;

   ``internal_error``
      Swindon encountered internal error while processing the request.
      ``data`` field contains string describing an error.

.. :: NOTE: These two were never used, thus dropped;
   ``invalid_content_type``
      Wrong (i.e. unsupported) ``Content-Type`` in response from a backend.
   ``forbidden``
      This call is forbidden to call from frontend. This is used when you
      are trying to call ``tangle.*`` or ``swindon.*`` methods. These names
      are reserved for calls initiated by swindon.

.. _hello-message:

User Information (``hello``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   :event_type: ``hello``

   .. code-block:: json

      ["hello", {}, {"username": "John"}]

   Initial event sent just after websocket handshake is complete, which
   in turn means backend has authorized connection.

   Format of the data sent (third item in the tuple above) is defined
   by a backend (i.e. it's JSON data sent from a backend).
   See :ref:`backend-auth` for more info.

.. _fatal_error message:

Fatal Errors (``fatal_error``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Fatal errors are very similar to method call errors, but they close connection
after being received. Usually, fatal error is encountered when connection
is first established (i.e. instead of ``hello``), but may also appear later.

Many fatal error are also duplicated by :ref:`websocket shutdown codes`, but
some browsers do not expose them to the application.

Example::

   ["fatal_error",
    {"error_kind": "http_error", "http_error": 400},
    {"data": "sent", "by": ["application", "handler"]}]

.. _front-message:

Message (``message``)
~~~~~~~~~~~~~~~~~~~~~

   :event_type: ``message``

   .. code-block:: json

      ["message",
       {"topic": "test-chat.room1"},
       {"id": 1,
        "message": "...",
        "author": ".."
        }]

   This message type is used to propagate published messages to frontend.
   See :ref:`Pub/Sub subscriptions <topic-publish>` for more info.

Lattice Update (``lattice``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

   More about lattice updates in :ref:`lattice-definition`

   :event_type: ``lattice``

   .. code-block:: json

      ["lattice",
       {"namespace": "test-chat.rooms"},
       {
         "room1": {
           "last_message_count": 2,
           "last_seen_count": 3
         },
         "room2": {
           "last_message_count": 123
         },
      }]


text: Know your Professor!


text:
package manager

import (
	"fmt"
	"net/url"
	"strings"

	"k8s.io/apimachinery/pkg/util/validation"

	v3 "github.com/rancher/rancher/pkg/generated/norman/management.cattle.io/v3"
	"github.com/rancher/rancher/pkg/helm"
)

const invalidURLErrMsg string = "a valid url must consist of an http, https, or git scheme"

type ChartsWithErrors struct {
	Template *helm.ChartVersion
	error    InvalidChartError
}

type InvalidChartError struct {
	Err          string
	TemplateName string
}

func (e *InvalidChartError) Error() string {
	return fmt.Sprintf("failed %v %s", e.TemplateName, e.Err)
}

// Go through each catalog entry and check for errors in values used for template name and labels
// due to restrictions for kubernetes objects. Do not create templates with errored charts.
func (m *Manager) preprocessCatalog(catalog *v3.Catalog, catalogEntries map[string]helm.ChartVersions) ([]ChartsWithErrors, map[string]helm.ChartVersions) {
	var invalidEntries []ChartsWithErrors
	for chart, metadata := range catalogEntries {
		for _, version := range metadata {
			var versionErrors []string
			// get a chart name that matches helm general conventions
			templateName := getValidTemplateName(catalog.Name, chart)
			// check that template name could be used as a kubernetes sub domain
			errorString := validation.IsDNS1123Subdomain(templateName)
			if len(errorString) > 0 {
				versionErrors = append(versionErrors, fmt.Sprintf("template name %s: [%s]", templateName, strings.Join(errorString, ";")))
			}
			// check that template name can be used as a label
			errorString = validation.IsValidLabelValue(templateName)
			if len(errorString) > 0 {
				versionErrors = append(versionErrors, fmt.Sprintf("template name %s: [%s]", templateName, strings.Join(errorString, ";")))
			}
			templateVersionName := getValidTemplateNameWithVersion(templateName, version.Version)
			// validate template version name can be used as a kubernetes sub domain
			errorString = validation.IsDNS1123Subdomain(templateVersionName)
			if len(errorString) > 0 {
				versionErrors = append(versionErrors, fmt.Sprintf("template version name %s: [%s]", templateVersionName, strings.Join(errorString, ";")))
			}
			if version.URLs != nil {
				for _, url := range version.URLs {
					// check to see if url is http, https or git scheme
					if isInvalidVersionURL(url) {
						versionErrors = append(versionErrors, fmt.Sprintf("url %s is invalid. %s", url, invalidURLErrMsg))
					}
				}
			}
			// a chart can have multiple version, so errors are collected per version
			// this allows valid chart versions to be processed for use
			if len(versionErrors) > 0 {
				invalidEntries = append(invalidEntries, ChartsWithErrors{
					Template: version,
					error: InvalidChartError{
						Err:          strings.Join(versionErrors, ";"),
						TemplateName: version.Name,
					},
				})
			}
		}
	}
	// remove invalid entry from catalog entries so that they are not processed into templates
	for _, version := range invalidEntries {
		delete(catalogEntries, version.Template.Name)
	}
	return invalidEntries, catalogEntries
}

func isInvalidVersionURL(versionURL string) bool {
	url, err := url.Parse(versionURL)
	if err != nil {
		return false
	}
	if url.Scheme == "file" || url.Scheme == "local" {
		return true
	}
	return false
}


text:
/**
 */
package CIM.IEC61970.Informative.MarketOperations.impl;

import CIM.IEC61970.Core.impl.CurveImpl;

import CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage;
import CIM.IEC61970.Informative.MarketOperations.ReserveReq;
import CIM.IEC61970.Informative.MarketOperations.SensitivityPriceCurve;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Sensitivity Price Curve'.
 *
 *

 * The following features are implemented:
 *

 *

 *
{@link CIM.IEC61970.Informative.MarketOperations.impl.SensitivityPriceCurveImpl#getReserveReq Reserve Req}

 *

 *
 * @generated
 */
public class SensitivityPriceCurveImpl extends CurveImpl implements SensitivityPriceCurve {
	/**
	 * The cached value of the '{@link #getReserveReq() Reserve Req}' reference.
	 *
	 *
	 * @see #getReserveReq()
	 * @generated
	 * @ordered
	 */
	protected ReserveReq reserveReq;

	/**
	 *
	 *
	 * @generated
	 */
	protected SensitivityPriceCurveImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return MarketOperationsPackage.Literals.SENSITIVITY_PRICE_CURVE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public ReserveReq getReserveReq() {
		if (reserveReq != null && reserveReq.eIsProxy()) {
			InternalEObject oldReserveReq = (InternalEObject)reserveReq;
			reserveReq = (ReserveReq)eResolveProxy(oldReserveReq);
			if (reserveReq != oldReserveReq) {
				if (eNotificationRequired())
					eNotify(new ENotificationImpl(this, Notification.RESOLVE, MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ, oldReserveReq, reserveReq));
			}
		}
		return reserveReq;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public ReserveReq basicGetReserveReq() {
		return reserveReq;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetReserveReq(ReserveReq newReserveReq, NotificationChain msgs) {
		ReserveReq oldReserveReq = reserveReq;
		reserveReq = newReserveReq;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ, oldReserveReq, newReserveReq);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setReserveReq(ReserveReq newReserveReq) {
		if (newReserveReq != reserveReq) {
			NotificationChain msgs = null;
			if (reserveReq != null)
				msgs = ((InternalEObject)reserveReq).eInverseRemove(this, MarketOperationsPackage.RESERVE_REQ__SENSITIVITY_PRICE_CURVE, ReserveReq.class, msgs);
			if (newReserveReq != null)
				msgs = ((InternalEObject)newReserveReq).eInverseAdd(this, MarketOperationsPackage.RESERVE_REQ__SENSITIVITY_PRICE_CURVE, ReserveReq.class, msgs);
			msgs = basicSetReserveReq(newReserveReq, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ, newReserveReq, newReserveReq));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ:
				if (reserveReq != null)
					msgs = ((InternalEObject)reserveReq).eInverseRemove(this, MarketOperationsPackage.RESERVE_REQ__SENSITIVITY_PRICE_CURVE, ReserveReq.class, msgs);
				return basicSetReserveReq((ReserveReq)otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ:
				return basicSetReserveReq(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ:
				if (resolve) return getReserveReq();
				return basicGetReserveReq();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ:
				setReserveReq((ReserveReq)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ:
				setReserveReq((ReserveReq)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case MarketOperationsPackage.SENSITIVITY_PRICE_CURVE__RESERVE_REQ:
				return reserveReq != null;
		}
		return super.eIsSet(featureID);
	}

} //SensitivityPriceCurveImpl


text:
@javax.xml.bind.annotation.XmlSchema(namespace = "http://welcomesoap.rdokollari.me/")
package me.rdokollari.welcomesoap;


text:
#ifndef itkBlockMatchingMultiResolutionIterationCommand_h
#define itkBlockMatchingMultiResolutionIterationCommand_h

#include "itkCommand.h"

#include "itkBlockMatchingMultiResolutionImageRegistrationMethod.h"

namespace itk
{
namespace BlockMatching
{

/**
 * \class MultiResolutionIterationCommand
 *
 * \brief This is a base class for classes that want to observe/adjust a
 * BlockMatching::MultiResolutionImageRegistrationMethod at every iteration.
 *
 * \ingroup Ultrasound
 * */
template <typename TMultiResolutionMethod>
class MultiResolutionIterationCommand : public Command
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(MultiResolutionIterationCommand);

  using Self = MultiResolutionIterationCommand;
  using Superclass = Command;
  using Pointer = SmartPointer<Self>;

  void
  Execute(itk::Object * caller, const itk::EventObject & event) override
  {
    Execute((const itk::Object *)caller, event);
  }

  void
  Execute(const itk::Object * object, const itk::EventObject & event) override;

  using MultiResolutionMethodType = TMultiResolutionMethod;

  void
  SetMultiResolutionMethod(MultiResolutionMethodType * method)
  {
    m_MultiResolutionMethod = method;
  }

  using FixedImagePyramidType = typename MultiResolutionMethodType::FixedImagePyramidType;
  using FixedImagePyramidPointer = typename FixedImagePyramidType::ConstPointer;
  using MovingImagePyramidType = typename MultiResolutionMethodType::MovingImagePyramidType;
  using MovingImagePyramidPointer = typename MovingImagePyramidType::ConstPointer;

  using BlockRadiusCalculatorType = typename MultiResolutionMethodType::BlockRadiusCalculatorType;
  using BlockRadiusCalculatorPointer = typename BlockRadiusCalculatorType::ConstPointer;

  using SearchRegionImageSourceType = typename MultiResolutionMethodType::SearchRegionImageSourceType;
  using SearchRegionImageSourcePointer = typename SearchRegionImageSourceType::ConstPointer;

protected:
  MultiResolutionIterationCommand() { m_MultiResolutionMethod = nullptr; }
  virtual ~MultiResolutionIterationCommand(){};

  typename MultiResolutionMethodType::Pointer m_MultiResolutionMethod;

  FixedImagePyramidPointer  m_FixedImagePyramid;
  MovingImagePyramidPointer m_MovingImagePyramid;

  BlockRadiusCalculatorPointer m_BlockRadiusCalculator;

  SearchRegionImageSourcePointer m_SearchRegionImageSource;

private:
};

} // end namespace BlockMatching
} // end namespace itk

#include "itkBlockMatchingMultiResolutionIterationCommand.hxx"

#endif


text:
package com.pard.common.utils.file.callback;

import java.io.File;

/**
 * Created by wawe on 17/5/31.
 */
public interface ScanCallBack extends CanExitCallBack {

    void accept(int deep, File file);

    default void error(int deep, File file, Throwable e) {
        e.printStackTrace();
    }

}


text:
package Modules;

/**
 * Created by Mai Thanh Hiep on 4/3/2016.
 */
public class Duration {
    public String text;
    public int value;

    public Duration(String text, int value) {
        this.text = text;
        this.value = value;
    }
}


text:
import unittest

import six

from modularodm import fields
from modularodm.storedobject import ContextLogger
from modularodm import StoredObject
from modularodm.exceptions import ModularOdmException

from tests.base import (
    ModularOdmTestCase
)

class OneToManyFieldTestCase(ModularOdmTestCase):

    def define_objects(self):

        class Foo(StoredObject):
            _meta = {
                'optimistic': True
            }
            _id = fields.StringField()
            my_bar = fields.ForeignField('Bar', backref='my_foos')
            my_other_bar = fields.ForeignField('Bar', backref='my_foos')

        class Bar(StoredObject):
            _meta = {'optimistic': True}
            _id = fields.StringField()

        return Foo, Bar

    def set_up_objects(self):

        self.bar = self.Bar()
        self.bar.save()

        self.foos = []
        for i in range(5):
            foo = self.Foo()
            if i > 0:
                foo.my_bar = self.bar
            else:
                foo.my_other_bar = self.bar
            foo.save()
            self.foos.append(foo)

    def test_dunder_br_returns_foreignlist(self):
        self.assertIs(
            type(self.bar.foo__my_foos),
            fields.ForeignList
        )

    def test_dunder_br_returns_correct(self):
        self.assertEqual(
            len(self.bar.foo__my_foos),
            5
        )

    @unittest.skip('Behavior not defined.')
    def test_dunder_br_unknown_field(self):
        with self.assertRaises(KeyError):
            self.bar.foo__not_a_real_key

    def test_dunder_br_unknown_node(self):
        with self.assertRaises(ModularOdmException):
            self.bar.not_a_real_node__foo

    def test_dunder_br_parent_field_correct(self):
        self.assertEqual(
            len(self.bar.foo__my_foos__my_other_bar),
            1
        )

    def test_dunder_br_laziness(self):
        StoredObject._clear_caches()

        with ContextLogger() as c:
            # get the Bar object
            bar = self.Bar.find_one()
            # access the ForeignList
            bar.foo__my_foos

            # Two calls so far - .find_one() and .find()
            self.assertNotIn(
                'foo',
                [k[0] for k, v in six.iteritems(c.report())],
            )

            # access a member of the ForeignList, forcing that member to load
            bar.foo__my_foos[0]

            # now there should be a call to Foo.get()
            self.assertEqual(
                c.report()[('foo', 'get')][0],
                1
            )

class OneToManyAbstractFieldTestCase(ModularOdmTestCase):

    def define_objects(self):

        class Foo(StoredObject):
            _meta = {
                'optimistic': True
            }
            _id = fields.StringField()
            my_abstract = fields.AbstractForeignField(backref='my_foos')
            my_other_abstract = fields.AbstractForeignField(backref='my_foos')

        class Bar(StoredObject):
            _meta = {'optimistic': True}
            _id = fields.StringField()

        class Bob(StoredObject):
            _meta = {'optimistic': True}
            _id = fields.StringField()

        return Foo, Bar, Bob

    def set_up_objects(self):

        self.bar = self.Bar()
        self.bar.save()

        self.bob = self.Bob()
        self.bob.save()

        self.foos = []
        for i in range(5):
            foo = self.Foo()
            if i > 0:
                foo.my_abstract = self.bar
                foo.my_other_abstract = self.bob
            else:
                foo.my_abstract = self.bob
                foo.my_other_abstract = self.bar
            foo.save()
            self.foos.append(foo)

    def test_dunder_br_returns_foreignlist(self):
        self.assertIs(
            type(self.bar.foo__my_foos),
            fields.ForeignList
        )

    def test_dunder_br_returns_correct(self):
        self.assertEqual(
            len(self.bar.foo__my_foos),
            5
        )

    @unittest.skip('Behavior not defined.')
    def test_dunder_br_unknown_field(self):
        with self.assertRaises(KeyError):
            self.bar.foo__not_a_real_key

    def test_dunder_br_unknown_node(self):
        with self.assertRaises(ModularOdmException):
            self.bar.not_a_real_node__foo

    def test_dunder_br_parent_field_correct(self):
        self.assertEqual(
            len(self.bar.foo__my_foos__my_other_abstract),
            1
        )

    def test_dunder_br_laziness(self):
        StoredObject._clear_caches()

        with ContextLogger() as c:
            # get the Bar object
            bar = self.Bar.find_one()
            # access the ForeignList
            bar.foo__my_foos

            # Two calls so far - .find_one() and .find()
            self.assertNotIn(
                'foo',
                [k[0] for k, v in six.iteritems(c.report())],
            )

            # access a member of the ForeignList, forcing that member to load
            bar.foo__my_foos[0]

            # now there should be a call to Foo.get()
            self.assertEqual(
                c.report()[('foo', 'get')][0],
                1
            )


text:
FROM ubuntu:14.04
MAINTAINER xymostech <xymostech@gmail.com>

# Install things
RUN apt-get -qq update
RUN apt-get -qqy install git dvipng default-jre default-jdk texlive wget fontforge mftrace fonttools optipng advancecomp man-db build-essential unzip zlib1g-dev python-fontforge ruby || true
RUN gem install ttfunk --version 1.1.1

# Download yuicompressor
RUN mkdir /usr/share/yui-compressor/
RUN wget "https://github.com/yui/yuicompressor/releases/download/v2.4.8/yuicompressor-2.4.8.jar" -O /usr/share/yui-compressor/yui-compressor.jar

# Download batik-ttf2svg.jar
RUN wget "http://supergsego.com/apache/xmlgraphics/batik/batik-1.7.zip"
RUN unzip -qq batik-1.7.zip
RUN mv batik-1.7/batik-ttf2svg.jar /usr/share/java/

# Download and compile ttf2eof (note we add a patch to make it compile)
RUN wget "https://ttf2eot.googlecode.com/files/ttf2eot-0.0.2-2.tar.gz"
RUN tar -xzf ttf2eot-0.0.2-2.tar.gz
RUN sed -i "1s/^/#include <cstddef>/" ttf2eot-0.0.2-2/OpenTypeUtilities.h
RUN make -C ttf2eot-0.0.2-2/
RUN mv ttf2eot-0.0.2-2/ttf2eot /usr/bin/

# Download and compile sfnt2woff
RUN wget "http://people.mozilla.org/~jkew/woff/woff-code-latest.zip"
RUN unzip -d sfnt2woff woff-code-latest.zip
RUN make -C sfnt2woff
RUN mv sfnt2woff/sfnt2woff /usr/bin/

# Download and setup MathJax-dev
RUN git clone "https://github.com/khan/MathJax-dev.git"
RUN cp MathJax-dev/default.cfg MathJax-dev/custom.cfg
RUN make -C MathJax-dev custom.cfg.pl


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.HPack;
using System.Net.Http.Headers;
using System.Text;
using Xunit;

namespace System.Net.Http.Unit.Tests.HPack
{
    public class HPackRoundtripTests
    {

        public static IEnumerable<object[]> TestHeaders()
        {
            yield return new object[] { new HttpRequestHeaders() { { "header", "value" } } };
            yield return new object[] { new HttpRequestHeaders() { { "header", new[] { "value1", "value2" } } } };
            yield return new object[] { new HttpRequestHeaders()
            {
                { "header-0", new[] { "value1", "value2" } },
                { "header-0", "value3" },
                { "header-1", "value1" },
                { "header-2", new[] { "value1", "value2" } },
            } };
        }

        [Theory, MemberData(nameof(TestHeaders))]
        public void HPack_HeaderEncodeDecodeRoundtrip_ShouldMatchOriginalInput(HttpHeaders headers)
        {
            Memory<byte> encoding = HPackEncode(headers);
            HttpHeaders decodedHeaders = HPackDecode(encoding);

            // Assert: decoded headers are structurally equal to original headers
            Assert.Equal(headers.Count(), decodedHeaders.Count());
            Assert.All(headers.Zip(decodedHeaders), pair =>
            {
                Assert.Equal(pair.First.Key, pair.Second.Key);
                Assert.Equal(pair.First.Value, pair.Second.Value);
            });
        }

        // adapted from Header serialization code in Http2Connection.cs
        private static Memory<byte> HPackEncode(HttpHeaders headers)
        {
            var buffer = new ArrayBuffer(4);
            FillAvailableSpaceWithOnes(buffer);

            foreach (KeyValuePair<HeaderDescriptor, string[]> header in headers.GetHeaderDescriptorsAndValues())
            {
                KnownHeader knownHeader = header.Key.KnownHeader;
                if (knownHeader != null)
                {
                    // For all other known headers, send them via their pre-encoded name and the associated value.
                    WriteBytes(knownHeader.Http2EncodedName);
                    string separator = null;
                    if (header.Value.Length > 1)
                    {
                        HttpHeaderParser parser = header.Key.Parser;
                        if (parser != null && parser.SupportsMultipleValues)
                        {
                            separator = parser.Separator;
                        }
                        else
                        {
                            separator = HttpHeaderParser.DefaultSeparator;
                        }
                    }

                    WriteLiteralHeaderValues(header.Value, separator);
                }
                else
                {
                    // The header is not known: fall back to just encoding the header name and value(s).
                    WriteLiteralHeader(header.Key.Name, header.Value);
                }
            }

            return buffer.ActiveMemory;

            void WriteBytes(ReadOnlySpan<byte> bytes)
            {
                if (bytes.Length > buffer.AvailableLength)
                {
                    buffer.EnsureAvailableSpace(bytes.Length);
                    FillAvailableSpaceWithOnes(buffer);
                }

                bytes.CopyTo(buffer.AvailableSpan);
                buffer.Commit(bytes.Length);
            }

            void WriteLiteralHeaderValues(string[] values, string separator)
            {
                int bytesWritten;
                while (!HPackEncoder.EncodeStringLiterals(values, separator, buffer.AvailableSpan, out bytesWritten))
                {
                    buffer.EnsureAvailableSpace(buffer.AvailableLength + 1);
                    FillAvailableSpaceWithOnes(buffer);
                }

                buffer.Commit(bytesWritten);
            }

            void WriteLiteralHeader(string name, string[] values)
            {
                int bytesWritten;
                while (!HPackEncoder.EncodeLiteralHeaderFieldWithoutIndexingNewName(name, values, HttpHeaderParser.DefaultSeparator, buffer.AvailableSpan, out bytesWritten))
                {
                    buffer.EnsureAvailableSpace(buffer.AvailableLength + 1);
                    FillAvailableSpaceWithOnes(buffer);
                }

                buffer.Commit(bytesWritten);
            }

            // force issues related to buffer not being zeroed out
            void FillAvailableSpaceWithOnes(ArrayBuffer buffer) => buffer.AvailableSpan.Fill(0xff);
        }

        // adapted from header deserialization code in Http2Connection.cs
        private static HttpHeaders HPackDecode(Memory<byte> memory)
        {
            var header = new HttpRequestHeaders();
            var hpackDecoder = new HPackDecoder(maxDynamicTableSize: 0, maxResponseHeadersLength: HttpHandlerDefaults.DefaultMaxResponseHeadersLength * 1024);

            hpackDecoder.Decode(memory.Span, true, ((_, name, value) => HeaderHandler(name, value)), null);

            return header;

            void HeaderHandler(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
            {
                if (!HeaderDescriptor.TryGet(name, out HeaderDescriptor descriptor))
                {
                    throw new HttpRequestException(SR.Format(SR.net_http_invalid_response_header_name, Encoding.ASCII.GetString(name)));
                }

                string headerValue = descriptor.GetHeaderValue(value);

                header.TryAddWithoutValidation(descriptor, headerValue.Split(',').Select(x => x.Trim()));
            }
        }
    }
}


text:
package controllers.traits.auth

import config.{Authorised, BackController, NotAuthorised}
import models.auth.Login
import play.api.mvc.Action
import services.LoginService

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

trait LoginCtrl extends BackController {

  val loginService : LoginService

  def userLogin : Action[String] = Action.async(parse.text) {
    implicit request =>
      authOpenAction {
        case Authorised =>
          decryptRequest[Login] {
            loginData =>
              loginService.getSingleUser(loginData) map {
                case unauthorised @ "Unauthorised" => Unauthorized(unauthorised)
                case payload => Ok(payload)
              }
          }
        case NotAuthorised => Future.successful(Forbidden)
      }
  }
}


text:
package com.intel.analytics.bigdl.parameters

import java.nio.ByteBuffer

import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.utils.Engine

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.reflect._

class FP16CompressedTensor[T: ClassTag](buffer: Array[Byte], bufferOffset: Int, bufferLength: Int)
  extends CompressedTensor[T] {

  def this(tensor: Tensor[T]) {
    this(new Array[Byte](tensor.nElement() * 2), 0, tensor.nElement() * 2)
    compress(tensor)
  }

  def this(length: Int) = this(new Array[Byte](length * 2), 0, length * 2)

  def this(bytes: ByteBuffer) = this(bytes.array(), bytes.position(), bytes.remaining())

  require(bufferLength % 2 == 0 && bufferOffset + bufferLength <= buffer.length)

  override def compress(offset: Int, src: Tensor[T], srcOffset: Int, length: Int)
  : this.type = {
    require(src.isContiguous() && offset >= 0 && srcOffset >= 0 &&
      srcOffset + length <= src.nElement()
      && offset + length <= bufferLength / 2)
    val tOffset = src.storageOffset() - 1 + srcOffset
    if (classTag[T] == classTag[Double]) {
      FP16CompressedTensor.toFP16(src.storage().array().asInstanceOf[Array[Double]], tOffset,
        buffer, bufferOffset + offset, length)
    } else if (classTag[T] == classTag[Float]) {
      FP16CompressedTensor.toFP16(src.storage().array().asInstanceOf[Array[Float]], tOffset,
        buffer, bufferOffset + offset, length)
    } else {
      throw new IllegalArgumentException
    }

    this
  }

  override def compress(src: Tensor[T]): this.type = compress(0, src, 0, src.nElement())

  override def bytes(): ByteBuffer = bytes(0, bufferLength / 2)

  override def bytes(offset: Int, length: Int): ByteBuffer = {
    require(offset >= 0 && length > 0 && (offset + length) * 2 <= bufferLength,
      s"$offset $length $bufferLength")
    if (classTag[T] == classTag[Double]) {
      ByteBuffer.wrap(buffer, offset * 2 + bufferOffset, length * 2)
    } else if (classTag[T] == classTag[Float]) {
      ByteBuffer.wrap(buffer, offset * 2 + bufferOffset, length * 2)
    } else {
      throw new IllegalArgumentException
    }
  }

  override def deCompress(tensor: Tensor[T]): Unit = deCompress(0, tensor, 0, bufferLength / 2)

  override def deCompress(srcOffset: Int, tensor: Tensor[T],
                          tgtOffset: Int, length: Int): Unit = {
    require(srcOffset >= 0 && length > 0 && (srcOffset + length) * 2 <= bufferLength &&
      tgtOffset >= 0 && tgtOffset + length <= tensor.nElement())
    require(tensor.isContiguous())
    if (classTag[T] == classTag[Double]) {
      val tdata = tensor.storage().array().asInstanceOf[Array[Double]]
      val toffset = tensor.storageOffset() - 1 + tgtOffset
      FP16CompressedTensor.fromFP16(buffer, srcOffset * 2 + bufferOffset,
        length * 2, tdata, toffset)
    } else if (classTag[T] == classTag[Float]) {
      val tdata = tensor.storage().array().asInstanceOf[Array[Float]]
      val toffset = tensor.storageOffset() - 1 + tgtOffset
      FP16CompressedTensor.fromFP16(buffer, srcOffset * 2 + bufferOffset,
        length * 2, tdata, toffset)
    } else {
      throw new IllegalArgumentException
    }
  }

  override def add(data: ByteBuffer): this.type = add(data, 0, bufferLength / 2)

  override def add(data: ByteBuffer, offset: Int, length: Int): this.type = {
    require(offset >= 0 && length > 0 && (offset + length) * 2 <= bufferLength)
    require(length * 2 == data.remaining())
    FP16CompressedTensor.add(buffer, offset * 2 + bufferOffset,
      data.array(), data.position(), data.remaining())
    this
  }

  override def parAdd(data: ByteBuffer): this.type = add(data, 0, bufferLength / 2)

  override def parAdd(data: ByteBuffer, offset: Int, length: Int): this.type = {
    require(offset >= 0 && length > 0 && (offset + length) * 2 <= bufferLength)
    require(length * 2 == data.remaining())
    FP16CompressedTensor.parAdd(buffer, offset * 2 + bufferOffset, data.array(),
      data.position(), data.remaining())
    this
  }
}

object FP16CompressedTensor {
  private def parAdd(l: Array[Byte], lOffset: Int, r: Array[Byte],
    rOffset: Int, length: Int): Array[Byte] = {
    val start = System.nanoTime()
    require(length % 2 == 0)
    require(lOffset + length <= l.length)
    require(rOffset + length <= r.length)

    val elementSize = length / 2
    val taskSize = elementSize / Engine.coreNumber()
    val extraSize = elementSize % Engine.coreNumber()
    val availableTask = if (taskSize == 0) extraSize else Engine.coreNumber()
    Engine.default.invokeAndWait(
      (0 until availableTask).map(tid => () => {
        val start = tid * taskSize * 2 + math.min(extraSize, tid) * 2
        val end = (tid + 1) * taskSize * 2 + math.min(extraSize, tid + 1) * 2
        var i = start
        while (i < end) {
          val sum = toFloat(l(i + lOffset), l(i + lOffset + 1)) +
            toFloat(r(i + rOffset), r(i + rOffset + 1))
          val bytes = truncate(sum)
          l(i + lOffset) = (bytes >>> 24 & 0xff).toByte
          l(i + lOffset + 1) = (bytes >>> 16 & 0xff).toByte
          i += 2
        }
      })
    )

    l
  }

  private def add(l: Array[Byte], lOffset: Int, r: Array[Byte],
    rOffset: Int, length: Int): Array[Byte] = {
    val start = System.nanoTime()
    require(length % 2 == 0)
    require(lOffset + length <= l.length)
    require(rOffset + length <= r.length)

    var i = 0
    while (i < length) {
      val sum = toFloat(l(i + lOffset), l(i + lOffset + 1)) +
        toFloat(r(i + rOffset), r(i + rOffset + 1))
      val bytes = truncate(sum)
      l(i + lOffset) = (bytes >>> 24 & 0xff).toByte
      l(i + lOffset + 1) = (bytes >>> 16 & 0xff).toByte

      i += 2
    }

    l
  }

  private[parameters] def toFP16(src: Array[Float], srcOffset: Int, tgt: Array[Byte],
                                 tgtOffset: Int, length: Int): Array[Byte] = {
    require(srcOffset + length <= src.length)
    require(tgtOffset + length * 2 <= tgt.length)

    val taskSize = length / Engine.coreNumber()
    val extraSize = length % Engine.coreNumber()
    val availableTask = if (taskSize == 0) extraSize else Engine.coreNumber()
    Engine.default.invokeAndWait(
      (0 until availableTask).map(tid => () => {
        val start = tid * taskSize + math.min(extraSize, tid)
        val end = (tid + 1) * taskSize + math.min(extraSize, tid + 1)
        var i = start
        while (i < end) {
          val bytes = truncate(src(i + srcOffset))
          tgt(tgtOffset + i * 2) = (bytes >>> 24 & 0xff).toByte
          tgt(tgtOffset + i * 2 + 1) = (bytes >>> 16 & 0xff).toByte
          i += 1
        }
      })
    )

    tgt
  }

  private[parameters] def toFP16(src: Array[Double], srcOffset: Int, tgt: Array[Byte],
                                 tgtOffset: Int, length: Int): Array[Byte] = {
    require(srcOffset + length <= src.length)
    require(tgtOffset + length * 2 <= tgt.length)

    val taskSize = length / Engine.coreNumber()
    val extraSize = length % Engine.coreNumber()
    val availableTask = if (taskSize == 0) extraSize else Engine.coreNumber()
    Engine.default.invokeAndWait(
      (0 until availableTask).map(tid => () => {
        val start = tid * taskSize + math.min(extraSize, tid)
        val end = (tid + 1) * taskSize + math.min(extraSize, tid + 1)
        var i = start
        while (i < end) {
          val bytes = truncate(src(i + srcOffset).toFloat)
          tgt(tgtOffset + i * 2) = (bytes >>> 24 & 0xff).toByte
          tgt(tgtOffset + i * 2 + 1) = (bytes >>> 16 & 0xff).toByte
          i += 1
        }
      })
    )

    tgt
  }

  private[parameters] def fromFP16(fp16: Array[Byte], fp16Offset: Int, fp16Length: Int,
                                   target: Array[Float], targetOffset: Int): Unit = {
    require(fp16Length % 2 == 0)
    require(fp16Length + fp16Offset <= fp16.length)
    require(fp16Length / 2 + targetOffset <= target.length)

    val targetLength = fp16Length / 2
    val taskSize = targetLength / Engine.coreNumber()
    val extraSize = targetLength % Engine.coreNumber()
    val availableTask = if (taskSize == 0) extraSize else Engine.coreNumber()
    Engine.default.invokeAndWait(
      (0 until availableTask).map(tid => () => {
        val start = tid * taskSize * 2 + math.min(extraSize, tid) * 2
        val end = (tid + 1) * taskSize * 2 + math.min(extraSize, tid + 1) * 2
        var i = start
        while (i < end && i < fp16Length + fp16Offset) {
          target(i / 2 + targetOffset) = toFloat(fp16(i + fp16Offset), fp16(i + 1 + fp16Offset))
          i += 2
        }
      })
    )
  }

  private[parameters] def fromFP16(fp16: Array[Byte], fp16Offset: Int, fp16Length: Int,
                                   target: Array[Double], targetOffset: Int): Unit = {
    require(fp16Length % 2 == 0)
    require(fp16Length + fp16Offset <= fp16.length)
    require(fp16Length / 2 + targetOffset <= target.length)

    val targetLength = fp16Length / 2
    val taskSize = targetLength / Engine.coreNumber()
    val extraSize = targetLength % Engine.coreNumber()
    val availableTask = if (taskSize == 0) extraSize else Engine.coreNumber()
    Engine.default.invokeAndWait(
      (0 until availableTask).map(tid => () => {
        val start = tid * taskSize * 2 + math.min(extraSize, tid) * 2
        val end = (tid + 1) * taskSize * 2 + math.min(extraSize, tid + 1) * 2
        var i = start
        while (i < end && i < fp16Length + fp16Offset) {
          target(i / 2 + targetOffset) = toFloat(fp16(i + fp16Offset), fp16(i + 1 + fp16Offset))
          i += 2
        }
      })
    )
  }

  @inline
  private def truncate(value: Float): Int = {
    java.lang.Float.floatToRawIntBits(value) & 0xffff0000
  }

  @inline
  private def toFloat(byte1: Byte, byte2: Byte): Float = {
    java.lang.Float.intBitsToFloat(byte1 << 24 | byte2 << 16 & 0x00ff0000)
  }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.uiDesigner.binding;

import com.intellij.CommonBundle;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

/**
 * @author Eugene Zhuravlev
 */
public class ChangeBoundFieldTypeFix implements IntentionAction {
  private final PsiField myField;
  private final PsiType myTypeToSet;

  public ChangeBoundFieldTypeFix(PsiField field, PsiType typeToSet) {
    myField = field;
    myTypeToSet = typeToSet;
  }

  @Override
  @NotNull
  public String getText() {
    return QuickFixBundle.message("uidesigner.change.bound.field.type");
  }

  @Override
  @NotNull
  public String getFamilyName() {
    return getText();
  }

  @Override
  public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    return true;
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
    CommandProcessor.getInstance().executeCommand(myField.getProject(), () -> {
      try {
        final PsiManager manager = myField.getManager();
        myField.getTypeElement().replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createTypeElement(myTypeToSet));
      }
      catch (final IncorrectOperationException e) {
        ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(myField.getProject(),
                                                                                QuickFixBundle.message("cannot.change.field.exception", myField.getName(), e.getLocalizedMessage()),
                                                                                CommonBundle.getErrorTitle()));
      }
    }, getText(), null);
  }

  @Override
  public boolean startInWriteAction() {
    return true;
  }
}


text:
package kubernetes

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strings"

	"k8s.io/utils/pointer"

	v1 "k8s.io/api/core/v1"
	k8serrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/sigstore/cosign/pkg/cosign"
)

const (
	KeyReference = "k8s://"
)

func GetKeyPairSecret(ctx context.Context, k8sRef string) (*v1.Secret, error) {
	namespace, name, err := parseRef(k8sRef)
	if err != nil {
		return nil, err
	}

	client, err := client()
	if err != nil {
		return nil, fmt.Errorf("new for config: %w", err)
	}

	var s *v1.Secret
	if s, err = client.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}); err != nil {
		return nil, fmt.Errorf("checking if secret exists: %w", err)
	}

	return s, nil
}

func KeyPairSecret(ctx context.Context, k8sRef string, pf cosign.PassFunc) error {
	namespace, name, err := parseRef(k8sRef)
	if err != nil {
		return err
	}
	// now, generate the key in memory
	keys, err := cosign.GenerateKeyPair(pf)
	if err != nil {
		return fmt.Errorf("generating key pair: %w", err)
	}

	// create the k8s client
	client, err := client()
	if err != nil {
		return fmt.Errorf("new for config: %w", err)
	}
	immutable, err := checkImmutableSecretSupported(client)
	if err != nil {
		return fmt.Errorf("check immutable: %w", err)
	}
	var s *v1.Secret
	if s, err = client.CoreV1().Secrets(namespace).Get(ctx, name, metav1.GetOptions{}); err != nil {
		if k8serrors.IsNotFound(err) {
			s, err = client.CoreV1().Secrets(namespace).Create(ctx, secret(keys, namespace, name, nil, immutable), metav1.CreateOptions{})
			if err != nil {
				return fmt.Errorf("creating secret %s in ns %s: %w", name, namespace, err)
			}
		} else {
			return fmt.Errorf("checking if secret exists: %w", err)
		}
	} else { // Update the existing secret
		s, err = client.CoreV1().Secrets(namespace).Update(ctx, secret(keys, namespace, name, s.Data, immutable), metav1.UpdateOptions{})
		if err != nil {
			return fmt.Errorf("updating secret %s in ns %s: %w", name, namespace, err)
		}
	}

	fmt.Fprintf(os.Stderr, "Successfully created secret %s in namespace %s\n", s.Name, s.Namespace)
	if err := os.WriteFile("cosign.pub", keys.PublicBytes, 0600); err != nil {
		return err
	}
	fmt.Fprintln(os.Stderr, "Public key written to cosign.pub")
	return nil
}

// creates a secret with the following data:
// * cosign.key
// * cosign.pub
// * cosign.password
func secret(keys *cosign.KeysBytes, namespace, name string, data map[string][]byte, immutable bool) *v1.Secret {
	if data == nil {
		data = map[string][]byte{}
	}
	data["cosign.key"] = keys.PrivateBytes
	data["cosign.pub"] = keys.PublicBytes
	data["cosign.password"] = keys.Password()

	obj := metav1.ObjectMeta{
		Name:      name,
		Namespace: namespace,
	}

	// For Kubernetes >= 1.21, set Immutable by default
	if immutable {
		return &v1.Secret{
			ObjectMeta: obj,
			Data:       data,
			Immutable:  pointer.Bool(true),
		}
	}

	return &v1.Secret{
		ObjectMeta: obj,
		Data:       data,
	}
}

// the reference should be formatted as <namespace>/<secret name>
func parseRef(k8sRef string) (string, string, error) {
	s := strings.Split(strings.TrimPrefix(k8sRef, KeyReference), "/")
	if len(s) != 2 {
		return "", "", errors.New("kubernetes specification should be in the format k8s://<namespace>/<secret>")
	}
	return s[0], s[1], nil
}


text:
fails:IO#ungetbyte does nothing when passed nil
fails:IO#ungetbyte puts back each byte in a String argument
fails:IO#ungetbyte calls #to_str to convert the argument
fails:IO#ungetbyte puts back one byte for an Integer argument


text:
<?php

namespace Bugsnag\Request;

class PhpRequest implements RequestInterface
{
    /**
     * The server variables.
     *
     * @var array
     */
    protected $server;

    /**
     * The session variables.
     *
     * @var array
     */
    protected $session;

    /**
     * The cookie variables.
     *
     * @var array
     */
    protected $cookies;

    /**
     * The http headers.
     *
     * @var array
     */
    protected $headers;

    /**
     * The input params.
     *
     * @var array|null
     */
    protected $input;

    /**
     * Create a new php request instance.
     *
     * @param array      $server  the server variables
     * @param array      $session the session variables
     * @param array      $cookies the cookie variables
     * @param array      $headers the http headers
     * @param array|null $input   the input params
     *
     * @return void
     */
    public function __construct(array $server, array $session, array $cookies, array $headers, array $input = null)
    {
        $this->server = $server;
        $this->session = $session;
        $this->cookies = $cookies;
        $this->headers = $headers;
        $this->input = $input;
    }

    /**
     * Are we currently processing a request?
     *
     * @return bool
     */
    public function isRequest()
    {
        return true;
    }

    /**
     * Get the session data.
     *
     * @return array
     */
    public function getSession()
    {
        return $this->session;
    }

    /**
     * Get the cookies.
     *
     * @return array
     */
    public function getCookies()
    {
        return $this->cookies;
    }

    /**
     * Get the request formatted as meta data.
     *
     * @return array
     */
    public function getMetaData()
    {
        $data = [];

        $data['url'] = $this->getCurrentUrl();

        if (isset($this->server['REQUEST_METHOD'])) {
            $data['httpMethod'] = $this->server['REQUEST_METHOD'];
        }

        $data['params'] = $this->input;

        $data['clientIp'] = $this->getRequestIp();

        if (isset($this->server['HTTP_USER_AGENT'])) {
            $data['userAgent'] = $this->server['HTTP_USER_AGENT'];
        }

        if ($this->headers) {
            $data['headers'] = $this->headers;
        }

        return ['request' => $data];
    }

    /**
     * Get the request context.
     *
     * @return string|null
     */
    public function getContext()
    {
        if (isset($this->server['REQUEST_METHOD']) && isset($this->server['REQUEST_URI'])) {
            return $this->server['REQUEST_METHOD'].' '.strtok($this->server['REQUEST_URI'], '?');
        }
    }

    /**
     * Get the request user id.
     *
     * @return string|null
     */
    public function getUserId()
    {
        return $this->getRequestIp();
    }

    /**
     * Get the request url.
     *
     * @return string
     */
    protected function getCurrentUrl()
    {
        $schema = ((!empty($this->server['HTTPS']) && $this->server['HTTPS'] !== 'off') || (!empty($this->server['SERVER_PORT']) && $this->server['SERVER_PORT'] == 443)) ? 'https://' : 'http://';

        $host = isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost';

        return $schema.$host.$this->server['REQUEST_URI'];
    }

    /**
     * Get the request ip.
     *
     * @return string|null
     */
    protected function getRequestIp()
    {
        if (isset($this->server['HTTP_X_FORWARDED_FOR'])) {
            return $this->server['HTTP_X_FORWARDED_FOR'];
        }

        if (isset($this->server['REMOTE_ADDR'])) {
            return $this->server['REMOTE_ADDR'];
        }
    }
}


text:
#ifndef GRPC_CORE_EXT_CLIENT_CONFIG_RESOLVER_REGISTRY_H
#define GRPC_CORE_EXT_CLIENT_CONFIG_RESOLVER_REGISTRY_H

#include "src/core/ext/client_config/resolver_factory.h"

void grpc_resolver_registry_init();
void grpc_resolver_registry_shutdown(void);

/** Set the default URI prefix to \a default_prefix. */
void grpc_resolver_registry_set_default_prefix(const char *default_prefix);

/** Register a resolver type.
    URI's of \a scheme will be resolved with the given resolver.
    If \a priority is greater than zero, then the resolver will be eligible
    to resolve names that are passed in with no scheme. Higher priority
    resolvers will be tried before lower priority schemes. */
void grpc_register_resolver_type(grpc_resolver_factory *factory);

/** Create a resolver given \a target.
    First tries to parse \a target as a URI. If this succeeds, tries
    to locate a registered resolver factory based on the URI scheme.
    If parsing or location fails, prefixes default_prefix from
    grpc_resolver_registry_init to target, and tries again (if default_prefix
    was not NULL).
    If a resolver factory was found, use it to instantiate a resolver and
    return it.
    If a resolver factory was not found, return NULL. */
grpc_resolver *grpc_resolver_create(const char *target);

/** Find a resolver factory given a name and return an (owned-by-the-caller)
 *  reference to it */
grpc_resolver_factory *grpc_resolver_factory_lookup(const char *name);

/** Given a target, return a (freshly allocated with gpr_malloc) string
    representing the default authority to pass from a client. */
char *grpc_get_default_authority(const char *target);

#endif /* GRPC_CORE_EXT_CLIENT_CONFIG_RESOLVER_REGISTRY_H */


text:
require 'sinatra'
require 'json'

module Sinatra
  module JSONAPI
    VERSION = "0.0.3"

    def self.registered(app)
      app.disable :show_exceptions
      app.disable :raise_errors
      app.disable :protection
      app.enable :raise_errors if test?

      app.before do
        content_type :json
      end

      app.error do
        api_error 'unexpected_error', 'An unexpected error has occured, please try your request again later'
      end

      # Disables Sinatra's internal HTML error message for development mode.
      app.error Sinatra::NotFound do
        not_found
      end

      app.not_found do
        # If 404 body is not the default "Not Found" message, we can return it without processing.
        return response if response.body.first != "
Not Found
"

        api_error 'not_found', "The requested method was not found: #{request.path}"
      end

      app.helpers do
        def api_error(type, message)
          payload = {:error => {:type => type, :message => message}}
          halt process_payload(payload)
        end

        def api_response(payload)
          halt process_payload(payload)
        end

        def _jsonapi_to_json(input)
          JSON.unparse input
        end

        def process_payload(payload)
          if params[:callback]
            response_body = "#{params[:callback]}({\n"+
                            "  #{_jsonapi_to_json payload}\n"+
                            "})"
          else
            response_body = _jsonapi_to_json payload
          end
        end
      end
    end
  end

  register JSONAPI
end


text:
Banca y finanzas

Asesoramiento especializado para la correcta toma de decisiones financieras.Asesoramos a nuestros clientes en la toma de decisiones financieras, entendemos la importancia del

Civil e inmobiliaria

Brindamos asesoría legal en todas las áreas de la industria inmobiliaria, incluyendo la compra venta de inmuebles y el desarrollo de proyectos inmobiliarios, contratos de arrendamiento

Competencia

Todos los días apreciamos nuevas formas y mecanismos de competencia en el mercado. Nuestro marco normativo se encuentra sujeto a la creatividad de los competidores, quienes en búsqueda

Concursal y patrimonial

Brindamos asesoría oportuna y e ciente a empresas que enfrentan situaciones de crisis patrimonial. Afrontamos nuestros casos con un alto nivel de análisis y dedicación a efectos de

Corporativa

Nuestra área corporativa brinda todos los servicios legales que una compañía pueda requerir en su día a día. Asesoramos a nuestros clientes en temas vinculados al proceso de constitución

Administrativo

Lazo, De Romaña & Gaglui  Abogados asesora a empresas en procesos de obtención de autorizaciones, licencias y permisos administrativos. Asimismo, se dedica a la defensa de los intereses

Laboral

Las relaciones laborales al interior de la empresa adquieren signi cativa relevancia al permitir el desarrollo de sus actividades de manera armoniosa, lo cual influye en la productividad

Propiedad intelectual

Los signos distintivos y las creaciones de las empresas se constituyen como importantes activos que merecen una esmerada y adecuada protección frente a terceros. Considerando ello, Lazo

Protección consumidor

Las políticas públicas en materia de Protección al Consumidor en el Perú han venido reforzándose en los últimos años, re ejándose esto en la aprobación de diversas normas especiales

Tributario

Los servicios que brinda el área tributaria y de planeamiento tributario se sustentan en el conocimiento integral que sus miembros pretenden alcanzar sobre la naturaleza de los correspondientes

Banca y finanzas

Asesoramiento especializado para la correcta toma de decisiones financieras.Asesoramos a nuestros clientes en la toma de decisiones financieras, entendemos la importancia del

Civil e inmobiliaria

Brindamos asesoría legal en todas las áreas de la industria inmobiliaria, incluyendo la compra venta de inmuebles y el desarrollo de proyectos inmobiliarios, contratos de arrendamiento

Competencia

Todos los días apreciamos nuevas formas y mecanismos de competencia en el mercado. Nuestro marco normativo se encuentra sujeto a la creatividad de los competidores, quienes en búsqueda


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;

namespace Xceed.Wpf.Toolkit.Core.Converters
{
    public class CornerRadiusToDoubleConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double radius = 0.0;

            if (value != null)
                radius = ((CornerRadius)value).TopLeft;

            return radius;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double radius = 0.0;

            if (value != null)
                radius = (double)value;

            return new CornerRadius(radius);
        }
    }
}