text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>sparknlp_jsl.legal.chunk_classification.resolution.sentence_entity_resolver — Spark NLP 4.0.0 documentation</title>

  <link href="../../../../../static/styles/theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">
<link href="../../../../../static/styles/pydata-sphinx-theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">

  <link rel="stylesheet"
    href="../../../../../static/vendor/fontawesome/6.1.2/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../../../../static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../static/css/custom.css" />

  <link rel="preload" as="script" href="../../../../../static/scripts/pydata-sphinx-theme.js?digest=1e1de1a1873e13ef5536">

    <link rel="shortcut icon" href="../../../../../static/fav.ico"/>
    <link rel="index" title="Index" href="../../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../../search.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="docsearch:language" content="en">

  <input type="checkbox" class="sidebar-toggle" name="__primary" id="__primary">

  <input type="checkbox" class="sidebar-toggle" name="__secondary" id="__secondary">

<form class="bd-search d-flex align-items-center" action="../../../../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
  Ctrl+K
</form>

        Site Navigation

                        Getting Started

                        API Reference

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

        Site Navigation

                        Getting Started

                        API Reference

Source code for sparknlp_jsl.legal.chunk_classification.resolution.sentence_entity_resolver

from sparknlp_jsl.annotator.resolution.sentence_entity_resolver import SentenceEntityResolverModel as M
from sparknlp_jsl.annotator.resolution.sentence_entity_resolver import SentenceEntityResolverApproach as A
from sparknlp.common import *

[docs]class SentenceEntityResolverApproach(A):
    """Thius class contains all the parameters and methods to train a SentenceEntityResolverModel.
       The model transforms a dataset with Input Annotation type SENTENCE_EMBEDDINGS, coming from e.g.
       [BertSentenceEmbeddings](/docs/en/transformers#bertsentenceembeddings)
       and returns the normalized entity for a particular trained ontology / curated dataset.
       (e.g. ICD-10, RxNorm, SNOMED etc.)

       ========================================= ======================
       Input Annotation types                    Output Annotation type
       ========================================= ======================
       ``SENTENCE_EMBEDDINGS``                    ``ENTITY``
       ========================================= ======================

       Parameters
       ----------
       labelCol
            Column name for the value we are trying to resolve
       normalizedCol
            Column name for the original, normalized description
       pretrainedModelPath
            Path to an already trained SentenceEntityResolverModel, which is used as a starting point for training the new model.
       overrideExistingCodes
            Whether to override the existing codes with new data while continue the training from a pretrained model. Default value is false(keep all the codes).
       returnCosineDistances
            Extract Cosine Distances. TRUE or False
       aux_label_col
            Auxiliary label which maps resolved entities to additional labels
       useAuxLabel
            Use AuxLabel Col or not
       overrideExistingCodes
            Whether to override the codes present in a pretrained model with new codes when the training process begins with a pretrained model
       dropCodesList
            A list of codes in a pretrained model that will be omitted when the training process begins with a pretrained model

       Examples
       --------

       >>> import sparknlp
       >>> from sparknlp.base import *
       >>> from sparknlp.common import *
       >>> from sparknlp.annotator import *
       >>> from sparknlp.training import *
       >>> import sparknlp_jsl
       >>> from sparknlp_jsl.base import *
       >>> from sparknlp_jsl.annotator import *
       >>> from pyspark.ml import Pipeline
       >>> documentAssembler = DocumentAssembler().setInputCol("text").setOutputCol("document")
       >>> sentenceDetector = SentenceDetector().setInputCols(["document"]).setOutputCol("sentence")
       >>> tokenizer = Tokenizer().setInputCols(["sentence"]).setOutputCol("token")
       >>> bertEmbeddings = BertSentenceEmbeddings.pretrained("sent_biobert_pubmed_base_cased") \\
       ...  .setInputCols(["sentence"]) \\
       ...  .setOutputCol("embeddings")
       >>> snomedTrainingPipeline = Pipeline(stages=[
       ...  documentAssembler,
       ...  sentenceDetector,
       ...  bertEmbeddings,
       ... ])
       >>> snomedTrainingModel = snomedTrainingPipeline.fit(data)
       >>> snomedData = snomedTrainingModel.transform(data).cache()
       >>> assertionModel = assertionPipeline.fit(data)
       >>> assertionModel = assertionPipeline.fit(data)

       >>> bertExtractor = SentenceEntityResolverApproach() \\
       ...   .setNeighbours(25) \\
       ...   .setThreshold(1000) \\
       ...   .setInputCols(["bert_embeddings"]) \\
       ...   .setNormalizedCol("normalized_text") \\
       ...   .setLabelCol("label") \\
       ...   .setOutputCol("snomed_code") \\
       ...   .setDistanceFunction("EUCLIDIAN") \\
       ...   .setCaseSensitive(False)

       >>> snomedModel = bertExtractor.fit(snomedData)
       """

    @keyword_only
    def __init__(self):
        AnnotatorApproach.__init__(self,
                                   classname="com.johnsnowlabs.legal.chunk_classification.resolution.SentenceEntityResolverApproach")
        self._setDefault(labelCol="code", normalizedCol="code", distanceFunction="EUCLIDEAN", neighbours=500,
                         threshold=5, missAsEmpty=True, returnCosineDistances=True)

[docs]class SentenceEntityResolverModel(M):
    """Thius class contains all the parameters and methods to train a SentenceEntityResolverModel.
       The model transforms a dataset with Input Annotation type SENTENCE_EMBEDDINGS, coming from e.g.
       [BertSentenceEmbeddings](/docs/en/transformers#bertsentenceembeddings)
       and returns the normalized entity for a particular trained ontology / curated dataset.
       (e.g. ICD-10, RxNorm, SNOMED etc.)

       ========================================= ======================
       Input Annotation types                    Output Annotation type
       ========================================= ======================
       ``SENTENCE_EMBEDDINGS``                   ``ENTITY``
       ========================================= ======================

       Parameters
       ----------
       returnCosineDistances
            Extract Cosine Distances. TRUE or False
       aux_label_col
            Auxiliary label which maps resolved entities to additional labels
       useAuxLabel
            Use AuxLabel Col or not

       searchTree
            Search tree for resolution

       Examples
       --------

       >>> import sparknlp
       >>> from sparknlp.base import *
       >>> from sparknlp.common import *
       >>> from sparknlp.annotator import *
       >>> from sparknlp.training import *
       >>> import sparknlp_jsl
       >>> from sparknlp_jsl.base import *
       >>> from sparknlp_jsl.annotator import *
       >>> from pyspark.ml import Pipeline
       >>> documentAssembler = DocumentAssembler().setInputCol("text").setOutputCol("document")
       >>> sentenceDetector = SentenceDetector().setInputCols(["document"]).setOutputCol("sentence")
       >>> tokenizer = Tokenizer().setInputCols(["sentence"]).setOutputCol("token")
       >>> bertEmbeddings = BertSentenceEmbeddings.pretrained("sent_biobert_pubmed_base_cased") \\
       ...  .setInputCols(["sentence"]) \\
       ...  .setOutputCol("embeddings")
       >>> snomedTrainingPipeline = Pipeline(stages=[
       ...  documentAssembler,
       ...  sentenceDetector,
       ...  bertEmbeddings,
       ... ])
       >>> snomedTrainingModel = snomedTrainingPipeline.fit(data)
       >>> snomedData = snomedTrainingModel.transform(data).cache()
       >>> assertionModel = assertionPipeline.fit(data)
       >>> assertionModel = assertionPipeline.fit(data)

       >>> bertExtractor = SentenceEntityResolverApproach() \\
       ...   .setNeighbours(25) \\
       ...   .setThreshold(1000) \\
       ...   .setInputCols(["bert_embeddings"]) \\
       ...   .setNormalizedCol("normalized_text") \\
       ...   .setLabelCol("label") \\
       ...   .setOutputCol("snomed_code") \\
       ...   .setDistanceFunction("EUCLIDIAN") \\
       ...   .setCaseSensitive(False)

       >>> snomedModel = bertExtractor.fit(snomedData)
       """

[docs]    name = "SentenceEntityResolverModel"

    def __init__(self,
                 classname="com.johnsnowlabs.legal.chunk_classification.resolution.SentenceEntityResolverModel",
                 java_model=None):
        super(SentenceEntityResolverModel, self).__init__(
            classname=classname,
            java_model=java_model
        )

    @staticmethod

[docs]    def pretrained(name, lang="en", remote_loc=None):
        from sparknlp_jsl.pretrained import InternalResourceDownloader
        return InternalResourceDownloader.downloadModel(SentenceEntityResolverModel, name, lang, remote_loc,
                                                        j_dwn='InternalsPythonResourceDownloader')

    © Copyright 2022, John Snow Labs.

Created using Sphinx 5.3.0.


text:
package org.assertj.core.internal.longs;

import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.LongsBaseTest;
import org.junit.Test;
import org.junit.runner.RunWith;

import static java.lang.Math.abs;
import static org.assertj.core.api.Assertions.byLessThan;
import static org.assertj.core.error.ShouldNotBeEqualWithinOffset.shouldNotBeEqual;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;

@RunWith(DataProviderRunner.class)
public class Longs_assertIsNotCloseTo_Test extends LongsBaseTest {

  private static final Long ZERO = 0L;
  private static final Long ONE = 1L;
  private static final Long TWO = 2L;
  private static final Long THREE = 3L;
  private static final Long TEN = 10L;

  @Test
  public void should_fail_if_actual_is_null() {
    thrown.expectAssertionError(actualIsNull());
    longs.assertIsNotCloseTo(someInfo(), null, ONE, byLessThan(ONE));
  }

  @Test(expected = NullPointerException.class)
  public void should_fail_if_expected_value_is_null() {
    longs.assertIsNotCloseTo(someInfo(), ONE, null, byLessThan(ONE));
  }

  @Test(expected = NullPointerException.class)
  public void should_fail_if_offset_is_null() {
    longs.assertIsNotCloseTo(someInfo(), ONE, ZERO, null);
  }

  @Test
  public void should_pass_if_difference_is_greater_than_given_offset() {
    longs.assertIsNotCloseTo(someInfo(), ONE, THREE, byLessThan(ONE));
    longs.assertIsNotCloseTo(someInfo(), ONE, TEN, byLessThan(TWO));
  }

  @Test
  @DataProvider({
      "1, 1, 0",
      "1, 0, 1",
      "-1, 0, 1",
      "-1, -1, 0",
      "-1, 1, 2",
      "0, 9223372036854775807, 9223372036854775807",
      "9223372036854775807, 9223372036854775807, 0",
      "-9223372036854775808, -9223372036854775808, 0"
  })
  public void should_fail_if_difference_is_equal_to_given_offset(Long actual, Long other, Long offset) {
    AssertionInfo info = someInfo();
    try {
      longs.assertIsNotCloseTo(someInfo(), actual, other, byLessThan(offset));
    } catch (AssertionError e) {
      verify(failures).failure(info, shouldNotBeEqual(actual, other, byLessThan(offset), abs(actual - other)));
      return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
  }

  @Test
  public void should_fail_if_actual_is_too_close_to_expected_value() {
    AssertionInfo info = someInfo();
    try {
      longs.assertIsNotCloseTo(info, ONE, TWO, byLessThan(TEN));
    } catch (AssertionError e) {
      verify(failures).failure(info, shouldNotBeEqual(ONE, TWO, byLessThan(TEN), TWO - ONE));
      return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Gets metadata for support form autovalues, validates and returns correctly structured array
 *
 * @return array Array of autovalues for support form
 */
function nm_get_support_autovalues() {
  $meta = NM_get_option('nm_fundraising_settings_support_section_autovalues', 'nm_fundraising_options');

  $return = [];

  if (!empty($meta)) {
    foreach($meta as $index => $autovalues_set) {
      if ($index === 0) {
        $key = 'default';
      } else if (isset($autovalues_set['url_code'])) {
        $key = $autovalues_set['url_code'];
      } else {
        $key = false;
      }

      $values = array(
        isset($autovalues_set['regular_low']) ? $autovalues_set['regular_low'] : null,
        isset($autovalues_set['regular_medium']) ? $autovalues_set['regular_medium'] : null,
        isset($autovalues_set['regular_high']) ? $autovalues_set['regular_high'] : null,
        isset($autovalues_set['oneoff_low']) ? $autovalues_set['oneoff_low'] : null,
        isset($autovalues_set['oneoff_medium']) ? $autovalues_set['oneoff_medium'] : null,
        isset($autovalues_set['oneoff_high']) ? $autovalues_set['oneoff_high'] : null,
      );

      if ($key && count(array_filter($values, 'is_numeric')) === 6) {
        $return[$key] = $values;
      }
    }
  }

  if (count($return) === 0) {
    $return['default'] = array(3, 5, 8, 5, 10, 20);
  }

  return $return;
}

/**
 * Gets contributors on a post and returns an array of post objects, or false if nothing set
 *
 * @param integer $post_id Post ID to check for contributors
 *
 * @return array/Boolean Array of contributor post objects
 */
function get_contributors_array($post_id) {
  $contributors = get_post_meta($post_id, '_cmb_contributors', true);

  if (empty($contributors)) {
    return false;
  }

  $contributors_posts_array = [];

  foreach(explode(',', $contributors) as $contributor_id) {
    $post = get_post($contributor_id);

    if ($post) {
      array_push($contributors_posts_array, $post);
    }
  }

  if (count($contributors_posts_array) === 0) {
    return false;
  }

  return $contributors_posts_array;
}

/**
* Get the category at the show/brand AKA child level. Meaning get the first child of the top level category.
*
* @param integer $post_id Post ID
*
* @return Object/Boolean WP Term object or false if doesn't exist
*/
function get_child_level_child_category($post_id) {
  $categories = get_the_category($post_id);
  $child_categories = array_filter($categories, 'only_child_category_filter');
  $child_categories = array_values($child_categories);

  if (isset($child_categories[0])) {
    return $child_categories[0];
  } else {
    return false;
  }
}

/**
* Get the category at the top level. Should be either Articles, Audio or Video
*
* @param integer $post_id Post ID
*
* @return Object/Boolean WP Term object or false if isnt set
*/
function get_the_top_level_category($post_id) {
  $categories = get_the_category($post_id);
  $top_level_category = array_filter($categories, 'only_top_level_category_filter');

  if (!$top_level_category) { // if there is no top level category set to post
    if ($categories[0]->parent) { // then check the first category set
      $top_level_category = get_category($categories[0]->parent); // and if there is a parent
    }
  } else {
    $top_level_category = array_values($top_level_category); // if there is a top level category
    $top_level_category = $top_level_category[0]; // get the first one (because there should only be one)
  }

  if (!empty($top_level_category)) {
    return $top_level_category;
  } else {
    return false;
  }
}

/**
* Answer the question is this a single post in the articles category?
*
* @return Boolean
*/
function nm_is_single_article() {
  if (!is_single()) { // if not single return straight away
    return false;
  }

  global $post;

  $categories = get_the_terms($post->ID, 'category'); // get the categories for the post

  if (!$categories) {
    return false;
  }

  $found_in_categories = array_filter($categories,
    function ($category) {
      return $category->slug === 'articles';
    }); // check to see if any of the categories returned match the articles slug

  if (count($found_in_categories) > 0) {
    return true; // if articles slug was found return true
  }

  return false;
}

// get and return the first sub category assigned to the post
function get_the_sub_category($postId, $object = false) {
  $categories = get_the_category($postId);

  $child_categories = array_filter($categories, 'only_child_category_filter');
  $child_categories = array_values($child_categories);

  if (isset($child_categories[0])) {
    if ($object) {
      return $child_categories[0];
    } else {
      return $child_categories[0]->name;
    }
  } else {
    return false;
  }
}

// for array_filters

// returns the id from a post object from a WP query
function nm_filter_query_ids($post) {
  return $post->ID;
}

// filters an array of post categories for just top level categories
function only_top_level_category_filter($var) {
  if ($var->category_parent == 0) {
    return true;
  }
}

// filters an array of post categories for just child categories
function only_child_category_filter($var) {
  if ($var->category_parent !== 0) {
    return true;
  }
}

/**
 * Create youtube embed url with consistent parameters
 *
 * Note the option to use the .js-lazy-loaded-youtube-embed utility class on a container with this return value set as data-src in order to lazy load. See Utilities.js module for more.
 *
 * @param string $id Youtube video ID
 * @param boolean $autoplay Set true if the video autoplay function is required (only posible on internal website linking due to browser policy)
 *
 * @return string Valid youtube iframe src url
 */
function generate_youtube_embed_url($id, $autoplay = false) {
  $url = 'https://www.youtube.com/embed/' . $id . '?modestbranding=1&rel=0';

  if ($autoplay) {
    $url .= '&autoplay=1';
  }

  return $url;
}

// obviously it gets related posts and returns a WP Query
function get_related_posts($excluded_ids_array = null, $category_name = null, $number_of_posts = 4) {

  // Check if we are on a single page, if not, return false
  if (!is_single())  {
    return false;
  }

  // Get the current post id
  $post_id = get_queried_object_id();

  // Get all the tags of the current post
  $tags = wp_get_post_tags($post_id);

  // Exlude this post and possibly others if parsed as variable
  $posts_not_in[] = $post_id;

  if ($excluded_ids_array) {
    $posts_not_in = array_merge($posts_not_in, $excluded_ids_array);
  }

  $args = array(
    'post__not_in' => $posts_not_in,
    'posts_per_page' => $number_of_posts,
  );

  if ($category_name) {
    $args['category_name'] = $category_name;
  }

  if ($tags) {

    $tag_ids = array();

    //Get the id of every tag and add it to the array
    foreach( $tags as $individual_tag ) {
      $tag_ids[] = $individual_tag->term_id;
    }

    //args for the query which will get the related posts
    $args = array_merge($args, array(
      'tag__in' => $tag_ids,
      'order' => 'DESC',
      'orderby' => 'post_date',
    ));

  }

  return new WP_Query($args);
}

// for site options. Returns array for select
function home_focus_list() {

  $focuses = array(
    null => 'No Focus Shown',
  );

  $focus_terms = get_terms(array(
    'taxonomy' => 'focus',
  ));

  if ($focus_terms) {
    foreach($focus_terms as $term) {
      $focuses[$term->term_id] = $term->name;
    }

  }

  return $focuses;

}

function menu_tags_list() {

  $tags = array();

  $tags_all = get_terms(array(
    'taxonomy' => 'post_tag',
  ));

  if ($tags_all) {
    foreach($tags_all as $tag) {
      $tags[$tag->term_id] = $tag->name;
    }

  }

  return $tags;

}


text:
import gulp from 'gulp';
import {path, tasks} from './const';

gulp.task(tasks.CLIENT_COPY, () => {
  return gulp.src(path.DEV + '**/*')
             .pipe(gulp.dest(path.DIST));
});


text:
package com.s24.wiki;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.jhu.nlp.wikipedia.WikiPage;

public class GermanGrammarPageParser extends GermanPageParser {

   public GermanGrammarPageParser(PageParserCallback cb) {
      super(cb);
   }

   @Override
   public void parse(WikiPage page) {

      if (isValidPage(page)) {
         Pattern pattern = Pattern.compile("\\{\\{.*\\n(\\|.*\\n){8}");
         Matcher matcher = pattern.matcher(page.getWikiText());
         List<String> left = new ArrayList<String>();
         List<String> right = new ArrayList<String>();
         left.add(page.getTitle().trim().toLowerCase());
         right.add(page.getTitle().trim().toLowerCase());

         if (matcher.find()) {

            Pattern wordpattern = Pattern.compile("\\|[NGDA][a-zA-Z\\s]+=.*?\\s(\\p{Upper}[\\p{L}]+)");
            Matcher wordmatcher = wordpattern.matcher(matcher.group());
            int end = 0;

            while (wordmatcher.find(end)) {
               String item = wordmatcher.group(1).toLowerCase();
               if (!left.contains(item)) {
                  left.add(item);
               }

               end = wordmatcher.end();
            }

         }

         callback.callback(left, right);
      }

   }

   @Override
   protected String getName() {
      return "Übersicht";
   }

}


text:
<!doctype html>

  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>toolbarmenubuttonrenderer.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <meta charset="utf8">

      Closure Library API Documentation

        Go to class or file:
        <input type="text" id="ac">

toolbarmenubuttonrenderer.js

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Copyright 2008 Google Inc. All Rights Reserved.

/**
 * @fileoverview A toolbar menu button renderer.
 *
 */

goog.provide('goog.ui.ToolbarMenuButtonRenderer');

goog.require('goog.ui.MenuButtonRenderer');

/**
 * Toolbar-specific renderer for {@link goog.ui.MenuButton}s, based on {@link
 * goog.ui.MenuButtonRenderer}.
 * @constructor
 * @extends {goog.ui.MenuButtonRenderer}
 */
goog.ui.ToolbarMenuButtonRenderer = function() {
  goog.ui.MenuButtonRenderer.call(this);
};
goog.inherits(goog.ui.ToolbarMenuButtonRenderer, goog.ui.MenuButtonRenderer);
goog.addSingletonGetter(goog.ui.ToolbarMenuButtonRenderer);

/**
 * Default CSS class to be applied to the root element of menu buttons rendered
 * by this renderer.
 * @type {string}
 */
goog.ui.ToolbarMenuButtonRenderer.CSS_CLASS = 'goog-toolbar-menu-button';

/**
 * Returns the CSS class to be applied to the root element of menu buttons
 * rendered using this renderer.
 * @return {string} Renderer-specific CSS class.
 */
goog.ui.ToolbarMenuButtonRenderer.prototype.getCssClass = function() {
  return goog.ui.ToolbarMenuButtonRenderer.CSS_CLASS;
};


text:
package org.kuali.rice.krad.labs.kitchensink;

import org.kuali.rice.testtools.common.JiraAwareFailable;
import org.openqa.selenium.By;

/**
 * Tests the Component section in Rice.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public abstract class UifTooltipAftBase extends LabsKitchenSinkBase {

    /**
     * /kr-krad/uicomponents?viewId=UifCompView&methodToCall=start&pageId=UifCompView-Page10
     */
    public static final String BOOKMARK_URL = "/kr-krad/uicomponents?viewId=UifCompView&methodToCall=start&pageId=UifCompView-Page10";

    private static final String NAME_FIELD_1 = "field1";
    private static final String NAME_FIELD_2 = "field2";

    @Override
    protected String getBookmarkUrl() {
        return BOOKMARK_URL;
    }

    protected void navigation() throws Exception {
        navigateToKitchenSink("Other Examples");
    }

    protected void testUifTooltipByName(String nameField1, String nameField2) throws Exception {
        findElement(By.name(nameField2)); // fields must be in view for tooltips to be displayed

        // check if tooltip opens on focus
        fireEvent(nameField1, "focus");
        fireMouseOverEventByName(nameField1);

        String tooltipContents = waitForToolTipPresent().getText();
        assertEquals("This tooltip is triggered by focus or and mouse over.", tooltipContents);
        fireEvent(nameField1, "blur");

        fireEvent(nameField2, "focus");
        Thread.sleep(5000);

        // check if tooltip opens on mouse over
        fireMouseOverEventByName(nameField2);
        assertFalse("unable to detect tooltip", isVisibleByXpath("//td[contains(.,\"This is a tool-tip with different position and tail options\")]"));

        // check if tooltip closed on mouse out of nameField2
        fireEvent(nameField2, "blur");
        fireMouseOverEventByName(nameField1);
        waitAndTypeByName(nameField1, "");
        Thread.sleep(5000);
        assertFalse("able to detect tooltip", isVisibleByXpath(
                "//td[contains(.,\"This is a tool-tip with different position and tail options\")]"));

        // check that default tooltip does not display when there are an error message on the field
        waitAndTypeByName(nameField1, "1");
        fireEvent(nameField1, "blur");
        fireMouseOverEventByName(nameField1);
        Thread.sleep(10000);
    }

    protected void testUifTooltipNav(JiraAwareFailable failable) throws Exception {
        navigation();
        testUifTooltipByName(NAME_FIELD_1, NAME_FIELD_2);
        passed();
    }

    protected void testUifTooltipBookmark(JiraAwareFailable failable) throws Exception {
        testUifTooltipByName(NAME_FIELD_1, NAME_FIELD_2);
        passed();
    }
}


text:
package cache

import (
	"bytes"
	"compress/gzip"
	"encoding/gob"
	"fmt"
	"net/http"
	"time"

	"appengine"
	"appengine/memcache"
)

// TimeKey specifies the memcache entity that keeps the logical datastore time.
var TimeKey = "cachetime"

const (
	nocache = "nocache"
	expiry  = 10 * time.Minute
)

func newTime() uint64 { return uint64(time.Now().Unix()) << 32 }

// Now returns the current logical datastore time to use for cache lookups.
func Now(c appengine.Context) uint64 {
	t, err := memcache.Increment(c, TimeKey, 0, newTime())
	if err != nil {
		c.Errorf("cache.Now: %v", err)
		return 0
	}
	return t
}

// Tick sets the current logical datastore time to a never-before-used time
// and returns that time. It should be called to invalidate the cache.
func Tick(c appengine.Context) uint64 {
	t, err := memcache.Increment(c, TimeKey, 1, newTime())
	if err != nil {
		c.Errorf("cache.Tick: %v", err)
		return 0
	}
	return t
}

// Get fetches data for name at time now from memcache and unmarshals it into
// value. It reports whether it found the cache record and logs any errors to
// the admin console.
func Get(c appengine.Context, r *http.Request, now uint64, name string, value interface{}) bool {
	if now == 0 || r.FormValue(nocache) != "" {
		return false
	}
	key := fmt.Sprintf("%s.%d", name, now)
	_, err := gzipGobCodec.Get(c, key, value)
	if err == nil {
		c.Debugf("cache hit %q", key)
		return true
	}
	c.Debugf("cache miss %q", key)
	if err != memcache.ErrCacheMiss {
		c.Errorf("get cache %q: %v", key, err)
	}
	return false
}

// Set puts value into memcache under name at time now.
// It logs any errors to the admin console.
func Set(c appengine.Context, r *http.Request, now uint64, name string, value interface{}) {
	if now == 0 || r.FormValue(nocache) != "" {
		return
	}
	key := fmt.Sprintf("%s.%d", name, now)
	err := gzipGobCodec.Set(c, &memcache.Item{
		Key:        key,
		Object:     value,
		Expiration: expiry,
	})
	if err != nil {
		c.Errorf("set cache %q: %v", key, err)
	}
}

var gzipGobCodec = memcache.Codec{Marshal: marshal, Unmarshal: unmarshal}

func marshal(v interface{}) ([]byte, error) {
	var b bytes.Buffer
	zw := gzip.NewWriter(&b)
	if err := gob.NewEncoder(zw).Encode(v); err != nil {
		return nil, err
	}
	if err := zw.Close(); err != nil {
		return nil, err
	}
	return b.Bytes(), nil
}

func unmarshal(b []byte, v interface{}) error {
	zr, err := gzip.NewReader(bytes.NewReader(b))
	if err != nil {
		return err
	}
	return gob.NewDecoder(zr).Decode(v)
}


text:
float Sin(float degree)
{
	return sin(degree/180);
}

float Cos(float degree)
{
	return cos(degree/180);
}

float Tan(float degree)
{
	return tan(degree/180);
}


text:
module Shoulda
  module Matchers
    module ActiveModel
      module NumericalityMatchers
        # @private
        class Submatchers
          def initialize(submatchers)
            @submatchers = submatchers
          end

          def matches?(subject)
            @subject = subject
            failing_submatchers.empty?
          end

          def failure_message
            last_failing_submatcher.failure_message
          end

          def failure_message_when_negated
            last_failing_submatcher.failure_message_when_negated
          end

          def add(submatcher)
            @submatchers << submatcher
          end

          def last_failing_submatcher
            failing_submatchers.last
          end

          private

          def failing_submatchers
            @_failing_submatchers ||= @submatchers.reject do |submatcher|
              submatcher.matches?(@subject)
            end
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveRecord::RecordInvalid</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.0.0

            Class
            ActiveRecord::RecordInvalid

                <

                    ActiveRecord::ActiveRecordError

/home/jude/.gem/ruby/2.0.0/gems/activerecord-4.0.0/lib/active_record/validations.rb

Active Record RecordInvalid

Raised by save! and create! when the record is
invalid. Use the record method to retrieve the record which
did not validate.

begin
  complex_operation_that_calls_save!_internally
rescue ActiveRecord::RecordInvalid => invalid
  puts invalid.record.errors
end


text:
package bearertoken

import (
	"errors"
	"net/http"
	"strings"

	"k8s.io/apiserver/pkg/authentication/authenticator"
	"k8s.io/apiserver/pkg/authentication/user"
)

type Authenticator struct {
	auth authenticator.Token
}

func New(auth authenticator.Token) *Authenticator {
	return &Authenticator{auth}
}

var invalidToken = errors.New("invalid bearer token")

func (a *Authenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {
	auth := strings.TrimSpace(req.Header.Get("Authorization"))
	if auth == "" {
		return nil, false, nil
	}
	parts := strings.Split(auth, " ")
	if len(parts) < 2 || strings.ToLower(parts[0]) != "bearer" {
		return nil, false, nil
	}

	token := parts[1]

	// Empty bearer tokens aren't valid
	if len(token) == 0 {
		return nil, false, nil
	}

	user, ok, err := a.auth.AuthenticateToken(token)
	// if we authenticated successfully, go ahead and remove the bearer token so that no one
	// is ever tempted to use it inside of the API server
	if ok {
		req.Header.Del("Authorization")
	}

	// If the token authenticator didn't error, provide a default error
	if !ok && err == nil {
		err = invalidToken
	}

	return user, ok, err
}


text:
package org.apache.flink.streaming.api.functions.sink;

import org.apache.flink.annotation.PublicEvolving;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * Writes tuples in csv format.
 *
 * @param <IN>
 *            Input tuple type
 *
 * @deprecated Please use the {@link org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink StreamingFileSink}
 * for writing to files from a streaming program.
 */
@PublicEvolving
@Deprecated
public class WriteFormatAsCsv<IN> extends WriteFormat<IN> {
	private static final long serialVersionUID = 1L;

	@Override
	protected void write(String path, ArrayList<IN> tupleList) {
		try (PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(path, true)))) {
			for (IN tupleToWrite : tupleList) {
				String strTuple = tupleToWrite.toString();
				outStream.println(strTuple.substring(1, strTuple.length() - 1));
			}
		} catch (IOException e) {
			throw new RuntimeException("Exception occured while writing file " + path, e);
		}
	}

}


text:
An easy way to create an Ember class from a ES6 one, through the use of [Ember.Mixin](http://emberjs.com/api/classes/Ember.Mixin.html)

## Usage

### Basic

```javascript
import Ember from 'ember';
import mixinify from 'ember-mixinify-class';

class MyBabelClass {
  get foo() {
    return 'Properties are accessible...';
  }
  bar() {
    return '...and functions are ported over.';
  }
}

const EmberClass = Ember.Object.extend(mixinify(MyBabelClass));

const obj = EmberClass.create();
obj.get('foo'); // -> 'Properties are accessible...'
obj.bar();      // -> '...and functions are ported over.'
```

### Extending and Overwriting the Class

```javascript
// Assuming class and imports above are available

const ExtendedEmberClass = Ember.Object.extend(mixinify(MyBabelClass), {
  foo: 'Properties can be overwritten...',
  bar() {
    return '...as can functions...';
  },
  buzz() {
    return '...and you can easily extend the default behavior';
  }
});

const obj = ExtendedEmberClass.create();
obj.get('foo'); // -> 'Properties can be overwritten...'
obj.bar();      // -> '...as can functions...'
obj.buzz();     // -> '..and you can easily extend the default behavior'
```

These examples and more can be found in the tests included in this repository.

## Limitations

Currently, there's no way to access the constructor for an ES6 class and call it like a function.  Because of this, it's not really possible to apply the constructor of the ES6 class to the Ember class being created.  I'll be looking into whether there's any way to get around that, but for now, **the constructor for the ES6 class is not called**.

## Compatibility

This addon doesn't work on IE versions lower than 9 due to use of [`Object.getOwnPropertyNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames) API.

## Installation

### As an addon

```bash
ember install ember-mixinify-class
```

### For development

* `git clone` this repository
* `npm install`
* `bower install`

## Running

* `ember server`
* Visit your app at http://localhost:4200.

## Running Tests

* `npm test` (Runs `ember try:testall` to test your addon against multiple Ember versions)
* `ember test`
* `ember test --server`

## Building

* `ember build`

For more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).


text:
/** @constructor */
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = (function() {
  ScalaJS.c.scala_runtime_AbstractFunction1.call(this)
});
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype = new ScalaJS.inheritable.scala_runtime_AbstractFunction1();
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype.constructor = ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2;
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype.apply__Lscala_Tuple2__Lscala_Tuple2 = (function(x0$1) {
  var x1 = x0$1;
  if ((x1 !== null)) {
    var k = ScalaJS.as.scala_util_regexp_WordExp$Label(x1.$$und1__O());
    var v = ScalaJS.as.scala_collection_immutable_List(x1.$$und2__O());
    return ScalaJS.modules.scala_Predef$ArrowAssoc().$$minus$greater$extension__O__O__Lscala_Tuple2(ScalaJS.modules.scala_Predef().any2ArrowAssoc__O__O(k), ScalaJS.modules.scala_collection_immutable_BitSet().apply__Lscala_collection_Seq__Lscala_collection_BitSet(v))
  };
  throw new ScalaJS.c.scala_MatchError().init___O(x1)
});
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype.apply__O__O = (function(v1) {
  return this.apply__Lscala_Tuple2__Lscala_Tuple2(ScalaJS.as.scala_Tuple2(v1))
});
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype.init___Lscala_util_automata_WordBerrySethi$$anonfun$3 = (function($$outer) {
  ScalaJS.c.scala_runtime_AbstractFunction1.prototype.init___.call(this);
  return this
});
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype.apply__Lscala_Tuple2__ = (function(x0$1) {
  return this.apply__Lscala_Tuple2__Lscala_Tuple2(x0$1)
});
/** @constructor */
ScalaJS.inheritable.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = (function() {
  /*<skip>*/
});
ScalaJS.inheritable.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype = ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype;
ScalaJS.is.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = (function(obj) {
  return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2)))
});
ScalaJS.as.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = (function(obj) {
  if ((ScalaJS.is.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2(obj) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwClassCastException(obj, "scala.util.automata.WordBerrySethi$$anonfun$3$$anonfun$apply$2")
  }
});
ScalaJS.isArrayOf.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = (function(obj, depth) {
  return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2)))
});
ScalaJS.asArrayOf.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = (function(obj, depth) {
  if ((ScalaJS.isArrayOf.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2(obj, depth) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwArrayCastException(obj, "Lscala.util.automata.WordBerrySethi$$anonfun$3$$anonfun$apply$2;", depth)
  }
});
ScalaJS.data.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2 = new ScalaJS.ClassTypeData({
  scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2: 0
}, false, "scala.util.automata.WordBerrySethi$$anonfun$3$$anonfun$apply$2", ScalaJS.data.scala_runtime_AbstractFunction1, {
  scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2: 1,
  scala_Serializable: 1,
  java_io_Serializable: 1,
  scala_runtime_AbstractFunction1: 1,
  scala_Function1: 1,
  java_lang_Object: 1
});
ScalaJS.c.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2.prototype.$classData = ScalaJS.data.scala_util_automata_WordBerrySethi$$anonfun$3$$anonfun$apply$2;
//@ sourceMappingURL=WordBerrySethi$$anonfun$3$$anonfun$apply$2.js.map


text:
package com.googlecode.japi.checker.rules;

import com.googlecode.japi.checker.Reporter;
import com.googlecode.japi.checker.Rule;
import com.googlecode.japi.checker.Severity;
import com.googlecode.japi.checker.Reporter.Report;
import com.googlecode.japi.checker.model.ClassData;
import com.googlecode.japi.checker.model.JavaItem;

public class CheckInheritanceChanges implements Rule {

    private static final String JAVA_LANG_OBJECT_NAME = "java/lang/Object";

    @Override
    public void checkBackwardCompatibility(Reporter reporter,
            JavaItem reference, JavaItem newItem) {
        if (reference instanceof ClassData) {
            // Check extends...
            if (!doesExtend((ClassData)newItem, ((ClassData) reference).getSuperName())) {
                reporter.report(new Report(Severity.ERROR, reference.getName() + " extends " + ((ClassData) newItem).getSuperName() +
                        " and not " + ((ClassData) reference).getSuperName() + " anymore.", reference, newItem));
            }
            // Check interfaces
            for (String ifaceRef : ((ClassData) reference).getInterfaces()) {
                if (!hasInterface((ClassData)newItem, ifaceRef)) {
                    reporter.report(new Report(Severity.ERROR, reference.getName() + " is not implementing " + ifaceRef + " anymore.", reference, newItem));
                }
            }
        }
    }

    private boolean doesExtend(ClassData newItem, String superClassName)
    {
        if (newItem == null)
        {
            return false;
        }
        else if (newItem.getSuperName().equals(superClassName))
        {
            return true;
        }
        else if (!newItem.getSuperName().equals(JAVA_LANG_OBJECT_NAME))
        {
            return doesExtend(newItem.getClassDataLoader().fromName(newItem.getSuperName()), superClassName);
        }
        else
        {
            return false;
        }
    }

    private boolean hasInterface(ClassData newItem, String ifaceRef)
    {
        if (newItem == null)
        {
            return false;
        }
        else if (newItem.getInterfaces().contains(ifaceRef))
        {
            return true;
        }
        else if (!newItem.getSuperName().equals(JAVA_LANG_OBJECT_NAME))
        {
            return hasInterface(newItem.getClassDataLoader().fromName(newItem.getSuperName()), ifaceRef);
        }
        else
        {
            return false;
        }
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>FTCAndroidLibrary: com.lasarobotics.library.doodle.maps.DoodleMap Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

FTCAndroidLibrary

Main Page

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

com

lasarobotics

library

doodle

maps

DoodleMap

Classes |
Public Member Functions |
Protected Member Functions |
List of all members

com.lasarobotics.library.doodle.maps.DoodleMap Class Referenceabstract

Classes

enum  	RangeOfMotion

Public Member Functions

abstract void 	move (float amplitude, float rotation, float translation)

void 	update (HardwareMap map)

void 	move (float amplitude)

void 	move (float amplitude, float rotation)

void 	move (float amplitude, Float translation)

Protected Member Functions

 	DoodleMap (HardwareMap map, RangeOfMotion rangeOfMotion)

Detailed Description

Maps robot movement to specific motors

The documentation for this class was generated from the following file:

ftc-library/src/main/java/com/lasarobotics/library/doodle/maps/DoodleMap.java

<address class="footer">
Generated by

 1.8.10
</address>


text:
package org.apache.maven.plugin.idea;

import org.dom4j.Document;
import org.dom4j.Element;

import java.util.List;

/**
 * @author Edwin Punzalan
 */
public class IdeaProjectTest
    extends AbstractIdeaTestCase
{
    public void testIdeaProjectTestEnvironment()
        throws Exception
    {
        Document iprDocument = executeMojo( "src/test/project-plugin-configs/min-plugin-config.xml" );

        testJdkName( iprDocument, null, null );
    }

    public void testIdeaProjectVersion4()
        throws Exception
    {
        Document iprDocument = executeMojo( "src/test/project-plugin-configs/plugin-config-idea4.xml" );

        Element root = iprDocument.getRootElement();

        Element component = findComponent( root, "ProjectRootManager" );

        String jdkName = component.attributeValue( "project-jdk-name" );

        String javaVersion = System.getProperty( "java.version" );

        assertEquals( "Default jdkName should be from System.Properties",
                      jdkName, "java version "" + javaVersion + """ );

        component = findComponent( root, "CompilerConfiguration" );

        Element patterns = findElementByNameAttribute( component, "wildcardResourcePatterns", null );

        findElementByNameAttribute( patterns, "entry", "!?*.java" );
    }

    public void testIdeaProjectJdk11()
        throws Exception
    {
        Document iprDocument = executeMojo( "src/test/project-plugin-configs/plugin-config-jdk11.xml" );

        testJdkName( iprDocument, "1.1", "java version 1.1" );
    }

    public void testIdeaProjectJdk15()
        throws Exception
    {
        Document iprDocument = executeMojo( "src/test/project-plugin-configs/plugin-config-jdk15.xml" );

        testJdkName( iprDocument, "1.5", "java version 1.5" );
    }

    public void testIdeaProjectWithModules()
        throws Exception
    {
        Document iprDocument = executeMojo( "src/test/project-plugin-configs/plugin-config-modules.xml" );

        Element component = findComponent( iprDocument.getRootElement(), "ProjectModuleManager" );

        Element el = findElementByNameAttribute( component, "modules", null );

        List modules = findElementsByName( el, "module" );

        assertEquals( "Must have 4 modules", 4, modules.size() );

        el = (Element) modules.get( 0 );
        assertEquals( "Test project module",
                      "$PROJECT_DIR$/plugin-test-p-mod.iml",
                      el.attributeValue( "filepath" ) );

        el = (Element) modules.get( 1 );
        assertEquals( "Test module 1",
                      "$PROJECT_DIR$/module-1/module-1.iml",
                      el.attributeValue( "filepath" ) );

        el = (Element) modules.get( 2 );
        assertEquals( "Test module 2",
                      "$PROJECT_DIR$/module-2/module-2.iml",
                      el.attributeValue( "filepath" ) );

        el = (Element) modules.get( 3 );
        assertEquals( "Test module 3",
                      "$PROJECT_DIR$/module-3/module-3.iml",
                      el.attributeValue( "filepath" ) );
    }

    private void testJdkName( Document document, String jdkLevel, String expected )
        throws Exception
    {
        Element root = document.getRootElement();

        Element component = findComponent( root, "ProjectRootManager" );

        String jdkName = component.attributeValue( "project-jdk-name" );

        if ( jdkLevel == null )
        {
            jdkLevel = System.getProperty( "java.specification.version" );
        }

        if ( jdkLevel.startsWith( "1.4" ) )
        {
            assertEquals( "assert-keyword must be true for jdk 1.4",
                          "true", component.attributeValue( "assert-keyword" ) );

            assertEquals( "jdk-15 must be false for jdk 1.4",
                          "false", component.attributeValue( "jdk-15") );
        }
        else if ( jdkLevel.compareTo( "1.5" ) >= 0 )
        {
            assertEquals( "assert-keyword must be true for jdk >= 1.5",
                          "true", component.attributeValue( "assert-keyword" ) );

            assertEquals( "jdk-15 must be true for jdk >= 1.5",
                          "true", component.attributeValue( "jdk-15") );
        }
        else
        {
            assertEquals( "assert-keyword must be true for jdk >= 1.5",
                          "false", component.attributeValue( "assert-keyword" ) );
        }

        if ( expected != null )
        {
            assertEquals( "Expected jdkName test", jdkName, expected );
        }
    }

    protected Document executeMojo( String pluginXml )
        throws Exception
    {
        return super.executeMojo( "project", pluginXml, "ipr" );
    }
}


text:
'''modules for use in unit testing'''

from modules.base import Automatia, CannotAutomateException
from modules.orchestra import OrchestraAutomatia, OrchestraMetadataAutomatia

class TestModule(Automatia):
	'''Test item automation model
	Successfuly automates a specific item
	'''
	can_handle = ('TestModuleItem',)

	def do_magic(self):
		return  # Returning nothing is fine. The item will still succeed

class TestModuleUnimplemented(Automatia):
	'''Test item automation model

	Raises NotImplementedError when mudpuppy tries to call do_magic
	'''
	can_handle = ('TestUnimplementedModuleItem',)

class TestAlwaysAutomates(Automatia):
	'''Test item that always automates anything it sees
	also adds stuff to both the task metadata and the state metadata
	'''
	@classmethod
	def can_automate_item(cls, item_state, task_metadata):
		return True

	def do_magic(self):
		itemstuff = { 'guess what': ['TestAlwaysAutomates was here', {'fish': 'are cool'}], 'foo': 'bar' }
		taskstuff = { 'TestAlwaysAutomates last touched': self.item_state['name'] }
		return dict( task_metadata_update=taskstuff, item_metadata_update=itemstuff )

class TestFakeIP(Automatia):
	'''Test item automation model to add task metadata
	Adds a dummy IP address to the task metadata
	'''
	can_handle = ('TestFakeIPitem',)

	def do_magic(self):
		return dict( task_metadata_update={'ip': '10.0.0.1'} )

class TestCannotAutomate(Automatia):
	can_handle = ('TestCannotAutomate item',)
	def do_magic(self):
		nyan = "NYAN NYAN NYAN NYAN NYAN NYAN NYAN NYAN NYAN"
		raise CannotAutomateException(nyan)

class TestOrchestraBad(OrchestraAutomatia):
	can_handle = ('TestOrchestraBadItem',)

class TestOrchestra(OrchestraAutomatia):
	can_handle = ('TestOrchestraItem',)
	score_name = 'helloworld'

class TestOrchestraMetadata(OrchestraMetadataAutomatia):
	can_handle = ('TestOrchestraMetadataItem',)

	# echo score returns score args passed with ORC_ prepended to the key names
	score_name = 'echo'

	# get return variables from orchestra and put into into task metadata keys
	orchestra_response_map = { 'ORC_fish': "fish", "ORC_foo": "taskfoo" }
	score_args = { 'fish':'heads', 'foo':'bar' }


text:
layout: front
title: Valores, visión y política de calidad
description: Conoce nuestros valores, nuestra visión y nuestro compromiso con la calidad
---

Política de calidad

Declaramos la implantación, el mantenimiento y la mejora del sistema de gestión de calidad como objetivo
        estratégico y prioritario

Solidez económica y financiera

Para mantenerse en el tiempo y evolucionar se ha de garantizar una viabilidad
            económica que resulte rentable, y eso va muy ligado a la solidez en el mercado en el que nos movemos

Calidad y mejora continua

Una de nuestras máximas principales es la calidad. Y entendemos por calidad el
            ánimo de "hacer las cosas bien a la primera". Pero además de hacerlas bien, las queremos hacerlas
            cada vez mejor, en un proceso de mejora continua

Desarrollo de mercados y soluciones

Un signo distintivo que deseamos tener es la sensibilidad y orientación al cliente.
            Necesitamos conocer su opinión y qué aspectos de mejora podemos trabajar para estar lo más cerca de él
            que sea posible

Capital humano

Es de vital importancia para nosotros, que basamos nuestro éxito en la calidad,
            disponer de un equipo de personas con el máximo talento, motivado y fiel

Nuestra misión

              "Ofrecer las mejores y más competitivas soluciones de calidad, tanto para el desarrollo de
                software como para la gestión de procesos, a nuestros clientes,
                con el fin de acompañarlos activamente en su camino de mejora continua".

Nuestra visión

              "Llegar a ser una referencia singular y
                reconocida en el ámbito de la gestión de la calidad del software y de los procesos,
                con una ejecución impecable y un prestigio incuestionable"

Nuestros valores

Simplicidad y transparencia

Hacemos las cosas de manera sencilla, simple, eliminando aspectos superfluos y complejidades. La "transparencia" elimina ambigüedades y malentendidos.

Calidad y metodología

Nos adaptamos a los cambios impulsando metodologías ágiles, que permiten alcanzar un altísimo grado de calidad y confianza en lo que hacemos.

Innovación y mejora continua

Vemos las cosas de forma distinta. Nos "reinventamos" una y otra vez y ofrecer los mejores productos y servicios.

Equipo

Es fundamental que el equipo humano se encuentre motivado cada día, se sienta implicado en lo que hace, con el resto de compañeros y con la compañía.

Bienestar, ilusión y diversión

Nos divertirnos con lo que hacemos, lo hacemos con ilusión y pasión.

El cliente

Somos una compañía cercana, con una toma de decisiones eficaz y eficiente y con una gran empatía y sensibilidad con sus clientes y sus problemas.


text:
namespace xcdat {

class save_visitor {
  private:
    std::ofstream m_ofs;

  public:
    save_visitor(const std::string& filepath) : m_ofs(filepath, std::ios::binary) {
        XCDAT_THROW_IF(!m_ofs.good(), "Cannot open the input file");
    }

    virtual ~save_visitor() {
        m_ofs.close();
    }

    template <typename T>
    void visit(const immutable_vector<T>& vec) {
        vec.save(m_ofs);
    }

    template <typename T>
    void visit(const T& obj) {
        if constexpr (std::is_pod_v<T>) {
            m_ofs.write(reinterpret_cast<const char*>(&obj), sizeof(T));
        } else {
            const_cast<T&>(obj).visit(*this);
        }
    }

    std::uint64_t bytes() {
        return m_ofs.tellp();
    }
};

}  // namespace xcdat


text:
import pytest
from pytest_regressions.data_regression import DataRegressionFixture

from gdsfactory.components import cells
from gdsfactory.config import PATH
from gdsfactory.difftest import difftest

skip_test = {
    "version_stamp",
    "extend_ports_list",
    "extend_port",
    "component_sequence",
    "mzi_arm",
    "pack_doe",
    "pack_doe_grid",
    "crossing",
    "spiral_racetrack",
}

cells_to_test = set(cells.keys()) - skip_test

@pytest.fixture(params=cells_to_test, scope="function")
def component_name(request) -> str:
    return request.param

def test_gds(component_name: str) -> None:
    """Avoid regressions in GDS geometry shapes and layers."""
    component = cells[component_name]()
    difftest(component, test_name=component_name, dirpath=PATH.gdsdiff)

def test_settings(component_name: str, data_regression: DataRegressionFixture) -> None:
    """Avoid regressions when exporting settings."""
    component = cells[component_name]()
    data_regression.check(component.to_dict())

def test_assert_ports_on_grid(component_name: str) -> None:
    """Ensure ports are on grid."""
    component = cells[component_name]()
    component.assert_ports_on_grid()


text:
import argparse
import datetime
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import traceback
import urllib2

SLAVE_GCLIENT_CONFIG = """solutions = [
  {
    "name"      : "slave.DEPS",
    "url"       : "https://chrome-internal.googlesource.com/chrome/tools/build/slave.DEPS.git",
    "deps_file" : ".DEPS.git",
    "managed"   : True,
  },
]"""

INTERNAL_GCLIENT_CONFIG = """solutions = [
  {
    "name"      : "internal.DEPS",
    "url"       : "https://chrome-internal.googlesource.com/chrome/tools/build/internal.DEPS.git",
    "deps_file" : ".DEPS.git",
    "managed"   : True,
  },
]"""

GCLIENT_CONFIGS = {
  'slave.DEPS': SLAVE_GCLIENT_CONFIG,
  'internal.DEPS': INTERNAL_GCLIENT_CONFIG,
}

is_win = sys.platform.startswith('win')

PREVENT_REBOOT_FILE_CONTENT = 'slave_svn_to_git'

def log(line):
  sys.stdout.write('%s%s' % (line, os.linesep))
  sys.stdout.flush()

def check_call(cmd, cwd=None, env=None):
  log('Running %s%s' % (cmd, ' in %s' % cwd if cwd else ''))
  subprocess.check_call(cmd, cwd=cwd, shell=is_win, env=env)

def check_output(cmd, cwd=None, env=None):
  log('Running %s%s' % (cmd, ' in %s' % cwd if cwd else ''))
  return subprocess.check_output(cmd, cwd=cwd, shell=is_win, env=env,
                                 stderr=subprocess.STDOUT)

def report_checkout_state(b_dir, cur_host):
  """Report host checkout state to the tracking app.

  Args:
    b_dir: Directory where checkout is located.
    cur_host: Name of the current host.

  Returns:
    True if the host checkout should be converted to Git.
  """
  if os.path.isdir(os.path.join(b_dir, 'build', '.svn')):
    state = 'SVN'
  elif os.path.isdir(os.path.join(b_dir, 'build', '.git')):
    state = 'GIT'
  else:
    state = 'UNKNOWN'

  try:
    url = ('https://svn-to-git-tracking.appspot.com/api/reportState?host=%s&'
           'state=%s' % (urllib2.quote(cur_host), urllib2.quote(state)))
    return json.load(urllib2.urlopen(url))
  except Exception:
    return False

def report_broken_slave(cur_host, error_type):
  try:
    url = ('https://svn-to-git-tracking.appspot.com/api/reportBrokenSlave?'
           'host=%s&error_type=%s' % (urllib2.quote(cur_host),
                                      urllib2.quote(error_type)))
    urllib2.urlopen(url)
  except Exception as e:
    log('Failed to report %s for host %s: %s.' % (error_type, cur_host, e))

def get_svn2git_dirs(b_dir):
  return [f for f in os.listdir(b_dir) if f.startswith('slave_svn_to_git')]

def get_svn2git_noreboot_file(home_dir):
  noreboot_file_path = os.path.join(home_dir, 'no_reboot')
  if os.path.isfile(noreboot_file_path):
    with open(noreboot_file_path) as no_reboot_file:
      if no_reboot_file.read() == 'slave_svn_to_git':
        return noreboot_file_path

def report_host_state(home_dir, cur_host, b_dir):
  """Reports host state to the tracking app.

  Args:
    home_dir: Absolute path to the home directory.
    cur_host: Hostname of this host.
    b_dir: Absolute path to the checkout directory.

  Returns:
    Whether the host checkout should be converted to Git.
  """
  # Report and fix slaves with ~/no_reboot created by this script.
  if get_svn2git_noreboot_file(home_dir):
    try:
      os.remove(get_svn2git_noreboot_file(home_dir))
    except Exception:
      pass
    if get_svn2git_noreboot_file(home_dir):
      report_broken_slave(cur_host, 'no_reboot')

  # Report slaves without /b/.gclient.
  if not os.path.isfile(os.path.join(b_dir, '.gclient')):
    report_broken_slave(cur_host, 'gclient_missing')

  # Report and fix slaves with /b/slave_svn_to_git* folders.
  if get_svn2git_dirs(b_dir):
    try:
      for d in get_svn2git_dirs(b_dir):
        shutil.rmtree(os.path.join(b_dir, d))
    except Exception:
      pass
    if get_svn2git_dirs(b_dir):
      report_broken_slave(cur_host, 'slave_svn_to_git_dir_present')

  # Report slaves without /b/build/site_config/.bot_password.
  if not os.path.isfile(os.path.join(b_dir, 'build', 'site_config',
                                     '.bot_password')):
    report_broken_slave(cur_host, 'bot_password_missing')

  # Report slaves without /b/build/site_config/.boto.
  if not re.match('^.*\d+-c\d+$', cur_host):  # GCE bots don't need .boto file.
    if not os.path.isfile(os.path.join(b_dir, 'build', 'site_config', '.boto')):
      report_broken_slave(cur_host, 'boto_missing')

  return report_checkout_state(b_dir, cur_host)

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('-m', '--manual', action='store_true', default=False,
                      help='Run in manual mode')
  parser.add_argument('-s', '--send-repeated-updates-secs', type=int,
                      help='Instead of converting checkout, send regular '
                           'updates with the host state to the tracking app. '
                           'Value of this parameter is the delay between '
                           'updates in seconds.')
  parser.add_argument('--leak-tmp-dir', action='store_true', default=False,
                      help='Leaves temporary checkout dir on disk')
  options = parser.parse_args()

  # Find b directory.
  b_dir = None
  if is_win:
    if os.path.exists('E:\\b'):
      b_dir = 'E:\\b'
    elif os.path.exists('C:\\b'):
      b_dir = 'C:\\b'
  elif os.path.exists('/b'):
    b_dir = '/b'
  assert b_dir is not None and os.path.isdir(b_dir), 'Did not find b dir'

  home_dir = os.path.realpath(os.path.expanduser('~'))
  cur_host = socket.gethostname()

  if options.send_repeated_updates_secs:
    while True:
      report_host_state(home_dir, cur_host, b_dir)
      time.sleep(options.send_repeated_updates_secs)
    return 0

  if not report_host_state(home_dir, cur_host, b_dir) and not options.manual:
    log('Host %s is not pending SVN-to-Git conversion' % cur_host)
    return 0

  # Set up credentials for the download_from_google_storage hook.
  env = os.environ.copy()
  boto_file = os.path.join(b_dir, 'build', 'site_config', '.boto')
  if os.path.isfile(boto_file):
    env['AWS_CREDENTIAL_FILE'] = boto_file

  # Add depot_tools to PATH, so that gclient can be found.
  env_path_sep = ';' if is_win else ':'
  env['PATH'] = '%s%s%s' % (env['PATH'], env_path_sep,
                            os.path.join(b_dir, 'depot_tools'))

  # Find old .gclient config. If it doesn't exit - try .gclient.svn to handle
  # bots where we failed conversion half-way.
  gclient_path = os.path.join(b_dir, '.gclient')
  gclient_path_svn = os.path.join(b_dir, '.gclient.svn')
  if not os.path.isfile(gclient_path) and os.path.isfile(gclient_path_svn):
    log('Copying %s to %s' % (gclient_path_svn, gclient_path))
    shutil.copy(gclient_path_svn, gclient_path)
  assert os.path.isfile(gclient_path), 'Did not find old .gclient config'

  # Detect type of checkout.
  is_cros_slave = cur_host.startswith('cros')
  with open(gclient_path) as gclient_file:
    exec_env = {}
    exec gclient_file in exec_env
    solutions = exec_env['solutions']
  assert len(solutions) == 1, 'Number of solutions in .gclient is not 1'
  if not solutions[0]['url'].startswith('svn:'):
    log('Non-SVN URL in .gclient: %s' % solutions[0]['url'])
    if is_cros_slave and solutions[0]['deps_file'] == 'DEPS':
      log('Exempting unconverted CrOS slave from SVN URL requirement: %s' % (
          cur_host,))
    else:
      return 0
  sol_name = solutions[0]['name']
  assert sol_name in GCLIENT_CONFIGS, 'Unknown type of checkout: ' % sol_name
  gclient_config = GCLIENT_CONFIGS[sol_name]

  tmpdir = tempfile.mkdtemp(dir=os.path.realpath(b_dir),
                            prefix='slave_svn_to_git')
  try:
    # Create new temp Git checkout.
    with open(os.path.join(tmpdir, '.gclient'), 'w') as gclient_file:
      gclient_file.write(gclient_config)

    # Sync both repos (SVN first since mirroring happens from SVN to Git).
    try:
      try:
        check_output(['gclient', 'sync'], cwd=b_dir, env=env)
      except subprocess.CalledProcessError:
        # On Windows, gclient sync occasionally reports 'checksum mismatch'
        # error for build/scripts/slave/recipes/deterministic_build.expected/
        # full_chromium_swarm_linux_deterministic.json when calling 'svn update'
        # on 'build' directory. As a workaround, we delete parent dir containing
        # invalid .svn files and try again. The missing directory should be
        # re-created with the correct checksum by repeated call to 'svn update'.
        if is_win:
          parent_dir = os.path.join(
              b_dir, 'build', 'scripts', 'slave', 'recipes',
              'deterministic_build.expected')
          check_call(['rmdir', parent_dir, '/s', '/q'], cwd=b_dir, env=env)
          check_output(['gclient', 'sync'], cwd=b_dir, env=env)
        else:
          raise
    except subprocess.CalledProcessError as e:
      if 'DEPS source of truth has been moved to Git' not in e.output:
        print e.output  # simulate output if we've failed for another reason
        raise

    check_call(['gclient', 'sync'], cwd=tmpdir, env=env)

    # Find repositories handled by gclient.
    revinfo = check_output(['gclient', 'revinfo'], cwd=tmpdir, env=env)
    repos = {}
    for line in revinfo.splitlines():
      relpath, repospec = line.split(':', 1)
      repos[relpath.strip()] = repospec.strip()

    # Sanity checks.
    for relpath in sorted(repos):
      # Only process directories that have .svn dir in them.
      if not os.path.isdir(os.path.join(b_dir, relpath, '.svn')):
        log('%s subdir does not have .svn directory' % relpath)
        del repos[relpath]
        continue
      # Make sure Git directory exists.
      assert os.path.isdir(os.path.join(tmpdir, relpath, '.git'))

    # Move SVN .gclient away so that no one can run gclient sync while
    # conversion is in progress.
    log('Moving %s to %s' % (gclient_path, gclient_path_svn))
    shutil.move(gclient_path, gclient_path_svn)

    # Rename all .svn directories into .svn.backup. We use set because .svn dirs
    # may be found several times as some repos are subdirs of other repos.
    svn_dirs = set()
    count = 0
    log('Searching for .svn folders')
    for relpath in sorted(repos):
      for root, dirs, _files in os.walk(os.path.join(b_dir, relpath)):
        count += 1
        if count % 100 == 0:
          log('Processed %d directories' % count)
        if '.svn' in dirs:
          svn_dirs.add(os.path.join(relpath, root, '.svn'))
          dirs.remove('.svn')
        else:
          dirs[:] = []
    for rel_svn_dir in svn_dirs:
      svn_dir = os.path.join(b_dir, rel_svn_dir)
      log('Moving %s to %s.backup' % (svn_dir, svn_dir))
      shutil.move(svn_dir, '%s.backup' % svn_dir)

    # Move Git directories from temp dir to the checkout.
    for relpath, repospec in sorted(repos.iteritems()):
      src_git = os.path.join(tmpdir, relpath, '.git')
      dest_git = os.path.join(b_dir, relpath, '.git')
      log('Moving %s to %s' % (src_git, dest_git))
      shutil.move(src_git, dest_git)

    # Revert any local modifications after the conversion to Git.
    for relpath in sorted(repos):
      abspath = os.path.join(b_dir, relpath)
      diff = check_output(['git', 'diff'], cwd=abspath)
      if diff:
        diff_name = '%s.diff' % re.sub('[^a-zA-Z0-9]', '_', relpath)
        with open(os.path.join(home_dir, diff_name), 'w') as diff_file:
          diff_file.write(diff)
        check_call(['git', 'reset', '--hard'], cwd=abspath)

    # Update .gclient file to reference Git DEPS.
    with open(os.path.join(b_dir, '.gclient'), 'w') as gclient_file:
      gclient_file.write(gclient_config)
  finally:
    # Remove the temporary directory.
    if not options.leak_tmp_dir:
      shutil.rmtree(tmpdir)

  # Refresh gclient checkout.
  if is_cros_slave:
    # Make sure our current root URL matches the one in the .gclient file.
    #
    # On CrOS slaves, internal.DEPS is checked out as:
    # https://...../internal.DEPS
    #
    # The URL used for standard slaves (and the .gclient file that we drop) is:
    # https://...../internal.DEPS.git
    #
    # Because CrOS slaves use a Git checkout for internal.DEPS, the initial
    # repository is exempted from converstion. This will convert it to the
    # standard slave checkout so we're all uniform.
    with open(gclient_path) as gclient_file:
      exec_env = {}
      exec gclient_file in exec_env
      solutions = exec_env['solutions']

    root_repo_path = os.path.join(b_dir, solutions[0]['name'])
    check_call(['git', 'remote', 'set-url', 'origin', solutions[0]['url']],
               cwd=root_repo_path)

  # Run gclient sync again.
  check_call(['gclient', 'sync'], cwd=b_dir, env=env)

  return 0

if __name__ == '__main__':
  log('Running slave_svn_to_git on %s UTC' % datetime.datetime.utcnow())
  try:
    retcode = main()
  except Exception as e:
    traceback.print_exc(e)
    retcode = 1
  log('Return code: %d' % retcode)
  sys.exit(retcode)


text:
package uk.co.quidos.adminconsole.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

public abstract class BaseController {
	@Autowired
	protected ResourceBundleMessageSource _res;

//	@Autowired
//	protected SpringContextHolder _contextHolder;

	protected ModelAndView ajaxDone(int statusCode, String message) {
		ModelAndView mav = new ModelAndView("ajaxDone");
		mav.addObject("statusCode", statusCode);
		mav.addObject("message", message);
		return mav;
	}

	public UserSessionObject getUserSessionObject(HttpSession session)
	{
		return (UserSessionObject)session.getAttribute(Constants.SESSION_USER_ATTR_NAME);
	}

	protected ModelAndView ajaxDoneSuccess(String message) {
		return ajaxDone(200, message);
	}

	protected ModelAndView ajaxDoneError(String message) {
		return ajaxDone(300, message);
	}

	protected String getMessage(String code) {
		return this.getMessage(code, new Object[] {});
	}

	protected String getMessage(String code, Object arg0) {
		return getMessage(code, new Object[] { arg0 });
	}

	protected String getMessage(String code, Object arg0, Object arg1) {
		return getMessage(code, new Object[] { arg0, arg1 });
	}

	protected String getMessage(String code, Object arg0, Object arg1,
			Object arg2) {
		return getMessage(code, new Object[] { arg0, arg1, arg2 });
	}

	protected String getMessage(String code, Object arg0, Object arg1,
			Object arg2, Object arg3) {
		return getMessage(code, new Object[] { arg0, arg1, arg2, arg3 });
	}

	protected String getMessage(String code, Object[] args) {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
		Locale locale = localeResolver.resolveLocale(request);

		return _res.getMessage(code, args, locale);
	}

	protected void download(HttpServletResponse response, String physicalPath){
		FileInputStream fis = null;
		ServletOutputStream os = null;
		try {
			fis = new FileInputStream(new File(physicalPath));

			os = response.getOutputStream();
			byte[] buffer = new byte[1024];
			int n = -1;
			while ((n = fis.read(buffer, 0, buffer.length)) != -1) {
				os.write(buffer, 0, n);
			}

			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				fis = null;
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				os = null;
			}
		}
	}
}


text:
<?php
namespace cloud\siteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="area")
 */
class Area
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="nombre", type="string", length=255)
     * @Assert\NotBlank(message = "Campo Obligatorio")
     *
     */
    protected $name;

    /**
     * @ORM\OneToMany(targetEntity="Asignatura", mappedBy="area_id")
     */
    protected $area_id;

    public function __toString() {
        return $this->getName();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Jornada
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->area_id = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add area_id
     *
     * @param cloud\siteBundle\Entity\Asignatura $areaId
     * @return Area
     */
    public function addAreaId(\cloud\siteBundle\Entity\Asignatura $areaId)
    {
        $this->area_id[] = $areaId;

        return $this;
    }

    /**
     * Remove area_id
     *
     * @param cloud\siteBundle\Entity\Asignatura $areaId
     */
    public function removeAreaId(\cloud\siteBundle\Entity\Asignatura $areaId)
    {
        $this->area_id->removeElement($areaId);
    }

    /**
     * Get area_id
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getAreaId()
    {
        return $this->area_id;
    }
}


text:
"""Provides printers for a full-structured representation"""

from textwrap import dedent, indent

from sympy.core.basic import Basic as SympyBasic

from .base import QnetBasePrinter
from .sympy import SympyReprPrinter
from ._render_head_repr import render_head_repr
from qnet.algebra.core.abstract_algebra import Expression
from ..utils.singleton import Singleton

__all__ = []
__private__ = [
    'QnetSReprPrinter', 'IndentedSReprPrinter', 'IndentedSympyReprPrinter']

class QnetSReprPrinter(QnetBasePrinter):
    """Printer for a string (ASCII) representation."""

    sympy_printer_cls = SympyReprPrinter

    def _render_str(self, string):
        return repr(string)

    def emptyPrinter(self, expr):
        """Fallback printer"""
        return render_head_repr(expr, sub_render=self.doprint)

    def _print_ndarray(self, expr):
        if len(expr.shape) == 2:
            rows = []
            for row in expr:
                rows.append(
                    '[' + ", ".join([self.doprint(val) for val in row]) + ']')
            return ("array([" + ", ".join(rows) +
                    "], dtype=%s)" % str(expr.dtype))
        else:
            raise ValueError("Cannot render %s" % expr)

class IndentedSympyReprPrinter(SympyReprPrinter):
    """Indented repr printer for Sympy objects"""

    def doprint(self, expr):
        res = super().doprint(expr)
        return "    " * (self._print_level - 1) + res

class IndentedSReprPrinter(QnetBasePrinter):
    """Printer for rendering an expression in such a way that the resulting
    string can be evaluated in an appropriate context to re-instantiate an
    identical object, using nested indentation (implementing
    ``srepr(expr, indented=True)``
    """

    sympy_printer_cls = IndentedSympyReprPrinter

    def _get_from_cache(self, expr):
        """Obtain cached result, prepend with the keyname if necessary, and
        indent for the current level"""
        is_cached, res = super()._get_from_cache(expr)
        if is_cached:
            indent_str = "    " * self._print_level
            return True, indent(res, indent_str)
        else:
            return False,  None

    def _write_to_cache(self, expr, res):
        """Store the cached result without indentation, and without the
        keyname"""
        res = dedent(res)
        super()._write_to_cache(expr, res)

    def _render_str(self, string):
        return "    " * self._print_level + repr(string)

    def emptyPrinter(self, expr):
        """Fallback printer"""
        indent_str = "    " * (self._print_level - 1)
        lines = []
        if isinstance(expr.__class__, Singleton):
            # We exploit that Singletons override __expr__ to directly return
            # their name
            return indent_str + repr(expr)
        if isinstance(expr, Expression):
            args = expr.args
            keys = expr.minimal_kwargs.keys()
            lines.append(indent_str + expr.__class__.__name__ + "(")
            for arg in args:
                lines.append(self.doprint(arg) + ",")
            for key in keys:
                arg = expr.kwargs[key]
                lines.append(
                    ("    " * self._print_level) + key + '=' +
                    self.doprint(arg).lstrip() + ",")
            if len(args) > 0 or len(keys) > 0:
                lines[-1] = lines[-1][:-1]  # drop trailing comma for last arg
            lines[-1] += ")"
        elif isinstance(expr, (tuple, list)):
            delims = ("(", ")") if isinstance(expr, tuple) else ("[", "]")
            if len(expr) == 1:
                delims = (delims[0], "," + delims[1])
            lines.append(
                indent_str + delims[0] +
                ", ".join([render_head_repr(v) for v in expr]) +
                delims[1])
        else:
            lines.append(indent_str + SympyReprPrinter().doprint(expr))
        return "\n".join(lines)

    def _print_ndarray(self, expr):
        indent_str = "    " * (self._print_level - 1)
        if len(expr.shape) == 2:
            lines = [indent_str + "array([", ]
            self._print_level += 1
            for row in expr:
                indent_str = "    " * (self._print_level - 1)
                lines.append(indent_str + '[')
                for val in row:
                    lines.append(self.doprint(val) + ",")
                lines[-1] = lines[-1][:-1]
                lines.append(indent_str + '],')
            lines[-1] = lines[-1][:-1] + "], dtype=%s)" % str(expr.dtype)
            return "\n".join(lines)
        else:
            raise ValueError("Cannot render %s" % expr)


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.navigationToolbar;

import com.intellij.ide.navbar.ide.NavBarIdeUtil;
import com.intellij.ide.navbar.ide.NavBarService;
import com.intellij.ide.navigationToolbar.ui.NavBarUIManager;
import com.intellij.ide.ui.NavBarLocation;
import com.intellij.ide.ui.ToolbarSettings;
import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.UISettingsListener;
import com.intellij.ide.ui.customization.CustomActionsSchema;
import com.intellij.ide.ui.customization.CustomisedActionGroup;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.ex.ComboBoxAction;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.IdeRootPaneNorthExtension;
import com.intellij.openapi.wm.StatusBarCentralWidgetProvider;
import com.intellij.openapi.wm.impl.status.IdeStatusBarImpl;
import com.intellij.openapi.wm.impl.status.InfoAndProgressPanel;
import com.intellij.ui.ExperimentalUI;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBScrollBar;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBThinOverlappingScrollBar;
import com.intellij.ui.hover.HoverListener;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.ui.JBSwingUtilities;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.CompletableFuture;

import static com.intellij.ide.navigationToolbar.NavBarRootPaneExtension.PANEL_KEY;

/**
 * @author Konstantin Bulenkov
 */
public final class NavBarRootPaneExtension implements IdeRootPaneNorthExtension {
  static final String PANEL_KEY = "NavBarPanel";

  @Override
  public @NotNull JComponent createComponent(@NotNull Project project, boolean isDocked) {
    return new MyNavBarWrapperPanel(project);
  }

  @Override
  public @NotNull String getKey() {
    return IdeStatusBarImpl.NAVBAR_WIDGET_KEY;
  }

  // used externally
  public abstract static class NavBarWrapperPanel extends JPanel implements UISettingsListener {
      public NavBarWrapperPanel(LayoutManager layout) {
        super(layout);
      }

      @Override
      protected Graphics getComponentGraphics(Graphics graphics) {
        return JBSwingUtilities.runGlobalCGTransform(this, super.getComponentGraphics(graphics));
      }
    }
}

final class MyNavBarWrapperPanel extends NavBarRootPaneExtension.NavBarWrapperPanel implements StatusBarCentralWidgetProvider {
  private final Project myProject;
  private JComponent myNavBarPanel;
  private JPanel myRunPanel;
  private Boolean myNavToolbarGroupExist;
  JComponent myNavigationBar;
  JScrollPane myScrollPane;

  MyNavBarWrapperPanel(Project project) {
    super(new BorderLayout());

    myProject = project;

    UISettings settings = UISettings.getInstance();
    if (!ExperimentalUI.isNewUI() || settings.getShowNavigationBar() && settings.getNavBarLocation() == NavBarLocation.TOP) {
      add(getNavBarPanel(), BorderLayout.CENTER);
    }
    else {
      setVisible(false);
    }

    revalidate();

    uiSettingsChanged(settings);
  }

  @Override
  public @NotNull JComponent createCentralStatusBarComponent() {
    return getNavBarPanel();
  }

  private JComponent getNavBarPanel() {
    if (myNavBarPanel != null) {
      return myNavBarPanel;
    }

    if (NavBarIdeUtil.isNavbarV2Enabled()) {
      myNavigationBar = NavBarService.getInstance(myProject).getStaticNavBarPanel();
    }
    else {
      myNavigationBar = new ReusableNavBarPanel(myProject, true);
      ((NavBarPanel)myNavigationBar).getModel().setFixedComponent(true);
    }
    putClientProperty(PANEL_KEY, myNavigationBar);

    myScrollPane = ScrollPaneFactory.createScrollPane(myNavigationBar);
    updateScrollBarFlippedState(null);

    myNavBarPanel = new NavBarContainer(new BorderLayout(), this);
    myNavBarPanel.add(myScrollPane, BorderLayout.CENTER);
    myNavBarPanel.setOpaque(!ExperimentalUI.isNewUI());
    myNavBarPanel.updateUI();

    if (ExperimentalUI.isNewNavbar()) {
      HoverListener hoverListener = new HoverListener() {
        @Override
        public void mouseEntered(@NotNull Component component, int x, int y) {
          toggleScrollBar(true);
        }

        @Override
        public void mouseMoved(@NotNull Component component, int x, int y) { }

        @Override
        public void mouseExited(@NotNull Component component) {
          toggleScrollBar(false);
        }
      };
      hoverListener.addTo(myNavBarPanel);
    }

    return myNavBarPanel;
  }

  @Override
  public void uiSettingsChanged(@NotNull UISettings uiSettings) {
    toggleRunPanel(isShowToolPanel(uiSettings));
    toggleNavPanel(uiSettings);

    if (NavBarIdeUtil.isNavbarV2Enabled()) {
      NavBarService.getInstance(myProject).uiSettingsChanged(uiSettings);
    }

    if (myNavigationBar == null) {
      return;
    }

    if (myNavigationBar instanceof NavBarPanel) {
      ((NavBarPanel)myNavigationBar).updateState(uiSettings.getShowNavigationBar());
    }

    boolean visible = NavBarIdeUtil.isNavbarShown(uiSettings);
    if (ExperimentalUI.isNewUI()) {
      myScrollPane.setVisible(visible);
    }

    myNavigationBar.revalidate();
    setVisible(visible);

    revalidate();
    repaint();

    if (getComponentCount() > 0) {
      Component c = getComponent(0);
      if (c instanceof JComponent) {
        ((JComponent)c).setOpaque(false);
      }
    }
  }

  @Override
  public Insets getInsets() {
    return NavBarUIManager.getUI().getWrapperPanelInsets(super.getInsets());
  }

  private void updateScrollBarFlippedState(@Nullable NavBarLocation location) {
    if (ExperimentalUI.isNewNavbar() && myScrollPane != null) {
      if (location == null) location = UISettings.getInstance().getNavBarLocation();
      JBScrollPane.Flip flipState = (location == NavBarLocation.BOTTOM) ? JBScrollPane.Flip.VERTICAL : JBScrollPane.Flip.NONE;
      myScrollPane.putClientProperty(JBScrollPane.Flip.class, flipState);
    }
  }

  private static boolean isShowToolPanel(@NotNull UISettings uiSettings) {
    // Evanescent me: fix run panel show condition in ExpUI if necessary.
    if (!ExperimentalUI.isNewUI() && !uiSettings.getShowMainToolbar() && NavBarIdeUtil.isNavbarShown(uiSettings)) {
      ToolbarSettings toolbarSettings = ToolbarSettings.getInstance();
      return !toolbarSettings.isVisible() || !toolbarSettings.isAvailable();
    }
    return false;
  }

  private static void alignVertically(Container container) {
    if (container.getComponentCount() == 1) {
      Component c = container.getComponent(0);
      Insets insets = container.getInsets();
      Dimension d = c.getPreferredSize();
      Rectangle r = container.getBounds();
      c.setBounds(insets.left, (r.height - d.height - insets.top - insets.bottom) / 2 + insets.top, r.width - insets.left - insets.right, d.height);
    }
  }

  private static boolean isNeedGap(final AnAction group) {
    final AnAction firstAction = getFirstAction(group);
    return firstAction instanceof ComboBoxAction;
  }

  private static @Nullable AnAction getFirstAction(final AnAction group) {
    if (group instanceof DefaultActionGroup) {
      AnAction firstAction = null;
      for (final AnAction action : ((DefaultActionGroup)group).getChildActionsOrStubs()) {
        if (action instanceof DefaultActionGroup) {
          firstAction = getFirstAction(action);
        }
        else if (action instanceof Separator || action instanceof ActionGroup) {
          continue;
        }
        else {
          firstAction = action;
          break;
        }

        if (firstAction != null) break;
      }

      return firstAction;
    }
    if (group instanceof CustomisedActionGroup) {
      return ((CustomisedActionGroup)group).getFirstAction();
    }
    return null;
  }

  private boolean runToolbarExists() {
    if (myNavToolbarGroupExist == null) {
      final AnAction correctedAction = CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_NAVBAR_TOOLBAR);
      myNavToolbarGroupExist =
        correctedAction instanceof DefaultActionGroup && ((DefaultActionGroup)correctedAction).getChildrenCount() > 0 ||
        correctedAction instanceof CustomisedActionGroup && ((CustomisedActionGroup)correctedAction).getFirstAction() != null;
    }
    return myNavToolbarGroupExist;
  }

  private void toggleNavPanel(UISettings settings) {
    boolean show = ExperimentalUI.isNewUI() ?
                   settings.getShowNavigationBar() && settings.getNavBarLocation() == NavBarLocation.TOP :
                   NavBarIdeUtil.isNavbarShown(settings);
    if (show) {
      ApplicationManager.getApplication().invokeLater(() -> {
        add(getNavBarPanel(), BorderLayout.CENTER);
        myNavBarPanel.updateUI();
      });
    }
    else {
      var c = ((BorderLayout)getLayout()).getLayoutComponent(BorderLayout.CENTER);
      if (c != null) {
        remove(c);
      }
    }

    updateScrollBarFlippedState(settings.getNavBarLocation());
    setVisible(show);
  }

  private void toggleRunPanel(boolean show) {
    CompletableFuture
      .supplyAsync(() -> CustomActionsSchema.getInstance().getCorrectedAction(IdeActions.GROUP_NAVBAR_TOOLBAR),
                   AppExecutorUtil.getAppExecutorService())
      .thenAcceptAsync(action -> {
        if (show && myRunPanel == null && runToolbarExists()) {
          if (myRunPanel != null) {
            remove(myRunPanel);
            myRunPanel = null;
          }

          ActionManager manager = ActionManager.getInstance();
          if (action instanceof ActionGroup) {
            ActionToolbar actionToolbar = manager.createActionToolbar(ActionPlaces.NAVIGATION_BAR_TOOLBAR, (ActionGroup)action, true);
            actionToolbar.setTargetComponent(null);
            myRunPanel = new JPanel(new BorderLayout()) {
              @Override
              public void doLayout() {
                alignVertically(this);
              }
            };
            myRunPanel.setOpaque(false);
            myRunPanel.add(actionToolbar.getComponent(), BorderLayout.CENTER);
            final boolean needGap = isNeedGap(action);
            myRunPanel.setBorder(JBUI.Borders.emptyLeft(needGap ? 5 : 1));
            NavBarLeftSideExtension.EP_NAME.forEachExtensionSafe(extension -> {
              extension.process(this, myProject);
            });
            add(myRunPanel, BorderLayout.EAST);
          }
        }
        else if (!show && myRunPanel != null) {
          remove(myRunPanel);
          myRunPanel = null;
        }
      }, command -> ApplicationManager.getApplication().invokeLater(command, myProject.getDisposed()));
  }

  void toggleScrollBar(boolean isOn) {
    JScrollBar scrollBar = myScrollPane.getHorizontalScrollBar();
    if (scrollBar instanceof JBScrollBar) {
      ((JBScrollBar)scrollBar).toggle(isOn);
    }
  }
}

final class NavBarContainer extends JPanel implements InfoAndProgressPanel.ScrollableToSelected {
  private final MyNavBarWrapperPanel panel;

  NavBarContainer(@NotNull LayoutManager layout, @NotNull MyNavBarWrapperPanel panel) {
    super(layout);

    this.panel = panel;
    updateUI();
  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    final Component navBar = panel.myScrollPane;
    Rectangle r = navBar.getBounds();

    Graphics2D g2d = (Graphics2D)g.create();
    g2d.translate(r.x, r.y);
    g2d.dispose();
  }

  @Override
  public void doLayout() {
    // align vertically
    final Rectangle r = getBounds();
    final Insets insets = getInsets();
    int x = insets.left;
    JScrollPane scrollPane = panel.myScrollPane;
    if (scrollPane == null || !scrollPane.isVisible()) {
      return;
    }

    int navBarHeight = ((Component)scrollPane).getPreferredSize().height;
    if (ExperimentalUI.isNewNavbar()) {
      navBarHeight = r.height;
    }

    scrollPane.setBounds(x, (r.height - navBarHeight) / 2, r.width - insets.left - insets.right, navBarHeight);
  }

  @Override
  public void updateUI() {
    // updateUI is called from JPanel constructor
    if (panel == null) {
      return;
    }

    super.updateUI();

    JScrollPane scrollPane = panel.myScrollPane;
    if (scrollPane == null || panel.myNavigationBar == null) {
      return;
    }

    var settings = UISettings.getInstance();
    var border = !ExperimentalUI.isNewUI() || settings.getShowNavigationBar()
                 ? new NavBarBorder()
                 : JBUI.Borders.empty();

    if (ExperimentalUI.isNewNavbar()) {
      scrollPane.setHorizontalScrollBar(new JBThinOverlappingScrollBar(Adjustable.HORIZONTAL));
      if (scrollPane instanceof JBScrollPane) {
        ((JBScrollPane)scrollPane).setOverlappingScrollBar(true);
      }
      scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
      panel.toggleScrollBar(false);
    }
    else {
      scrollPane.setHorizontalScrollBar(null);
    }

    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane.setBorder(border);
    scrollPane.setOpaque(false);
    scrollPane.getViewport().setOpaque(false);
    scrollPane.setViewportBorder(null);

    if (ExperimentalUI.isNewUI()) {
      boolean visible = NavBarIdeUtil.isNavbarShown(settings);
      scrollPane.setVisible(visible);
      if (panel.myNavigationBar instanceof NavBarPanel) {
        ((NavBarPanel)panel.myNavigationBar).updateState(visible);
      }
    }
    panel.myNavigationBar.setBorder(null);
  }

  @Override
  public void updateAutoscrollLimit(InfoAndProgressPanel.AutoscrollLimit limit) {
    JComponent navigationBar = panel.myNavigationBar;
    if (navigationBar instanceof NavBarPanel) {
      ((NavBarPanel)navigationBar).updateAutoscrollLimit(limit);
    }
  }
}