text:
This repository contains an example Order API that meets the business requirements documented by the Joint OBF OS/MEF Ordering Team.
This API conforms to the business requirements, inclusive of CfC comments resolved as of 2/27/2017.

The Order state machine is provided below. This state machine is based upon TMForum Order State machine, and will need to be revised (either by TMForum, or the Joint OBF OS/MEF LSO Sonata Ordering Team) to fully meet the needs of Carrier Ethernet Ordering.
![Order State Machine](MEF_OrderStateDiagram.png)

## API

This API is based on TMForum Order, with some extensions to better support ordering of Ethernet service. The TMForum Characteristic/Characteristic Value pattern is *not* used. Instead, Product Specifications will be defined using the ONF Specification pattern, where the various concrete Product Specifications are schemas whose attributes are "injected" into the Products derived from the Product Specifications. I.e. each Property defined in the Product Specification will be included dynamically (using Json Linked Data - JSON LD) in the Product derived from the Product Specification. For the moment, Product attributes in this API are inlined as Product attributes, and the Product Specification is not referenced using JSON LD. This should be corrected once the TMForum support for the ONF Specification pattern is defined.

The Order API is described in [Order API](order-api.md).

The Order Status API is described in [Order Status API](order-status-api.md).

The Order Notification API is described in [Order Notification API](order-notification-api.md).

Example Order Notifications are provided in [Order Notification Examples](order-notification.md).

## Additional Documentation

Endpoint definitions are provided in the [endpoints](../endpoints) directory of this repository.

Json Schema definitions of the request and response payloads are provided in the [schemas](../schemas) directory of this repository.

Example payloads are included in the [example-data](../example-data) directory of this repository.


text:
package fi.helsinki.cs.iot.hub.api.handlers.basic;

import java.io.File;
import java.util.Map;

import fi.helsinki.cs.iot.hub.utils.ScriptUtils;
import fi.helsinki.cs.iot.hub.webserver.NanoHTTPD;
import fi.helsinki.cs.iot.hub.webserver.NanoHTTPD.Method;
import fi.helsinki.cs.iot.hub.webserver.NanoHTTPD.Response;
import fi.helsinki.cs.iot.hub.webserver.NanoHTTPD.Response.Status;

public abstract class HttpRequestHandler {

	public static final String JSON_MIME_TYPE = "application/json";
	public static final String HTML_MIME_TYPE = "text/html; charset=utf-8";
	public static final String TAG = "HttpRequestHandler";

	public abstract boolean acceptRequest(Method method, String uri);
	public abstract Response handleRequest(Method method, String uri,
			Map<String, String> parameters, String mimeType, Map<String, String> files);

	public String getJsonData(Method method, Map<String, String> files) {
		if (files == null) {
			return null;
		}
		switch (method) {
		case POST:
			return files.get("postData");
		case PUT:
			File file = new File(files.get("content"));
			if (file.exists()) {
				return ScriptUtils.convertFileToString(file);
			}
		default:
			return null;
		}

	}

	public Response getHtmlResponse(String html) {
		return new NanoHTTPD.Response(Status.OK, HTML_MIME_TYPE, html);
	}

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * context.c - context management routines
 */

/*
 * The context consists of kernel/user mode registers, and kernel
 * stack. The user mode registers are always saved to the kernel
 * stack when processor enters kernel mode by H/W or S/W events.
 *
 * The user mode registers are located in the interrupt/trap
 * frame at the top of the kernel stack. Before the control
 * returns to user mode next time, these register value will be
 * restored automatically.
 *
 * All thread owns its context to keep its execution state. The
 * scheduler will switch the context to change an active thread.
 */

#include <kernel.h>
#include <kmem.h>
#include <cpu.h>
#include <context.h>
#include <locore.h>
#include <trap.h>

/*
 * Set user mode registers into the specific context.
 *
 * Note: When user mode program counter is set, all register
 * values except a stack pointer are reset to default value.
 */
void
context_set(context_t ctx, int type, register_t val)
{
	struct kern_regs *k;
	struct cpu_regs *u;
	uint32_t *argp;

	k = &ctx->kregs;

	switch (type) {
	case CTX_KSTACK:
		/* Adjust stack for C code */
		val -= STKFRAME_LEN;

		/* Set kernel mode stack pointer */
		ctx->uregs = (struct cpu_regs *)
				((uint32_t)val - sizeof(struct cpu_regs));

		k->sp = (uint32_t)ctx->uregs;
		k->kstack = (uint32_t)val;

		/* Reset minimum user mode registers */
		u = ctx->uregs;
		u->gr[3] = 0x11111111;
		u->gr[4] = 0x22222222;
		u->gr[5] = 0x33333333;
		u->srr1 = MSR_DFLT;
		break;

	case CTX_KENTRY:
		/* Kernel mode program counter */
		k->lr = (uint32_t)val;
		break;

	case CTX_KARG:
		/* Kernel mode argument */
		argp = (uint32_t *)(k->sp + sizeof(uint32_t) * 2);
		*argp = (uint32_t)val;
		break;

	case CTX_USTACK:
		/* User mode stack pointer */
		u = ctx->uregs;
		u->gr[1] = (uint32_t)val;
		break;

	case CTX_UENTRY:
		/* User mode program counter */
		u = ctx->uregs;
		u->srr0 = (uint32_t)val;
		u->srr1 = MSR_DFLT;
		break;

	case CTX_UARG:
		/* User mode argument */
		u = ctx->uregs;
		u->gr[3] = (uint32_t)val;
		argp = (uint32_t *)(u->gr[1] + sizeof(uint32_t));
		copyout(&val, argp, sizeof(uint32_t));
		break;

	default:
		/* invalid */
		break;
	}
}

/*
 * Switch to new context
 *
 * Kernel mode registers and kernel stack pointer are switched to
 * the next context.
 *
 * It is assumed all interrupts are disabled by caller.
 *
 * TODO: FPU context is not switched as of now.
 */
void
context_switch(context_t prev, context_t next)
{

	cpu_switch(&prev->kregs, &next->kregs);
}

/*
 * Save user mode context to handle exceptions.
 *
 * Copy current user mode registers in the kernel stack to the
 * user mode stack. The user stack pointer is adjusted for this
 * area. So that the exception handler can get the register
 * state of the target thread.
 *
 * It builds arguments for the exception handler in the following
 * format.
 *
 *   void exception_handler(int exc, void *regs);
 */
void
context_save(context_t ctx)
{
	struct cpu_regs *cur, *sav;

	/* Copy current register context into user mode stack */
	cur = ctx->uregs;
	sav = (struct cpu_regs *)(cur->gr[1] - sizeof(struct cpu_regs));
	copyout(cur, sav, sizeof(*sav));

	ctx->saved_regs = sav;

	/* Adjust stack pointer */
	cur->gr[1] = (uint32_t)sav - sizeof(uint32_t);
}

/*
 * Restore register context to return from the exception handler.
 */
void
context_restore(context_t ctx)
{
	struct cpu_regs *cur;

	/* Restore user mode context */
	cur = ctx->uregs;
	copyin(ctx->saved_regs, cur, sizeof(*cur));

	/* Correct some registers for fail safe */
	cur->srr1 |= MSR_DFLT;
}

void
context_dump(context_t ctx)
{

#ifdef DEBUG
	trap_dump(ctx->uregs);
#endif
}


text:
{% load cms_tags menu_tags sekizai_tags %}
{% load static from staticfiles %}
<!DOCTYPE html>

    <title>{% block title %}This is my new project home page{% endblock title %}</title>

    <link rel='stylesheet' href="{% static "css/bootstrap.min.css" %}" media="all" />
    <link rel='stylesheet' href="{% static "css/font-awesome.min.css" %}" media="all" />
    {% render_block "css" %}

    {% cms_toolbar %}

                 <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
                     Toggle navigation

                 </button>

                 Project Name

                     {% show_menu 0 1 100 100 "menu.html" %}

        {% block content %}{% endblock content %}

    {% render_block "js" %}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using WebDAVClient.Model;

namespace letsencrypt_tests.Support
{
    public class MockWebDAVClient : WebDAVClient.IClient
    {
        public MockWebDAVClient(NetworkCredential credential) { }

        public string BasePath { get; set; }

        public int? Port { get; set; }

        public string Server { get; set; }

        public string UserAgent { get; set; }

        public string UserAgentVersion { get; set; }

        public Task<bool> CreateDir(string remotePath, string name)
        {
            return Task.FromResult(true);
        }

        public Task DeleteFile(string path = "/")
        {
            return Task.FromResult(true);
        }

        public Task DeleteFolder(string path = "/")
        {
            return Task.FromResult(true);
        }

        public Task<Stream> Download(string remoteFilePath)
        {
            throw new NotImplementedException();
        }

        public Task<Item> GetFile(string path = "/")
        {
            throw new NotImplementedException();
        }

        public Task<Item> GetFolder(string path = "/")
        {
            throw new NotImplementedException();
        }

        public Task<IEnumerable<Item>> List(string path = "/", int? depth = 1)
        {
            List<Item> list = new List<Item>();
            list.Add(new Item
            {
                DisplayName = "web.config"
            });
            return Task.FromResult((IEnumerable<Item>)list);
        }

        public Task<bool> MoveFile(string srcFilePath, string dstFilePath)
        {
            return Task.FromResult(true);
        }

        public Task<bool> MoveFolder(string srcFolderPath, string dstFolderPath)
        {
            return Task.FromResult(true);
        }

        public Task<bool> Upload(string remoteFilePath, Stream content, string name)
        {
            return Task.FromResult(true);
        }
    }
}


text:
package javax.batch.api.chunk.listener;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public abstract class AbstractItemProcessListener implements ItemProcessListener {

    @Override
    public void beforeProcess(Object item) throws Exception {}

    @Override
    public void afterProcess(Object item, Object result) throws Exception {}

    @Override
    public void onProcessError(Object item, Exception exception) throws Exception {}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.opencb.cellbase</groupId>
        <artifactId>cellbase</artifactId>
        <version>4.1.0-beta</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>cellbase-core</artifactId>
    <version>${cellbase.version}</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.opencb.biodata</groupId>
            <artifactId>biodata-formats</artifactId>
        </dependency>
        <dependency>
            <groupId>org.opencb.biodata</groupId>
            <artifactId>biodata-tools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.opencb.commons</groupId>
            <artifactId>commons-datastore-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>configuration.json</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>


text: Project to regulary fetch and save post from kopipasta.ru


text:
use strict;
package Text::CMU::InputFilter::ICSI;
use IO::File;
use XML::Parser;
use base 'Text::CMU::InputFilter';

sub initialize {
    my ($self, %opts) = @_;

    $self->SUPER::initialize(%opts);
    $self->{fps} = defined($opts{fps}) ? $opts{fps} : 105;
    $self->{tagstack} = [];
}

sub process_transcript {
    my ($self, $transfile) = @_;

    $self->{parser} =
	 XML::Parser->new(Handlers => { Start => sub { StartTag($self, @_) },
					End   => sub { EndTag($self, @_) },
					Char  => sub { Text($self, @_) }});

    $self->{parser}->parsefile($transfile);
    return 1;
}

use vars qw(%StartHandlers %EndHandlers);
%StartHandlers = (
		  Channel => sub {
		      my ($self, $expat, $elem, %attr) = @_;
		      # Record the channel to microphone ID mapping
		      $self->{MICID}{$attr{Name}} = $attr{Mic};
		  },
		  Participant => sub {
		      my ($self, $expat, $elem, %attr) = @_;
		      # Record the participant to channel mapping
		      $self->{Channel}{$attr{Name}} = $attr{Channel};
		  },
		  Transcript => sub {
		      my ($self, $expat, $elem, %attr) = @_;
		      $self->{startTime}=int($attr{StartTime}*$self->{fps});
		      #HACK! To avoid potential spurious frames at the end.
		      #HACK! This is just for safety.
		      $self->{endTime}=int($attr{EndTime}*$self->{fps})-3;
		  },
		  Meeting => sub {
		      my ($self, $expat, $elem, %attr) = @_;
		      # Record the meeting ID
		      $self->{MeetingID} = $attr{Session};
		  },
		  Segment => \&StartSegment,
		 );
%EndHandlers = (
		Segment => \&EndSegment,
	       );

sub StartTag {
    my($self, $expat, $elem) = @_;
    my $stack = $self->{tagstack};
    push @$stack, $elem;
    if (exists $StartHandlers{$elem}) {
	$StartHandlers{$elem}->(@_);
    } else {
	StartMisc(@_);
    }
}

sub EndTag {
    my($self, $expat, $elem) = @_;
    my $stack = $self->{tagstack};
    my $e = pop @$stack;
    warn "Malformed XML, element $e != $elem" unless $e eq $elem;

    if (exists $EndHandlers{$elem}) {
	$EndHandlers{$elem}->(@_);
    } else {
	EndMisc(@_);
    }
}

sub StartSegment {
    my ($self, $expat, $elem, %attr) = @_;
    my($sid, $chan);
    my ($st, $et);

    my $micid = "none";
    # Figure out which channel to use.
    # If the Segment has a Channel attribute, just use it
    if (exists($attr{Channel})) {
	$chan = $attr{Channel};

	# If the Segment does NOT have a Channel attribute, but does
	# have a Participant, and CloseMic is true, use the default
	# channel for the participant.

    } elsif (exists($attr{Participant}) &&
	     (!exists($attr{CloseMic}) || $attr{CloseMic} eq "true")) {
	$chan = $self->{Channel}{$attr{Participant}};
	$micid = $self->{MICID}{$chan};
	if (!$micid) {
	    printf(STDERR "Microphone ID not found.");
	}
    } else {
	# Otherwise, just use "far"
	# Far field channels are ignored.
	$chan = 'far';
	$self->{isIgnore}=1;
    }

    # Get the Participant attribute, or "none" if none provided.
    if (exists($attr{Participant})) {
	$sid = $attr{Participant};
    } else {
	$sid = "none";
    }

    $st=$attr{StartTime};
    $et=$attr{EndTime};
    $self->{Header} = "$self->{MeetingID}/${chan}_${sid}_${micid}_${st}_${et}";
    $self->{StartTime} = $st;
    $self->{EndTime} = $et;
    $self->{ChannelID} = $chan;

    # Start collecting up text
    $self->{InSegment} = 1;
    $self->{TextSoFar} = '';

    # Any other tag is passed verbatim if we're in a <Segment> ... </Segment>
}

sub StartMisc {
    my ($self, $expat, $elem, %attr) = @_;
    my $opts = $self->{opts};

    #This routine takes care of the tags inside the <Segment> tag.
    #This is the current rule
    # -when <Foreign> <Pronounce> and <Uncertain> tags were encountered,
    # the sentence is ignored.
    # -when <Emphasis> is encountered, the tag is ignored.
    # -when <Pause> is encountered, the tag is replaced by <sil>
    # -when <Comment>/<VocalSound>/<NonVocalSound> are encountered,
    # they are handled with specific rules encoded in the rule file(s).
    #
    #           Uncomment this line to debug
    #	    $self->{TextSoFar} .= " " . $expat->original_string();
    if ($elem eq "Comment") {
	#Tag Comment handling
	$self->{TextSoFar} .= " " ;
	if ($attr{"Description"} ne "Digits") {
	    $self->{isIgnore}=1;
	}
    } elsif ($elem eq "Emphasis") {
	#Tag Emphasis handling
	#Skip the tag.
	$self->{TextSoFar} .= "" ;
    } elsif ($elem eq "Foreign") {
	#Tag Foreign handling
	$self->{TextSoFar} .= " " . $expat->original_string();
	$self->{isIgnore}=1;
    } elsif ($elem eq "Pause") {
	#Tag Pause handling
	$self->{TextSoFar} .= " " . "<sil>";
    } elsif ($elem eq "Pronounce") {
	#Tag Pronounce handling
	$self->{TextSoFar} .= " " ;
    } elsif ($elem eq "Uncertain") {
	#Tag Uncertain handling
	$self->{TextSoFar} .= " " ;
    } elsif ($elem eq "VocalSound" or $elem eq "NonVocalSound") {
	# Filler word handling
	my $label = $self->{FillerMap}{$attr{"Description"}};
	if (defined($label)) {
	    $self->{TextSoFar} .= " " . $label;
	} else {
	    warn "No corresponding label for <VocalSound> with description $attr{Description}";
	    $self->{isIgnore}=1;
	}
    }
}

sub EndSegment {
    my($self, $expat, $elem) = @_;
    my $opts = $self->{opts};

    # Clean everything up and print it out
    $self->{TextSoFar} =~ s/\n/ /g;
    $self->{TextSoFar} =~ s/\s\s+/ /g;
    $self->{TextSoFar} =~ s/^\s+//;
    $self->{TextSoFar} =~ s/\s+$//;
    if ($self->{TextSoFar} !~ /^\s*$/ && #only if file is not empty
	!$self->{isIgnore} #there are no special tags that caused us ignore this string.
       ) {
	# Do text normalization now.
	my @words = $self->text_norm($self->{TextSoFar});
	# And output an utterance
	$self->output_sentence(\@words, $self->{Header},
			       "$self->{MeetingID}/$self->{ChannelID}",
			       $self->{StartTime}, $self->{EndTime})
	    if @words;
    }
    $self->{InSegment} = 0;
    $self->{isIgnore} = 0 ;
    $self->{TextSoFar} = '';
}

sub EndMisc {
    my ($self, $expat, $elem) = @_;
    my $opts = $self->{opts};
    if ($self->{InSegment}) {
	if ($elem eq "Comment") {
	    #Tag Comment handling
	    $self->{TextSoFar} .= " " . $expat->original_string();
	} elsif ($elem eq "Emphasis") {
	    #Tag Emphasis handling
	    #Skip the tag.
	    $self->{TextSoFar} .= "" ;
	} elsif ($elem eq "Foreign") {
	    #Tag Foreign handling
	    $self->{TextSoFar} .= " " . $expat->original_string();
	} elsif ($elem eq "Pause") {
	    #Tag Pause handling
	    $self->{TextSoFar} .= " " . $expat->original_string();
	} elsif ($elem eq "Pronounce") {
	    #Tag Pronounce handling
	    $self->{TextSoFar} .= " " ;
	} elsif ($elem eq "Uncertain") {
	    #Tag Uncertain handling
	    $self->{TextSoFar} .= " " ;
	} elsif ($elem eq "VocalSound") {
	    #Tag VocalSound handling.
	    $self->{TextSoFar} .= " " . $expat->original_string();
	} elsif ($elem eq "NonVocalSound") {
	    #Tag NonVocalSound handling
	    $self->{TextSoFar} .= " " . $expat->original_string();
	}
    }
}

#WARNING BY ARCHAN!!!!!
#DON'T DO TEXT NORMALIZATION IN THIS FUNCTION!!!!!!
#$string can be some incomplete characters.
#Only thing I have done in this function is to make sure text with tags are correct.
#That proves to be tricky.
sub Text {
    my($self, $expat, $string) = @_;
    my $elem=$expat->current_element();
    my $opts = $self->{opts};
    if ($self->{InSegment}) {
	if ($elem eq "Uncertain" || $elem eq "Pronounce") {
	    $string =~ s/^\s+//;
	    $string =~ s/\s+$//;

	    my @words=split(/\s+/,$string);
	    foreach my $word (@words) {
		$self->{TextSoFar} .= " ++GARBAGE++ " . " " ;
	    }
	} elsif ($elem eq "Emphasis") {
	    $string =~ s/^\s+//;
	    $string =~ s/\s+$//;
	    $self->{TextSoFar} .= $string  ;
	} else {
	    $self->{TextSoFar} .= $string  ;
	}
    }
}

sub NormalizeWord{
    my ($self, $word) =@_;
    my $opts = $self->{opts};
    if($word eq "<sil>" || $word =~ /\+\+/){
	return "" unless $opts->{fillers};
    }
    #Get rid of comma, footstop, question mark and exclamation point.
    #Also '{' and '}'
    $word =~ s/,//g;
    $word =~ s/\.//g;
    $word =~ s/\!//g;
    $word =~ s/\?//g;
    $word =~ s/://g;
    #Get rid of asterisk symbol
    $word =~ s/\*//g;
    #Get rid of double approsothe
    $word =~ s/\"//g;

    # Delete stray '-'
    if ($word eq '-') {
	$word = "";
    }

    # ICSI has X_ for single letters which we claim is bogus
    if ($word =~ /^([A-Za-z])_$/) {
	$word = $1;
    }

    return $word;
}

sub text_norm{
    my($self, $string)=@_;
    $string=~s/^\s+//;
    $string=~s/\s+$//;

    my @words=split(" ",$string);
    my @outwords;
    my $norm_string = "";
    foreach my $word (@words){
	#This is the word normalization routine,
	#Entry point of text normalization.
	my $normword = $self->NormalizeWord($word);
	push @outwords, split(" ",$normword);
    }

    return @outwords;
}

1;
__END__

=head1 NAME

Text::CMU::InputFilter::ICSI - Input filter for ICSI format transcripts

=head1 SYNOPSIS

=head1 OPTIONS

=over 4

=item fillermap

A file listing a mapping of filler words from the input to filler
words in the output.  Each line has an input and an output separated
by whitespace.

=item dict

A dictionary to use for constructing a list of OOVs.

=item split

Whether to split compound words

=item partials

Whether to include partial words

=item filledpauses

Whether to include filled pauses

=item fillers

Whether to include filler words

=item noisy

Whether to include noise-only utterances

=back

=head1 AUTHORS

Arthur Chan E<lt>archan@cs.cmu.eduE<gt>, David Huggins-Daines
E<lt>dhuggins@cs.cmu.eduE<gt>.

=cut


text:
package org.jboss.pnc.bpm.test;

import org.jboss.pnc.bpm.BpmEventType;
import org.jboss.pnc.bpm.BpmManager;
import org.jboss.pnc.bpm.causeway.ProductMilestoneReleaseManager;
import org.jboss.pnc.bpm.model.causeway.BuildImportResultRest;
import org.jboss.pnc.bpm.model.causeway.BuildImportStatus;
import org.jboss.pnc.bpm.model.causeway.MilestoneReleaseResultRest;
import org.jboss.pnc.bpm.task.MilestoneReleaseTask;
import org.jboss.pnc.common.concurrent.Sequence;
import org.jboss.pnc.dto.ProductMilestoneCloseResult;
import org.jboss.pnc.enums.BuildPushStatus;
import org.jboss.pnc.enums.MilestoneCloseStatus;
import org.jboss.pnc.enums.ReleaseStatus;
import org.jboss.pnc.mapper.api.BuildMapper;
import org.jboss.pnc.mapper.api.ProductMilestoneCloseResultMapper;
import org.jboss.pnc.mock.repository.*;
import org.jboss.pnc.model.*;
import org.jboss.pnc.spi.datastore.repositories.ProductMilestoneReleaseRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductMilestoneRepository;
import org.jboss.pnc.spi.exception.CoreException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import javax.enterprise.event.Event;
import java.util.ArrayList;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

/**
 * Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com
 */
public class ProductMilestoneReleaseManagerTest {

    private static final String BREW_URL_PATTERN = "http://brew.example.com/build/%d/";

    @Mock
    private BpmManager bpmManager;

    @Mock
    private Event<ProductMilestoneCloseResult> productMilestoneCloseResultEvent;

    @Mock
    private ProductMilestoneCloseResultMapper mapper;

    private ProductMilestoneRepository milestoneRepository;
    private ProductMilestoneReleaseRepository productMilestoneReleaseRepository;
    private BuildRecordRepositoryMock buildRecordRepository;
    private BuildRecordPushResultRepositoryMock buildRecordPushResultRepository;

    private ProductMilestoneReleaseManager releaseManager;
    private final BpmTaskCapture taskCapture = new BpmTaskCapture();

    private int milestoneIdSequence = 0;

    @Before
    public void setUp() throws CoreException {
        milestoneRepository = new ProductMilestoneRepositoryMock();
        productMilestoneReleaseRepository = new ProductMilestoneReleaseRepositoryMock();
        buildRecordRepository = new BuildRecordRepositoryMock();
        buildRecordPushResultRepository = new BuildRecordPushResultRepositoryMock();

        MockitoAnnotations.initMocks(this);
        when(bpmManager.startTask(any())).then(taskCapture);
        releaseManager = new ProductMilestoneReleaseManager(
                productMilestoneReleaseRepository,
                bpmManager,
                new ProductVersionRepositoryMock(),
                buildRecordRepository,
                milestoneRepository,
                buildRecordPushResultRepository,
                mapper,
                productMilestoneCloseResultEvent,
                null,
                null);
    }

    @Test
    public void shouldStoreSuccess() {
        // given
        ProductMilestone milestone = createMilestone();
        BuildRecord record = buildRecord(milestone);
        int brewBuildId = 100;
        // when
        release(milestone, brewBuildId, record);
        // then
        assertPushResultLinkedToRecord(record, brewBuildId, brewUrl(brewBuildId));
    }

    @Test
    public void shouldStoreSuccessForTwoBuilds() {
        // given
        ProductMilestone milestone = createMilestone();
        BuildRecord[] records = { buildRecord(milestone), buildRecord(milestone) };

        int brewBuildId = 1000;
        // when
        release(milestone, brewBuildId, records);

        // then
        for (int i = 0; i < 2; i++) {
            BuildRecord record = records[i];
            assertPushResultLinkedToRecord(record, brewBuildId + i, brewUrl(brewBuildId + i));
        }
    }

    @Test
    public void shouldStorePartialImport() {
        // given
        ProductMilestone milestone = createMilestone();
        BuildRecord buildRecord1 = buildRecord(milestone);
        BuildRecord buildRecord2 = buildRecord(milestone);

        MilestoneReleaseResultRest result = new MilestoneReleaseResultRest();
        List<BuildImportResultRest> buildResults = new ArrayList<>();

        buildResults.add(buildImportResultRest(BuildImportStatus.SUCCESSFUL, buildRecord1.getId(), 1));
        buildResults.add(buildImportResultRest(BuildImportStatus.FAILED, buildRecord2.getId(), 2));
        result.setBuilds(buildResults);
        result.setReleaseStatus(ReleaseStatus.IMPORT_ERROR);

        // when
        release(milestone, result);

        // then
        BuildRecordPushResult pushResult1 = buildRecordPushResultRepository
                .getLatestForBuildRecord(buildRecord1.getId());
        assertThat(pushResult1).isNotNull();
        assertThat(pushResult1.getStatus()).isEqualTo(BuildPushStatus.SUCCESS);

        BuildRecordPushResult pushResult2 = buildRecordPushResultRepository
                .getLatestForBuildRecord(buildRecord2.getId());
        assertThat(pushResult2).isNotNull();
        assertThat(pushResult2.getStatus()).isEqualTo(BuildPushStatus.FAILED);

        List<ProductMilestoneRelease> releases = productMilestoneReleaseRepository.queryAll();
        assertThat(releases).hasSize(1)
                .first()
                .extracting(ProductMilestoneRelease::getStatus)
                .isEqualTo(MilestoneCloseStatus.FAILED);
    }

    private BuildImportResultRest buildImportResultRest(
            BuildImportStatus status,
            Base32LongID buildId,
            Integer brewId) {
        return new BuildImportResultRest(BuildMapper.idMapper.toDto(buildId), brewId, brewUrl(brewId), status, null);
    }

    /**
     * Start a milestone release and process the callback
     */
    private void release(ProductMilestone milestone, int brewBuildId, BuildRecord... records) {
        releaseManager.startRelease(milestone, null, false, Sequence.nextId());
        List<ProductMilestoneRelease> releases = productMilestoneReleaseRepository.queryAll();
        assertThat(releases).hasSize(1);
        taskCapture.task.notify(BpmEventType.BREW_IMPORT, successfulReleaseResult(brewBuildId, records));
    }

    private void release(ProductMilestone milestone, MilestoneReleaseResultRest releaseResultRest) {
        releaseManager.startRelease(milestone, null, false, Sequence.nextId());
        List<ProductMilestoneRelease> releases = productMilestoneReleaseRepository.queryAll();
        assertThat(releases).hasSize(1);
        taskCapture.task.notify(BpmEventType.BREW_IMPORT, releaseResultRest);
    }

    private void assertPushResultLinkedToRecord(BuildRecord record, Integer expectedBrewId, String expectedBrewLink) {
        BuildRecordPushResult pushResult = buildRecordPushResultRepository.getLatestForBuildRecord(record.getId());
        assertThat(pushResult).isNotNull();
        assertThat(pushResult.getBrewBuildId()).isEqualTo(expectedBrewId);
        assertThat(pushResult.getBrewBuildUrl()).isEqualTo(expectedBrewLink);
    }

    private MilestoneReleaseResultRest successfulReleaseResult(int brewBuildId, BuildRecord... records) {
        MilestoneReleaseResultRest result = new MilestoneReleaseResultRest();
        List<BuildImportResultRest> buildResults = new ArrayList<>();

        for (int i = 0; i < records.length; i++) {
            Base32LongID recordId = records[i].getId();
            buildResults.add(buildImportResultRest(BuildImportStatus.SUCCESSFUL, recordId, brewBuildId + i));
        }

        result.setBuilds(buildResults);
        result.setReleaseStatus(ReleaseStatus.SUCCESS);
        return result;
    }

    private String brewUrl(int brewBuildId) {
        return String.format(BREW_URL_PATTERN, brewBuildId);
    }

    private ProductMilestone createMilestone() {
        ProductMilestone milestone = new ProductMilestone();
        milestone.setId(milestoneIdSequence++);
        milestone.setProductVersion(new ProductVersion());
        milestoneRepository.save(milestone);

        return milestone;
    }

    private BuildRecord buildRecord(ProductMilestone milestone) {
        BuildRecord record = new BuildRecord();
        record.setProductMilestone(milestone);
        record.setId(new Base32LongID(Sequence.nextId()));
        buildRecordRepository.save(record);
        return record;
    }

    private static class BpmTaskCapture implements Answer<Boolean> {
        private MilestoneReleaseTask task;

        @Override
        public Boolean answer(InvocationOnMock invocation) {
            task = invocation.getArgument(0);
            return true;
        }

    }
}


text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

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

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

# Updating manylinux for Gandiva Jar Build.

Do the following to update arrow manylinux docker image for building Gandiva Jars

- Install java in the manylinux image.
- To do above, update Dockerfile-x86_64_base under python/manylinux1 to install java.
- Please note only upto java7 is available in CentOS5, so install java7 in the base.
- Export JAVA_HOME environment variable.
- Then update build_boost.sh under python/manylinux1/scripts to build boost statically.

Please look at https://github.com/praveenbingo/arrow/tree/buildGandivaDocker that already has these changes.


text:
namespace ash {

static NetworkHandler* g_network_handler = NULL;

NetworkHandler::NetworkHandler()
    : task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()) {
  network_state_handler_.reset(new NetworkStateHandler());
  network_device_handler_.reset(new NetworkDeviceHandlerImpl());
  cellular_inhibitor_.reset(new CellularInhibitor());
  cellular_esim_profile_handler_.reset(new CellularESimProfileHandlerImpl());
  stub_cellular_networks_provider_.reset(new StubCellularNetworksProvider());
  cellular_connection_handler_.reset(new CellularConnectionHandler());
  network_profile_handler_.reset(new NetworkProfileHandler());
  network_configuration_handler_.reset(new NetworkConfigurationHandler());
  managed_network_configuration_handler_.reset(
      new ManagedNetworkConfigurationHandlerImpl());
  network_connection_handler_.reset(new NetworkConnectionHandlerImpl());
  cellular_esim_installer_.reset(new CellularESimInstaller());
  cellular_esim_uninstall_handler_.reset(new CellularESimUninstallHandler());
  cellular_policy_handler_.reset(new CellularPolicyHandler());
  esim_policy_login_metrics_logger_.reset(new ESimPolicyLoginMetricsLogger());
  managed_cellular_pref_handler_.reset(new ManagedCellularPrefHandler());
  cellular_metrics_logger_.reset(new CellularMetricsLogger());
  connection_info_metrics_logger_.reset(new ConnectionInfoMetricsLogger());
  hidden_network_metrics_helper_.reset(new HiddenNetworkMetricsHelper());
  vpn_network_metrics_helper_.reset(new VpnNetworkMetricsHelper());
  if (base::FeatureList::IsEnabled(features::kHiddenNetworkMigration)) {
    hidden_network_handler_.reset(new HiddenNetworkHandler());
  }
  if (ash::features::IsHotspotEnabled()) {
    hotspot_state_handler_.reset(new HotspotStateHandler());
    hotspot_controller_.reset(new HotspotController());
  }
  if (NetworkCertLoader::IsInitialized()) {
    network_cert_migrator_.reset(new NetworkCertMigrator());
    client_cert_resolver_.reset(new ClientCertResolver());
    auto_connect_handler_.reset(new AutoConnectHandler());
    network_certificate_handler_.reset(new NetworkCertificateHandler());
  }
  network_activation_handler_.reset(new NetworkActivationHandlerImpl());
  prohibited_technologies_handler_.reset(new ProhibitedTechnologiesHandler());
  network_sms_handler_.reset(new NetworkSmsHandler());
  geolocation_handler_.reset(new GeolocationHandler());
}

NetworkHandler::~NetworkHandler() {
  network_state_handler_->Shutdown();
}

void NetworkHandler::Init() {
  network_state_handler_->InitShillPropertyHandler();
  network_device_handler_->Init(network_state_handler_.get());
  cellular_inhibitor_->Init(network_state_handler_.get(),
                            network_device_handler_.get());
  cellular_esim_profile_handler_->Init(network_state_handler_.get(),
                                       cellular_inhibitor_.get());
  stub_cellular_networks_provider_->Init(network_state_handler_.get(),
                                         cellular_esim_profile_handler_.get(),
                                         managed_cellular_pref_handler_.get());
  cellular_connection_handler_->Init(network_state_handler_.get(),
                                     cellular_inhibitor_.get(),
                                     cellular_esim_profile_handler_.get());
  network_profile_handler_->Init();
  network_configuration_handler_->Init(network_state_handler_.get(),
                                       network_device_handler_.get());
  managed_network_configuration_handler_->Init(
      cellular_policy_handler_.get(), managed_cellular_pref_handler_.get(),
      network_state_handler_.get(), network_profile_handler_.get(),
      network_configuration_handler_.get(), network_device_handler_.get(),
      prohibited_technologies_handler_.get());
  network_connection_handler_->Init(
      network_state_handler_.get(), network_configuration_handler_.get(),
      managed_network_configuration_handler_.get(),
      cellular_connection_handler_.get());
  cellular_esim_installer_->Init(
      cellular_connection_handler_.get(), cellular_inhibitor_.get(),
      network_connection_handler_.get(), network_profile_handler_.get(),
      network_state_handler_.get());
  cellular_esim_uninstall_handler_->Init(
      cellular_inhibitor_.get(), cellular_esim_profile_handler_.get(),
      managed_cellular_pref_handler_.get(),
      network_configuration_handler_.get(), network_connection_handler_.get(),
      network_state_handler_.get());
  cellular_policy_handler_->Init(
      cellular_esim_profile_handler_.get(), cellular_esim_installer_.get(),
      network_profile_handler_.get(), network_state_handler_.get(),
      managed_cellular_pref_handler_.get(),
      managed_network_configuration_handler_.get());
  if (base::FeatureList::IsEnabled(features::kHiddenNetworkMigration)) {
    hidden_network_handler_->Init(managed_network_configuration_handler_.get(),
                                  network_state_handler_.get());
  }
  if (ash::features::IsHotspotEnabled()) {
    hotspot_state_handler_->Init(network_state_handler_.get());
    hotspot_controller_->Init(hotspot_state_handler_.get());
  }
  managed_cellular_pref_handler_->Init(network_state_handler_.get());
  esim_policy_login_metrics_logger_->Init(
      network_state_handler_.get(),
      managed_network_configuration_handler_.get());
  cellular_metrics_logger_->Init(network_state_handler_.get(),
                                 network_connection_handler_.get(),
                                 cellular_esim_profile_handler_.get(),
                                 managed_network_configuration_handler_.get());
  connection_info_metrics_logger_->Init(network_state_handler_.get(),
                                        network_connection_handler_.get());
  hidden_network_metrics_helper_->Init(network_configuration_handler_.get());
  vpn_network_metrics_helper_->Init(network_configuration_handler_.get());
  if (network_cert_migrator_)
    network_cert_migrator_->Init(network_state_handler_.get());
  if (client_cert_resolver_) {
    client_cert_resolver_->Init(network_state_handler_.get(),
                                managed_network_configuration_handler_.get());
  }
  if (auto_connect_handler_) {
    auto_connect_handler_->Init(client_cert_resolver_.get(),
                                network_connection_handler_.get(),
                                network_state_handler_.get(),
                                managed_network_configuration_handler_.get());
  }
  prohibited_technologies_handler_->Init(
      managed_network_configuration_handler_.get(),
      network_state_handler_.get());
  network_sms_handler_->Init();
  geolocation_handler_->Init();
}

// static
void NetworkHandler::Initialize() {
  CHECK(!g_network_handler);
  g_network_handler = new NetworkHandler();
  g_network_handler->Init();
}

// static
void NetworkHandler::Shutdown() {
  CHECK(g_network_handler);
  delete g_network_handler;
  g_network_handler = NULL;
}

// static
NetworkHandler* NetworkHandler::Get() {
  CHECK(g_network_handler)
      << "NetworkHandler::Get() called before Initialize()";
  return g_network_handler;
}

// static
bool NetworkHandler::IsInitialized() {
  return g_network_handler;
}

void NetworkHandler::InitializePrefServices(
    PrefService* logged_in_profile_prefs,
    PrefService* device_prefs) {
  cellular_esim_profile_handler_->SetDevicePrefs(device_prefs);
  managed_cellular_pref_handler_->SetDevicePrefs(device_prefs);
  ui_proxy_config_service_.reset(new UIProxyConfigService(
      logged_in_profile_prefs, device_prefs, network_state_handler_.get(),
      network_profile_handler_.get()));
  managed_network_configuration_handler_->set_ui_proxy_config_service(
      ui_proxy_config_service_.get());
  network_metadata_store_.reset(new NetworkMetadataStore(
      network_configuration_handler_.get(), network_connection_handler_.get(),
      network_state_handler_.get(), logged_in_profile_prefs, device_prefs,
      is_enterprise_managed_));
  cellular_network_metrics_logger_.reset(new CellularNetworkMetricsLogger(
      network_state_handler_.get(), network_metadata_store_.get(),
      connection_info_metrics_logger_.get()));
  if (base::FeatureList::IsEnabled(ash::features::kHiddenNetworkMigration)) {
    hidden_network_handler_->SetNetworkMetadataStore(
        network_metadata_store_.get());
  }
}

void NetworkHandler::ShutdownPrefServices() {
  cellular_esim_profile_handler_->SetDevicePrefs(nullptr);
  managed_cellular_pref_handler_->SetDevicePrefs(nullptr);
  ui_proxy_config_service_.reset();
  if (base::FeatureList::IsEnabled(ash::features::kHiddenNetworkMigration))
    hidden_network_handler_->SetNetworkMetadataStore(nullptr);
  network_metadata_store_.reset();
}

bool NetworkHandler::HasUiProxyConfigService() {
  return IsInitialized() && Get()->ui_proxy_config_service_.get();
}

UIProxyConfigService* NetworkHandler::GetUiProxyConfigService() {
  DCHECK(HasUiProxyConfigService());
  return Get()->ui_proxy_config_service_.get();
}

NetworkStateHandler* NetworkHandler::network_state_handler() {
  return network_state_handler_.get();
}

AutoConnectHandler* NetworkHandler::auto_connect_handler() {
  return auto_connect_handler_.get();
}

CellularConnectionHandler* NetworkHandler::cellular_connection_handler() {
  return cellular_connection_handler_.get();
}

CellularESimInstaller* NetworkHandler::cellular_esim_installer() {
  return cellular_esim_installer_.get();
}

CellularESimProfileHandler* NetworkHandler::cellular_esim_profile_handler() {
  return cellular_esim_profile_handler_.get();
}

CellularESimUninstallHandler*
NetworkHandler::cellular_esim_uninstall_handler() {
  return cellular_esim_uninstall_handler_.get();
}

CellularInhibitor* NetworkHandler::cellular_inhibitor() {
  return cellular_inhibitor_.get();
}

CellularPolicyHandler* NetworkHandler::cellular_policy_handler() {
  return cellular_policy_handler_.get();
}

HiddenNetworkHandler* NetworkHandler::hidden_network_handler() {
  DCHECK(base::FeatureList::IsEnabled(features::kHiddenNetworkMigration));
  return hidden_network_handler_.get();
}

HotspotController* NetworkHandler::hotspot_controller() {
  return hotspot_controller_.get();
}

HotspotStateHandler* NetworkHandler::hotspot_state_handler() {
  return hotspot_state_handler_.get();
}

ManagedCellularPrefHandler* NetworkHandler::managed_cellular_pref_handler() {
  return managed_cellular_pref_handler_.get();
}

NetworkDeviceHandler* NetworkHandler::network_device_handler() {
  return network_device_handler_.get();
}

NetworkProfileHandler* NetworkHandler::network_profile_handler() {
  return network_profile_handler_.get();
}

NetworkConfigurationHandler* NetworkHandler::network_configuration_handler() {
  return network_configuration_handler_.get();
}

ManagedNetworkConfigurationHandler*
NetworkHandler::managed_network_configuration_handler() {
  return managed_network_configuration_handler_.get();
}

NetworkActivationHandler* NetworkHandler::network_activation_handler() {
  return network_activation_handler_.get();
}

NetworkCertificateHandler* NetworkHandler::network_certificate_handler() {
  return network_certificate_handler_.get();
}

NetworkConnectionHandler* NetworkHandler::network_connection_handler() {
  return network_connection_handler_.get();
}

NetworkMetadataStore* NetworkHandler::network_metadata_store() {
  return network_metadata_store_.get();
}

NetworkSmsHandler* NetworkHandler::network_sms_handler() {
  return network_sms_handler_.get();
}

GeolocationHandler* NetworkHandler::geolocation_handler() {
  return geolocation_handler_.get();
}

ProhibitedTechnologiesHandler*
NetworkHandler::prohibited_technologies_handler() {
  return prohibited_technologies_handler_.get();
}

void NetworkHandler::SetIsEnterpriseManaged(bool is_enterprise_managed) {
  is_enterprise_managed_ = is_enterprise_managed;
  if (esim_policy_login_metrics_logger_) {
    // Call SetIsEnterpriseManaged on ESimPolicyLoginMetricsLogger, this only
    // gets called when the primary user logs in.
    esim_policy_login_metrics_logger_->SetIsEnterpriseManaged(
        is_enterprise_managed);
  }
}

}  // namespace ash


text:
/**
 * @fileoverview Disallow sparse arrays
 * @author Nicholas C. Zakas
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "disallow sparse arrays",
            category: "Possible Errors",
            recommended: true
        },

        schema: []
    },

    create: function(context) {

        //--------------------------------------------------------------------------
        // Public
        //--------------------------------------------------------------------------

        return {

            ArrayExpression: function(node) {

                let emptySpot = node.elements.indexOf(null) > -1;

                if (emptySpot) {
                    context.report(node, "Unexpected comma in middle of array.");
                }
            }

        };

    }
};


text:
// Copyright 2000-2021 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.codeInsight.daemon.impl.actions;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInsight.intention.IntentionActionWithOptions;
import org.jetbrains.annotations.NotNull;

import java.util.Collections;
import java.util.List;

/**
 * An intention action that is used to fix the compilation error
 * with the ability to apply to the current file in batch.
 * <p>
 * If the action is used as an inspection quick-fix or
 * as a usual intention action, using this interface will have no effect.
 */
public interface IntentionActionWithFixAllOption extends IntentionActionWithOptions {
  @Override
  default @NotNull List<IntentionAction> getOptions() {
    return Collections.singletonList(new FixAllHighlightingProblems(this));
  }

  /**
   * Tests if the supplied action belongs to the same family as this action.
   * Default implementation assumes that actions from the same family
   * must have the same runtime class. Could be overridden to provide more specific
   * behavior. Must be symmetrical (x.belongsToMyFamily(y) == y.belongsToMyFamily(x))
   *
   * @param action action to check
   * @return true if the action belongs to the same family as this action.
   */
  default boolean belongsToMyFamily(@NotNull IntentionActionWithFixAllOption action) {
    return action.getClass().equals(getClass());
  }
}


text:
namespace c2cpp
{
iox::popo::ConsumerTooSlowPolicy consumerTooSlowPolicy(const ENUM iox_ConsumerTooSlowPolicy policy) noexcept;
iox::popo::QueueFullPolicy queueFullPolicy(const ENUM iox_QueueFullPolicy policy) noexcept;
iox::popo::SubscriberEvent subscriberEvent(const iox_SubscriberEvent value) noexcept;
iox::popo::SubscriberState subscriberState(const iox_SubscriberState value) noexcept;

iox::popo::ClientEvent clientEvent(const iox_ClientEvent value) noexcept;
iox::popo::ClientState clientState(const iox_ClientState value) noexcept;
iox::popo::ServerEvent serverEvent(const iox_ServerEvent value) noexcept;
iox::popo::ServerState serverState(const iox_ServerState value) noexcept;

iox::runtime::ServiceDiscoveryEvent serviceDiscoveryEvent(const iox_ServiceDiscoveryEvent value) noexcept;
iox::popo::MessagingPattern messagingPattern(const iox_MessagingPattern value) noexcept;
} // namespace c2cpp

#endif


text:
struct GraphTest : public StateTestWithBuiltinRules {
  VirtualFileSystem fs_;
};

TEST_F(GraphTest, MissingImplicit) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat in | implicit\n"));
  fs_.Create("in", 1, "");
  fs_.Create("out", 1, "");

  Edge* edge = GetNode("out")->in_edge();
  string err;
  EXPECT_TRUE(edge->RecomputeDirty(&state_, &fs_, &err));
  ASSERT_EQ("", err);

  // A missing implicit dep *should* make the output dirty.
  // (In fact, a build will fail.)
  // This is a change from prior semantics of ninja.
  EXPECT_TRUE(GetNode("out")->dirty());
}

TEST_F(GraphTest, ModifiedImplicit) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat in | implicit\n"));
  fs_.Create("in", 1, "");
  fs_.Create("out", 1, "");
  fs_.Create("implicit", 2, "");

  Edge* edge = GetNode("out")->in_edge();
  string err;
  EXPECT_TRUE(edge->RecomputeDirty(&state_, &fs_, &err));
  ASSERT_EQ("", err);

  // A modified implicit dep should make the output dirty.
  EXPECT_TRUE(GetNode("out")->dirty());
}

TEST_F(GraphTest, FunkyMakefilePath) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule catdep\n"
"  depfile = $out.d\n"
"  command = cat $in > $out\n"
"build out.o: catdep foo.cc\n"));
  fs_.Create("implicit.h", 2, "");
  fs_.Create("foo.cc", 1, "");
  fs_.Create("out.o.d", 1, "out.o: ./foo/../implicit.h\n");
  fs_.Create("out.o", 1, "");

  Edge* edge = GetNode("out.o")->in_edge();
  string err;
  EXPECT_TRUE(edge->RecomputeDirty(&state_, &fs_, &err));
  ASSERT_EQ("", err);

  // implicit.h has changed, though our depfile refers to it with a
  // non-canonical path; we should still find it.
  EXPECT_TRUE(GetNode("out.o")->dirty());
}

TEST_F(GraphTest, ExplicitImplicit) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule catdep\n"
"  depfile = $out.d\n"
"  command = cat $in > $out\n"
"build implicit.h: cat data\n"
"build out.o: catdep foo.cc || implicit.h\n"));
  fs_.Create("data", 2, "");
  fs_.Create("implicit.h", 1, "");
  fs_.Create("foo.cc", 1, "");
  fs_.Create("out.o.d", 1, "out.o: implicit.h\n");
  fs_.Create("out.o", 1, "");

  Edge* edge = GetNode("out.o")->in_edge();
  string err;
  EXPECT_TRUE(edge->RecomputeDirty(&state_, &fs_, &err));
  ASSERT_EQ("", err);

  // We have both an implicit and an explicit dep on implicit.h.
  // The implicit dep should "win" (in the sense that it should cause
  // the output to be dirty).
  EXPECT_TRUE(GetNode("out.o")->dirty());
}

TEST_F(GraphTest, PathWithCurrentDirectory) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule catdep\n"
"  depfile = $out.d\n"
"  command = cat $in > $out\n"
"build ./out.o: catdep ./foo.cc\n"));
  fs_.Create("foo.cc", 1, "");
  fs_.Create("out.o.d", 1, "out.o: foo.cc\n");
  fs_.Create("out.o", 1, "");

  Edge* edge = GetNode("out.o")->in_edge();
  string err;
  EXPECT_TRUE(edge->RecomputeDirty(&state_, &fs_, &err));
  ASSERT_EQ("", err);

  EXPECT_FALSE(GetNode("out.o")->dirty());
}

TEST_F(GraphTest, RootNodes) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out1: cat in1\n"
"build mid1: cat in1\n"
"build out2: cat mid1\n"
"build out3 out4: cat mid1\n"));

  string err;
  vector<Node*> root_nodes = state_.RootNodes(&err);
  EXPECT_EQ(4u, root_nodes.size());
  for (size_t i = 0; i < root_nodes.size(); ++i) {
    string name = root_nodes[i]->path();
    EXPECT_EQ("out", name.substr(0, 3));
  }
}

TEST_F(GraphTest, VarInOutQuoteSpaces) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build a$ b: cat nospace with$ space nospace2\n"));

  Edge* edge = GetNode("a b")->in_edge();
  EXPECT_EQ("cat nospace \"with space\" nospace2 > \"a b\"",
      edge->EvaluateCommand());
}

// Regression test for https://github.com/martine/ninja/issues/380
TEST_F(GraphTest, DepfileWithCanonicalizablePath) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule catdep\n"
"  depfile = $out.d\n"
"  command = cat $in > $out\n"
"build ./out.o: catdep ./foo.cc\n"));
  fs_.Create("foo.cc", 1, "");
  fs_.Create("out.o.d", 1, "out.o: bar/../foo.cc\n");
  fs_.Create("out.o", 1, "");

  Edge* edge = GetNode("out.o")->in_edge();
  string err;
  EXPECT_TRUE(edge->RecomputeDirty(&state_, &fs_, &err));
  ASSERT_EQ("", err);

  EXPECT_FALSE(GetNode("out.o")->dirty());
}


text:
/* Written by Jan Brittenson, bson@gnu.ai.mit.edu.  */

#if HAVE_CONFIG_H
# include <config.h>
#endif

/* Specification.  */
#include "getline.h"

#include <stddef.h>
#include <stdio.h>

/* Get ssize_t.  */
#include <sys/types.h>

#if defined __GNU_LIBRARY__ && HAVE_GETDELIM

ssize_t
getline (char **lineptr, size_t *linesize, FILE *stream)
{
  return getdelim (lineptr, linesize, '\n', stream);
}

#else /* ! have getdelim */

# include "getndelim2.h"

ssize_t
getline (char **lineptr, size_t *linesize, FILE *stream)
{
  return getndelim2 (lineptr, linesize, (size_t)(-1), stream, '\n', 0, 0);
}

ssize_t
getdelim (char **lineptr, size_t *linesize, int delimiter, FILE *stream)
{
  return getndelim2 (lineptr, linesize, (size_t)(-1), stream, delimiter, 0, 0);
}
#endif


text:
import React from 'react';
import { HashRouter as Router, Route } from 'react-router-dom';

import Dev from './containers/Dev';
import Test from './containers/Test';
import './stylesheets/styles.scss';

const App = () => (
  <Router basename="/">
    <div>
      <Route exact path="/" render={(props) => <Dev {...props} />} />
      <Route path="/testing" render={(props) => <Test {...props} />} />
    </div>
  </Router>
);

export default App;


text:
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System.Linq;
using System.Reactive.Linq;
using Perspex.Collections;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using Perspex.Controls.Primitives;
using Perspex.Controls.Shapes;
using Perspex.Controls.Templates;
using Perspex.Layout;
using Perspex.Media;
using Perspex.Styling;

namespace Perspex.Themes.Default
{
    using Controls = Controls.Controls;

    /// <summary>
    /// The default style for the <see cref="DropDown"/> control.
    /// </summary>
    public class DropDownStyle : Styles
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DropDownStyle"/> class.
        /// </summary>
        public DropDownStyle()
        {
            AddRange(new[]
            {
                new Style(x => x.OfType<DropDown>())
                {
                    Setters = new[]
                    {
                        new Setter(TemplatedControl.TemplateProperty, new ControlTemplate<DropDown>(Template)),
                        new Setter(TemplatedControl.BorderBrushProperty, new SolidColorBrush(0xff707070)),
                        new Setter(TemplatedControl.BorderThicknessProperty, 2.0),
                        new Setter(Control.FocusAdornerProperty, new FuncTemplate<IControl>(FocusAdornerTemplate)),
                        new Setter(DropDown.HorizontalContentAlignmentProperty, HorizontalAlignment.Center),
                        new Setter(DropDown.VerticalContentAlignmentProperty, VerticalAlignment.Center),
                    },
                },
                new Style(x => x.OfType<DropDown>().Descendent().OfType<ListBoxItem>().Class(":pointerover"))
                {
                    Setters = new[]
                    {
                        new Setter(TemplatedControl.BackgroundProperty, new SolidColorBrush(0xffbee6fd))
                    }
                }
            });
        }

        /// <summary>
        /// The default template for a <see cref="DropDown"/> control's focus adorner.
        /// </summary>
        /// <returns>The root of the instantiated template.</returns>
        public static Control FocusAdornerTemplate()
        {
            return new Rectangle
            {
                Stroke = Brushes.Black,
                StrokeThickness = 1,
                StrokeDashArray = new PerspexList<double>(1, 2),
                Margin = new Thickness(3.5),
            };
        }

        /// <summary>
        /// The default template for a <see cref="DropDown"/> control.
        /// </summary>
        /// <param name="control">The control being styled.</param>
        /// <returns>The root of the instantiated template.</returns>
        public static Control Template(DropDown control)
        {
            Border result = new Border
            {
                [~Border.BackgroundProperty] = control[~TemplatedControl.BackgroundProperty],
                [~Border.BorderBrushProperty] = control[~TemplatedControl.BorderBrushProperty],
                [~Border.BorderThicknessProperty] = control[~TemplatedControl.BorderThicknessProperty],
                Child = new Grid
                {
                    Name = "container",
                    ColumnDefinitions = new ColumnDefinitions
                    {
                        new ColumnDefinition(new GridLength(1, GridUnitType.Star)),
                        new ColumnDefinition(GridLength.Auto),
                    },
                    Children = new Controls
                    {
                        new ContentControl
                        {
                            Name = "contentControl",
                            Margin = new Thickness(3),
                            [~ContentControl.ContentProperty] = control[~DropDown.SelectionBoxItemProperty],
                            [~Layoutable.HorizontalAlignmentProperty] = control[~DropDown.HorizontalContentAlignmentProperty],
                            [~Layoutable.VerticalAlignmentProperty] = control[~DropDown.VerticalContentAlignmentProperty],
                        },
                        new ToggleButton
                        {
                            Name = "toggle",
                            BorderThickness = 0,
                            Background = Brushes.Transparent,
                            ClickMode = ClickMode.Press,
                            Focusable = false,
                            Content = new Path
                            {
                                Name = "checkMark",
                                Fill = Brushes.Black,
                                Width = 8,
                                Height = 4,
                                Stretch = Stretch.Uniform,
                                HorizontalAlignment = HorizontalAlignment.Center,
                                VerticalAlignment = VerticalAlignment.Center,
                                Data = StreamGeometry.Parse("F1 M 301.14,-189.041L 311.57,-189.041L 306.355,-182.942L 301.14,-189.041 Z"),
                                [Grid.ColumnProperty] = 0,
                            },
                            [~~ToggleButton.IsCheckedProperty] = control[~~DropDown.IsDropDownOpenProperty],
                            [Grid.ColumnProperty] = 1,
                        },
                        new Popup
                        {
                            Name = "popup",
                            Child = new Border
                            {
                                BorderBrush = Brushes.Black,
                                BorderThickness = 1,
                                Padding = new Thickness(4),
                                Child = new ItemsPresenter
                                {
                                    MemberSelector = control.MemberSelector,
                                    [~ItemsPresenter.ItemsProperty] = control[~ItemsControl.ItemsProperty],
                                }
                            },
                            PlacementTarget = control,
                            StaysOpen = false,
                            [~~Popup.IsOpenProperty] = control[~~DropDown.IsDropDownOpenProperty],
                            [~Layoutable.MinWidthProperty] = control[~Visual.BoundsProperty].Cast<Rect>().Select(x => (object)x.Width),
                        }
                    },
                },
            };

            return result;
        }
    }
}


text:
<?php

namespace Smartbox\Integration\FrameworkBundle\Components\Queues;

use JMS\Serializer\Annotation as JMS;
use Smartbox\Integration\FrameworkBundle\Configurability\DescriptableInterface;
use Smartbox\Integration\FrameworkBundle\Core\Protocols\Protocol;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Class QueueProtocol.
 */
class QueueProtocol extends Protocol implements DescriptableInterface
{
    /**
     * @JMS\Exclude
     *
     * @var array
     */
    protected static $SUPPORTED_EXCHANGE_PATTERNS = [self::EXCHANGE_PATTERN_IN_ONLY];

    const OPTION_PREFIX = 'prefix';
    const OPTION_PERSISTENT = 'persistent';
    const OPTION_TTL = 'ttl';
    const OPTION_TYPE = 'type';
    const OPTION_PRIORITY = 'priority';
    const OPTION_QUEUE_NAME = 'queue';
    const OPTION_QUEUE_DRIVER = 'queue_driver';

    protected $defaultPersistence;
    protected $defaultTTL;

    public function __construct($defaultPersistence, $defaultTTL)
    {
        $this->defaultPersistence = $defaultPersistence;
        $this->defaultTTL = $defaultTTL;
    }

    /**
     * @return mixed
     */
    public function getDefaultPersistence()
    {
        return $this->defaultPersistence;
    }

    /**
     * @param mixed $defaultPersistence
     */
    public function setDefaultPersistence($defaultPersistence)
    {
        $this->defaultPersistence = $defaultPersistence;
    }

    /**
     * @return mixed
     */
    public function getDefaultTTL()
    {
        return $this->defaultTTL;
    }

    /**
     * @param mixed $defaultTTL
     */
    public function setDefaultTTL($defaultTTL)
    {
        $this->defaultTTL = $defaultTTL;
    }

    protected $defaultOptions = [
    ];

    public function getOptionsDescriptions()
    {
        $options = array_merge(parent::getOptionsDescriptions(), [
            self::OPTION_PREFIX => ['Prefix to prepend to the queue name', []],
            self::OPTION_QUEUE_NAME => ['Name of the queue, e.g: /boxes/pending ', []],
            self::OPTION_QUEUE_DRIVER => ['Queue driver that should be used to talk with tclehe queueing system', []],
            self::OPTION_PRIORITY => ['Priority for the messages in this queue', []],
            self::OPTION_TTL => ['Time to live in seconds, after which the messages will expire', []],
            self::OPTION_PERSISTENT => ['Whether messages coming to this queue should be persisted in disk', []],
        ]);

        unset($options[self::OPTION_USERNAME]);
        unset($options[self::OPTION_PASSWORD]);
        unset($options[self::OPTION_EXCHANGE_PATTERN]);

        return $options;
    }

    /**
     * With this method this class can configure an OptionsResolver that will be used to validate the options.
     *
     * @param OptionsResolver $resolver
     *
     * @return mixed
     */
    public function configureOptionsResolver(OptionsResolver $resolver)
    {
        parent::configureOptionsResolver($resolver);
        $resolver->setDefaults([
            self::OPTION_TTL => $this->defaultTTL,
            self::OPTION_PERSISTENT => $this->defaultPersistence,
            self::OPTION_PRIORITY => 4,
            self::OPTION_EXCHANGE_PATTERN => self::EXCHANGE_PATTERN_IN_ONLY,
            self::OPTION_TRACK => true,
            self::OPTION_PREFIX => '',
        ]);

        $resolver->setRequired([
            self::OPTION_TTL, self::OPTION_PERSISTENT, self::OPTION_PRIORITY, self::OPTION_PREFIX,
            self::OPTION_QUEUE_DRIVER, self::OPTION_QUEUE_NAME,
        ]);

        $resolver->setAllowedTypes(self::OPTION_TTL, ['numeric']);
        $resolver->setAllowedValues(self::OPTION_PERSISTENT, [true, false, 'true', 'false', 0, 1, '0', '1']);
        $resolver->setAllowedTypes(self::OPTION_PERSISTENT, ['numeric', 'string', 'boolean']);
        $resolver->setAllowedTypes(self::OPTION_PRIORITY, ['numeric']);
        $resolver->setAllowedTypes(self::OPTION_PREFIX, ['string']);
        $resolver->setAllowedTypes(self::OPTION_QUEUE_DRIVER, ['string']);
    }

    /**
     * {@inheritdoc}
     */
    public function getDescription()
    {
        return 'Specialized protocol to interact with queuing systems (ActiveMq/STOMP only for now)';
    }
}


text:
package org.apache.harmony.rmi.internal.transport.jrmp;

import org.apache.harmony.rmi.internal.transport.ProtocolException;

/*
 * NOTE:
 * This class has been modified in order to support
 * Java VM 1.4.2 using the javac's target jsr14
 */

/**
 * This Enumerated Type describes the possible Messages received by a RMI
 * Server.
 *
 * @author Gustavo Petri
 *
 */
public class MessageType {

	/**
	 * A 0x50 byte representing a CALL message
	 */
	public final static MessageType CALL = new MessageType((byte) 0x50);

	/**
	 * A 0x52 byte representing a PING message
	 */
    public final static MessageType PING = new MessageType((byte) 0x52);

	/**
	 * A 0x54 byte representing a DGCACK message
	 */
    public final static MessageType DGCACK = new MessageType((byte) 0x54);

	/**
	 * The internal byte value for this enum
	 */
	private byte value;

	/**
	 * Private constructor, sets the internal {@link MessageType#value}
	 *
	 * @param value
	 */
	private MessageType(byte value) {
		this.value = value;
	}

	/**
	 * Getter method which returns the byte value of this enum
	 *
	 * @return the {@link MessageType#value} of this enum
	 */
	final byte getValue() {
		return value;
	}

	/**
	 * Creates a new {@link MessageType}
	 *
	 * @param value
	 *            the byte value of the {@link MessageType}
	 * @return a new {@link MessageType}
	 * @throws ProtocolException
	 *             if the value parameter is not a valid JRMP
	 *             header message type
	 */
	static final MessageType createMessageType(byte value)
			throws ProtocolException {
		if (value == CALL.getValue()) {
			return CALL;
		} else if (value == PING.getValue()) {
			return PING;
		} else if (value == DGCACK.getValue()) {
			return DGCACK;
		} else {
			throw new ProtocolException("Unrecognized Message Header "
					+ Integer.toHexString(value));
		}
	}
}


text:
package com.tle.web.sections.standard.js.impl;

import com.tle.web.sections.events.RenderContext;
import com.tle.web.sections.js.ElementId;
import com.tle.web.sections.js.JSCallable;
import com.tle.web.sections.standard.js.JSTableComponent;

public class DelayedJSTableComponent extends AbstractDelayedJS<JSTableComponent> {
  private JSCallable filterFunction;

  public DelayedJSTableComponent(ElementId id) {
    super(id);
  }

  public JSCallable createFilterFunction() {
    if (filterFunction == null) {
      filterFunction =
          new DelayedFunction<JSTableComponent>(this, "filter", id, 1) // $NON-NLS-1$
          {
            @Override
            protected JSCallable createRealFunction(RenderContext info, JSTableComponent renderer) {
              return renderer.createFilterFunction();
            }
          };
    }
    return filterFunction;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/titlebar_home_icon_pressed" />
    <item android:drawable="@drawable/titlebar_home_icon" />
</selector>


text:
using System.Collections.Generic;

namespace Serialization.Dcs.Inheritance
{
    public class Person : PersonBase
    {
        public Person() { }

        public Person(bool init)
        {
            SimpleString = "Simple String";
            StringCollection = new List<string>
            {
                "Item1", "Item2", "Item3"
            };
        }

        public string Name { get; set; }
    }
}


text:
template<typename CharT>
void test ( const CharT *s ) {
    typedef std::basic_string<CharT> String ;
    {
    std::experimental::basic_string_view<CharT> sv1 ( s );
    String                                      str1 = (String) sv1;

    assert ( sv1.size() == str1.size ());
    assert ( std::char_traits<CharT>::compare ( sv1.data(), str1.data(),  sv1.size()) == 0 );

#if __cplusplus >= 201103L
    auto str2 = sv1.to_string(min_allocator<CharT>());
    assert ( sv1.size() == str2.size ());
    assert ( std::char_traits<CharT>::compare ( sv1.data(), str2.data(), sv1.size()) == 0 );
#endif
    }

    {
    std::experimental::basic_string_view<CharT> sv1;
    String                                      str1 = (String) sv1;

    assert ( sv1.size() == str1.size ());
    assert ( std::char_traits<CharT>::compare ( sv1.data(), str1.data(), sv1.size()) == 0 );

#if __cplusplus >= 201103L
    auto str2 = sv1.to_string(min_allocator<CharT>());
    assert ( sv1.size() == str2.size ());
    assert ( std::char_traits<CharT>::compare ( sv1.data(), str2.data(), sv1.size()) == 0 );
#endif
    }
}

int main () {
    test ( "ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
    test ( "ABCDE");
    test ( "a" );
    test ( "" );

    test ( L"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
    test ( L"ABCDE" );
    test ( L"a" );
    test ( L"" );

#if __cplusplus >= 201103L
    test ( u"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
    test ( u"ABCDE" );
    test ( u"a" );
    test ( u"" );

    test ( U"ABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDEABCDE" );
    test ( U"ABCDE" );
    test ( U"a" );
    test ( U"" );
#endif
}


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

namespace Aspose.Cells.Examples.CSharp.Articles.ManagingWorkbooksWorksheets
{
    public class CheckIfPasswordProtected
    {
        public static void Run()
        {
            // ExStart:CheckIfPasswordProtected
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Create an instance of Workbook and load a spreadsheet
            var book = new Workbook(dataDir + "sample.xlsx");

            // Access the protected Worksheet
            var sheet = book.Worksheets[0];

            // Check if Worksheet is password protected
            if (sheet.Protection.IsProtectedWithPassword)
            {
                Console.WriteLine("Worksheet is password protected");
            }
            else
            {
                Console.WriteLine("Worksheet is not password protected");
            }
            // ExEnd:CheckIfPasswordProtected
        }
    }
}


text:
using System;
using System.Linq;
using FluentAssertions;

namespace SonarScanner.MSBuild.Tasks.IntegrationTest
{
    /// <summary>
    /// Assertion methods that check the content of the custom XML build log
    /// </summary>
    internal static class BuildLogAssertions
    {
        /// <summary>
        /// Checks that building the specified target succeeded.
        /// </summary>
        public static void AssertTargetSucceeded(this BuildLog log, string target)
        {
            AssertTargetExecuted(log, target);
            log.BuildSucceeded.Should().BeTrue();
        }

        /// <summary>
        /// Checks that building the specified target failed.
        /// </summary>
        public static void AssertTargetFailed(this BuildLog log, string target)
        {
            AssertTargetExecuted(log, target);
            log.BuildSucceeded.Should().BeFalse();
        }

        public static void AssertTargetExecuted(this BuildLog log, string targetName)
        {
            var found = log.Targets.FirstOrDefault(t => t.Equals(targetName, StringComparison.InvariantCulture));
            found.Should().NotBeNull("Specified target was not executed: {0}", targetName);
        }

        public static void AssertTargetNotExecuted(this BuildLog log, string targetName)
        {
            var found = log.Targets.FirstOrDefault(t => t.Equals(targetName, StringComparison.InvariantCulture));
            found.Should().BeNull("Not expecting the target to have been executed: {0}", targetName);
        }

        public static void AssertTaskExecuted(this BuildLog log, string taskName) =>
            log.ContainsTask(taskName).Should().BeTrue("Specified task was not executed: {0}", taskName);

        public static void AssertTaskNotExecuted(this BuildLog log, string taskName) =>
            log.ContainsTask(taskName).Should().BeFalse("Not expecting the task to have been executed: {0}", taskName);

        /// <summary>
        /// Checks that the expected tasks were executed in the specified order
        /// </summary>
        public static void AssertTargetOrdering(this BuildLog log, params string[] expected)
        {
            foreach (var target in expected)
            {
                AssertTargetExecuted(log, target);
            }

            var actual = log.Targets.Where(t => expected.Contains(t, StringComparer.Ordinal)).ToArray();

            Console.WriteLine("Expected target order: {0}", string.Join(", ", expected));
            Console.WriteLine("Actual target order: {0}", string.Join(", ", actual));

            actual.Should().BeEquivalentTo(expected, options => options.WithStrictOrdering());
        }

        public static void AssertNoWarningsOrErrors(this BuildLog log)
        {
            AssertErrorCount(log, 0);
            AssertWarningCount(log, 0);
        }

        public static void AssertErrorCount(this BuildLog log, int expected) =>
            log.Errors.Should().HaveCount(expected);

        public static void AssertWarningCount(this BuildLog log, int expected) =>
            log.Warnings.Should().HaveCount(expected);

        public static string GetPropertyValue(this BuildLog log, string propertyName, bool allowMissing = false)
        {
            log.TryGetPropertyValue(propertyName, out var value);
            if (!allowMissing)
            {
                value.Should().NotBeNull($"Test logger error: failed to find captured property '{propertyName}'");
            }
            return value;
        }

        public static void AssertPropertyValue(this BuildLog log, string propertyName, string expectedValue)
        {
            var capturedValue = GetPropertyValue(log, propertyName, expectedValue == null);
            capturedValue.Should().Be(expectedValue, "Captured property '{0}' does not have the expected value", propertyName);
        }

        public static void AssertSingleItemExists(this BuildLog log, string itemName, string expectedValue)
        {
            var data = log.GetItem(itemName).SingleOrDefault(x => x.Text.Equals(expectedValue, StringComparison.Ordinal));
            data.Should().NotBeNull($"Test logger error: Failed to find expected item value. Item name: '{itemName}', expected value: {expectedValue}");
        }

        public static void AssertItemGroupCount(this BuildLog log, string itemName, int expectedCount) =>
            log.GetItem(itemName).Count().Should().Be(expectedCount);
    }
}


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

// clang-format off

#ifndef ROCKETCOREXMLPARSER_H
#define ROCKETCOREXMLPARSER_H

#include <stack>
#include "BaseXMLParser.h"

namespace Rocket {
namespace Core {

class Context;
class DocumentHeader;
class Element;
class XMLNodeHandler;

/**
        Rocket's XML parsing engine. The factory creates an instance of this
   class for each RML parse.

        @author Lloyd Weehuizen
 */

class XMLParser : public BaseXMLParser {
public:
  XMLParser(Context* _context, Element* root);
  ~XMLParser();

  /// Registers a custom node handler to be used to a given tag.
  /// @param[in] tag The tag the custom parser will handle.
  /// @param[in] handler The custom handler.
  /// @return The registered XML node handler.
  static XMLNodeHandler* RegisterNodeHandler(
      Context* _context, const String& tag, XMLNodeHandler* handler);
  /// Releases all registered node handlers. This is called internally.
  static void ReleaseHandlers(Context* _context);

  /// Returns the XML document's header.
  /// @return The document header.
  DocumentHeader* GetDocumentHeader();
  /// Returns the source URL of this parse.
  /// @return The URL of the parsing stream.
  const URL& GetSourceURL() const;

  // The parse stack.
  struct ParseFrame {
    // Tag being parsed.
    String tag;

    // Element representing this frame.
    Element* element;

    // Handler used for this frame.
    XMLNodeHandler* node_handler;

    // The default handler used for this frame's children.
    XMLNodeHandler* child_handler;
  };

  /// Pushes an element handler onto the parse stack for parsing child elements.
  /// @param[in] tag The tag the handler was registered with.
  /// @return True if an appropriate handler was found and pushed onto the
  /// stack, false if not.
  bool PushHandler(const String& tag);
  /// Pushes the default element handler onto the parse stack.
  void PushDefaultHandler();

  /// Access the current parse frame.
  /// @return The parser's current parse frame.
  const ParseFrame* GetParseFrame() const;

  static void RegisterContextValues(Context* _context);

protected:
  /// Called when the parser finds the beginning of an element tag.
  virtual void HandleElementStart(
      const String& name, const XMLAttributes& attributes);
  /// Called when the parser finds the end of an element tag.
  virtual void HandleElementEnd(const String& name);
  /// Called when the parser encounters data.
  virtual void HandleData(const String& data);

private:
  // The header of the document being parsed.
  DocumentHeader* header;

  // The active node handler.
  XMLNodeHandler* active_handler;

  // The parser stack.
  typedef std::stack<ParseFrame> ParserStack;
  ParserStack stack;
};
}  // namespace Core
}  // namespace Rocket

#endif


text:
import declare from 'dojo/_base/declare';
import lang from 'dojo/_base/lang';
import _ModelBase from 'argos/Models/_ModelBase';
import MODEL_NAMES from '../Names';
import getResource from 'argos/I18n';

const resource = getResource('unitOfMeasureModel');

const __class = declare('crm.Integrations.BOE.Models.UnitOfMeasure.Base', [_ModelBase], {
  contractName: 'dynamic',
  resourceKind: 'unitsOfMeasure',
  entityName: 'UnitOfMeasure',
  entityDisplayName: resource.entityDisplayName,
  entityDisplayNamePlural: resource.entityDisplayNamePlural,
  modelName: MODEL_NAMES.UNITOFMEASURE,
  iconClass: 'spreadsheet',
  detailViewId: '',
  listViewId: 'unitofmeasure_list',
  editViewId: '',
  createRelationships: function createRelationships() {
    const rel = this.relationships || (this.relationships = [
    ]);
    return rel;
  },
});
lang.setObject('icboe.Models.UnitOfMeasure.Base', __class);
export default __class;


text:
/**
 * @file logistic_regression_function.cpp
 * @author Sumedh Ghaisas
 *
 * Implementation of the LogisticRegressionFunction class.
 */
#ifndef MLPACK_METHODS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP
#define MLPACK_METHODS_LOGISTIC_REGRESSION_FUNCTION_IMPL_HPP

// In case it hasn't been included yet.
#include "logistic_regression_function.hpp"

namespace mlpack {
namespace regression {

template<typename MatType>
LogisticRegressionFunction<MatType>::LogisticRegressionFunction(
    const MatType& predictors,
    const arma::Row<size_t>& responses,
    const double lambda) :
    predictors(predictors),
    responses(responses),
    lambda(lambda)
{
  initialPoint = arma::zeros<arma::mat>(predictors.n_rows + 1, 1);

  // Sanity check.
  if (responses.n_elem != predictors.n_cols)
    Log::Fatal << "LogisticRegressionFunction::LogisticRegressionFunction(): "
        << "predictors matrix has " << predictors.n_cols << " points, but "
        << "responses vector has " << responses.n_elem << " elements (should be"
        << " " << predictors.n_cols << ")!" << std::endl;
}

template<typename MatType>
LogisticRegressionFunction<MatType>::LogisticRegressionFunction(
    const MatType& predictors,
    const arma::Row<size_t>& responses,
    const arma::vec& initialPoint,
    const double lambda) :
    initialPoint(initialPoint),
    predictors(predictors),
    responses(responses),
    lambda(lambda)
{
  //to check if initialPoint is compatible with predictors
  if (initialPoint.n_rows != (predictors.n_rows + 1) ||
      initialPoint.n_cols != 1)
    this->initialPoint = arma::zeros<arma::mat>(predictors.n_rows + 1, 1);
}

/**
 * Evaluate the logistic regression objective function given the estimated
 * parameters.
 */
template<typename MatType>
double LogisticRegressionFunction<MatType>::Evaluate(
    const arma::mat& parameters) const
{
  // The objective function is the log-likelihood function (w is the parameters
  // vector for the model; y is the responses; x is the predictors; sig() is the
  // sigmoid function):
  //   f(w) = sum(y log(sig(w'x)) + (1 - y) log(sig(1 - w'x))).
  // We want to minimize this function.  L2-regularization is just lambda
  // multiplied by the squared l2-norm of the parameters then divided by two.

  // For the regularization, we ignore the first term, which is the intercept
  // term.
  const double regularization = 0.5 * lambda *
      arma::dot(parameters.col(0).subvec(1, parameters.n_elem - 1),
                parameters.col(0).subvec(1, parameters.n_elem - 1));

  // Calculate vectors of sigmoids.  The intercept term is parameters(0, 0) and
  // does not need to be multiplied by any of the predictors.
  const arma::vec exponents = parameters(0, 0) + predictors.t() *
      parameters.col(0).subvec(1, parameters.n_elem - 1);
  const arma::vec sigmoid = 1.0 / (1.0 + arma::exp(-exponents));

  // Assemble full objective function.  Often the objective function and the
  // regularization as given are divided by the number of features, but this
  // doesn't actually affect the optimization result, so we'll just ignore those
  // terms for computational efficiency.
  double result = 0.0;
  for (size_t i = 0; i < responses.n_elem; ++i)
  {
    if (responses[i] == 1)
      result += log(sigmoid[i]);
    else
      result += log(1.0 - sigmoid[i]);
  }

  // Invert the result, because it's a minimization.
  return -result + regularization;
}

/**
 * Evaluate the logistic regression objective function, but with only one point.
 * This is useful for optimizers that use a separable objective function, such
 * as SGD.
 */
template<typename MatType>
double LogisticRegressionFunction<MatType>::Evaluate(
    const arma::mat& parameters,
    const size_t i) const
{
  // Calculate the regularization term.  We must divide by the number of points,
  // so that sum(Evaluate(parameters, [1:points])) == Evaluate(parameters).
  const double regularization = lambda * (1.0 / (2.0 * predictors.n_cols)) *
      arma::dot(parameters.col(0).subvec(1, parameters.n_elem - 1),
                parameters.col(0).subvec(1, parameters.n_elem - 1));

  // Calculate sigmoid.
  const double exponent = parameters(0, 0) + arma::dot(predictors.col(i),
      parameters.col(0).subvec(1, parameters.n_elem - 1));
  const double sigmoid = 1.0 / (1.0 + std::exp(-exponent));

  if (responses[i] == 1)
    return -log(sigmoid) + regularization;
  else
    return -log(1.0 - sigmoid) + regularization;
}

//! Evaluate the gradient of the logistic regression objective function.
template<typename MatType>
void LogisticRegressionFunction<MatType>::Gradient(
    const arma::mat& parameters,
    arma::mat& gradient) const
{
  // Regularization term.
  arma::mat regularization;
  regularization = lambda * parameters.col(0).subvec(1, parameters.n_elem - 1);

  const arma::rowvec sigmoids = (1 / (1 + arma::exp(-parameters(0, 0)
      - parameters.col(0).subvec(1, parameters.n_elem - 1).t() * predictors)));

  gradient.set_size(parameters.n_elem);
  gradient[0] = -arma::accu(responses - sigmoids);
  gradient.col(0).subvec(1, parameters.n_elem - 1) = -predictors * (responses -
      sigmoids).t() + regularization;
}

/**
 * Evaluate the individual gradients of the logistic regression objective
 * function with respect to individual points.  This is useful for optimizers
 * that use a separable objective function, such as SGD.
 */
template<typename MatType>
void LogisticRegressionFunction<MatType>::Gradient(
    const arma::mat& parameters,
    const size_t i,
    arma::mat& gradient) const
{
  // Calculate the regularization term.
  arma::mat regularization;
  regularization = lambda * parameters.col(0).subvec(1, parameters.n_elem - 1)
      / predictors.n_cols;

  const double sigmoid = 1.0 / (1.0 + std::exp(-parameters(0, 0)
      - arma::dot(predictors.col(i), parameters.col(0).subvec(1,
      parameters.n_elem - 1))));

  gradient.set_size(parameters.n_elem);
  gradient[0] = -(responses[i] - sigmoid);
  gradient.col(0).subvec(1, parameters.n_elem - 1) = -predictors.col(i)
      * (responses[i] - sigmoid) + regularization;
}

} // namespace regression
} // namespace mlpack

#endif


text:
from lib.coloring.coloring.ordering import color_by_ordering, \
     next_free_color, most_used_color, least_used_color

def max_deg(orig, g, trans, frat, col, silent=True):
    undir_g = g.undirected()
    degBuckets = []
    degrees = {}  # Keep track of remaining degree
    maxdegree = 0
    for v in undir_g:
        d = undir_g.degree(v)
        if d >= len(degBuckets):
            degBuckets.extend([set() for x in range(len(degBuckets), d + 1)])
        degBuckets[d].add(v)
        degrees[v] = d
        maxdegree = max(maxdegree, d)

    for d in xrange(0, maxdegree+1):
        if d >= len(degBuckets):
            degBuckets.extend([set() for x in range(len(degBuckets), d + 1)])

    def vchoice(uncolored, coloring, graph):
        maxdeg = maxdegree
        while len(degBuckets[maxdeg]) == 0:
            maxdeg -= 1

        v = degBuckets[maxdeg].pop()

        # Update neighbours
        for w in graph.neighbours(v):
            if w not in degrees or w == v:
                continue  # Was already processed
            deg = degrees[w]
            degBuckets[deg].remove(w)
            degBuckets[deg-1].add(w)
            degrees[w] -= 1

        del degrees[v]
        return v

    return color_by_ordering(undir_g, vchoice, next_free_color)


text:
require 'java'
require 'logger'
require 'json'

$:.unshift(here = File.dirname(__FILE__))

Dir["#{here}/jar/*.jar"].each { |jar| require jar }
require 'lucene/analysis'
require 'lucene/document'
require 'lucene/function'
require 'lucene/index'
require 'lucene/query_parser'
require 'lucene/search'
require 'lucene/store'

require 'moonstone/engine'
require 'moonstone/tokenizer'
require 'moonstone/filter'
require 'moonstone/queued_filter'
require 'moonstone/analyzer'
require 'moonstone/multi_analyzer'
require 'moonstone/index_inspection'

require 'moonstone/filters/synonymer.rb'

require 'moonstone/racker'

Moonstone::Logger = Logger.new($stderr) unless defined? Moonstone::Logger