text:
<?php

namespace KZ;

class FlashMessenger implements  flashMessenger\interfaces\FlashMessenger
{
	/**
	 * Messages storage.
	 *
	 * @var array
	 */
	protected $messages;

	/**
	 * @var int
	 */
	protected $iteratorPosition = 0;

	protected $iteratorKeys = [];

	/**
	 * Key in session.
	 *
	 * @var string
	 */
	protected $sessionPrefix = 'flashMessenger';

	public function __construct(array $config = [])
	{
		$this->setConfig($config);
		$this->initMessages();
	}

	/**
	 * Add message,
	 *
	 * @param $text
	 * @param string $type - Message type.
	 * @return int - Return position for added item.
	 */
	public function add($text, $type = self::SUCCESS)
	{
		$size = array_push($this->messages, [
			'text' => $text,
			'type' => $type,
			'liveCounter' => 0
		]);

		return $size - 1;
	}

	/**
	 * Extend messages to next time.
	 *
	 * @return $this
	 */
	public function extend()
	{
		foreach ($this->messages as $key => $val)
			if ($this->messages[$key]['liveCounter'] > 0)
				$this->messages[$key]['liveCounter']--;

		return $this;
	}

	/**
	 * Delete message.
	 *
	 * @param $position
	 * @return $this
	 */
	public function delete($position)
	{
		if (isset($this->messages[$position]))
			unset($this->messages[$position]);

		return $this;
	}

	/**
	 * Get all messages by type.
	 *
	 * @param $type
	 * @return array
	 */
	public function getAllByType($type)
	{
		$out = [];

		foreach ($this->messages as $pos => $val) {
			if ($val['type'] != $type)
				continue;

			$out[] = $val['text'];
		}

		return $out;
	}

	/**
	 * @param string $sessionPrefix
	 * @throws \InvalidArgumentException
	 * @return $this
	 */
	public function setSessionPrefix($sessionPrefix)
	{
		if (trim($sessionPrefix) == '')
			throw new \InvalidArgumentException('Session prefix cannot be empty!');

		$changed = ($sessionPrefix != $this->sessionPrefix) ? true : false;
		$this->sessionPrefix = $sessionPrefix;

		if (isset($this->messages) && $changed)
			$this->initMessages();

		return $this;
	}

	/**
	 * @return string
	 */
	public function getSessionPrefix()
	{
		return $this->sessionPrefix;
	}

	/**
	 * Set config.
	 *
	 * @param array $config
	 * @return $this
	 */
	public function setConfig(array $config)
	{
		$allowedOptions = [
			'sessionPrefix'
		];

		foreach ($allowedOptions as $key) {
			if (!isset($config[$key]))
				continue;

			$method = 'set' . $key;
			if (method_exists($this, $method))
				$this->{$method}($config[$key]);
			else
				$this->{$key} = $config[$key];
		}

		return $this;
	}

	/**
	 * @return string
	 */
	public function current()
	{
		return $this->messages[$this->iteratorKeys[$this->iteratorPosition]]['text'];
	}

	/**
	 * Key returns type.
	 *
	 * @return string
	 */
	public function key()
	{
		return $this->messages[$this->iteratorKeys[$this->iteratorPosition]]['type'];
	}

	public function rewind()
	{
		$this->iteratorPosition = 0;
		$this->iteratorKeys = array_keys($this->messages);
	}

	public function next()
	{
		$this->iteratorPosition++;
	}

	public function valid()
	{
		return isset(
			$this->iteratorKeys[$this->iteratorPosition],
			$this->messages[$this->iteratorKeys[$this->iteratorPosition]]
		);
	}

	protected function initMessages()
	{
		if (!isset($_SESSION[$this->sessionPrefix]))
			$_SESSION[$this->sessionPrefix] = [];

		$this->messages = &$_SESSION[$this->sessionPrefix];

		foreach ($this->messages as $key => &$val) {
			$val['liveCounter']++;

			if ($val['liveCounter'] == 2)
				$this->delete($key);
		}
	}
}


text:
using namespace std;

class AliGenUHKM : public AliGenMC
{

 public:
  AliGenUHKM();
  AliGenUHKM(Int_t npart);

  virtual ~AliGenUHKM();
  virtual void    Generate();
  virtual void    Init();
  //  virtual void    AddHeader(AliGenEventHeader* header);

  // Setters
  // set reasonable default parameters suited for central Au+Au collisions at RHIC(200GeV)
  void SetAllParametersRHIC();
  // set reasonable default parameters suited for central Pb+Pb collisions at LHC(5.5TeV)
  void SetAllParametersLHC();

  void SetEcms(Double_t value) {fHydjetParams.fSqrtS = value;}          // CMS energy per nucleon [GeV] (<2.24 given temperature and ch pot are used)
  void SetAw(Double_t value) {fHydjetParams.fAw = value;}             // nuclei mass number
  void SetBmin(Double_t value) {fHydjetParams.fBmin = value;}           // Minimum impact parameter
  void SetBmax(Double_t value) {fHydjetParams.fBmax = value;}           // Maximum impact parameter
  void SetChFrzTemperature(Double_t value) {fHydjetParams.fT = value;}  // Temperature for the chemical freezeout [GeV]
  void SetMuB(Double_t value) {fHydjetParams.fMuB = value;}            // Baryonic chemical potential [GeV]
  void SetMuS(Double_t value) {fHydjetParams.fMuS = value;}            // Strangeness chemical potential [GeV]
  void SetMuQ(Double_t value) {fHydjetParams.fMuI3 = value;}  // Isospin chemical potential [GeV]
  void SetThFrzTemperature(Double_t value) {fHydjetParams.fThFO = value;}  // Temperature for the thermal freezeout [GeV]
  void SetMuPionThermal(Double_t value) {fHydjetParams.fMu_th_pip = value;} // Chemical potential for pi+ at thermal freezeout [GeV]
  virtual void SetSeed(UInt_t value) {fHydjetParams.fSeed = value;} //parameter to set the random nuber seed (=0 the current time is used
  //to set the random generator seed, !=0 the value fSeed is
  //used to set the random generator seed and then the state of random
  //number generator in PYTHIA MRPY(1)=fSeed
  void SetTauB(Double_t value) {fHydjetParams.fTau = value;}  // Proper time for the freeze-out hyper surface [fm/c]
  void SetSigmaTau(Double_t value) {fHydjetParams.fSigmaTau = value;}  // Standard deviation for the proper time (emission duration) [fm/c]
  void SetRmaxB(Double_t value) {fHydjetParams.fR = value;}              // Maximal transverse radius [fm]
  void SetYlMax(Double_t value) {fHydjetParams.fYlmax = value;}          // Maximal fireball longitudinal rapidity
  void SetEtaRMax(Double_t value) {fHydjetParams.fUmax = value;}           // Maximal transverse velocity
  void SetMomAsymmPar(Double_t value) {fHydjetParams.fDelta = value;}          // Momentum asymmetry parameter
  void SetCoordAsymmPar(Double_t value) {fHydjetParams.fEpsilon = value;}        // Coordinate asymmetry parameter

  void SetEtaType(Int_t value) {fHydjetParams.fEtaType = value;} // flag to choose rapidity distribution, if fEtaType<=0,
                                                  //then uniform rapidity distribution in [-fYlmax,fYlmax] if fEtaType>0,
                                                  //then Gaussian with dispertion = fYlmax
  void SetGammaS(Double_t value) {fHydjetParams.fCorrS = value;} // Strangeness suppression parameter (if gamma_s<=0 then it will be calculated)

  //PYQUEN parameters
  void SetPyquenNhsel(Int_t value) {fHydjetParams.fNhsel = value;} // Flag to choose the type of event to be generated
                                              // fNhsel = 0 --> UHKM fireball, no jets
                                              // fNhsel = 1 --> UHKM fireball, jets with no quenching
                                              // fNhsel = 2 --> UHKM fireball, jets with quenching
                                              // fNhsel = 3 --> no UHKM fireball, jets with no quenching
                                              // fNhsel = 4 --> no UHKM fireball, jets with quenching
  void SetPyquenShad(Int_t value) {fHydjetParams.fIshad = value;}//flag to switch on/off impact parameter dependent nuclear
                                                 // shadowing for gluons and light sea quarks (u,d,s) (0: shadowing off,
                                                 // 1: shadowing on for fAw=207, 197, 110, 40, default: 1
  void SetPyquenPtmin(Double_t value) {fHydjetParams.fPtmin = value;} // Pyquen input parameter for minimum Pt of parton-parton scattering (5GeV<pt<500GeV)
  void SetPyquenT0(Double_t value) {fHydjetParams.fT0 = value;}        //proper QGP formation tempereture
  void SetPyquenTau0(Double_t value) {fHydjetParams.fTau0 = value;}    //proper QGP formation time in fm/c (0.01<fTau0<10)
  void SetPyquenNf(Int_t value) {fHydjetParams.fNf = value;}  //number of active quark flavours N_f in QGP fNf=0, 1,2 or 3
  void SetPyquenIenglu(Int_t value) {fHydjetParams.fIenglu = value;}  // flag to fix type of in-medium partonic energy loss
                                                        //(0: radiative and collisional loss, 1: radiative loss only, 2:
                                                        //collisional loss only) (default: 0);
  void SetPyquenIanglu(Int_t value) {fHydjetParams.fIanglu = value;}  //flag to fix type of angular distribution of in-medium emitted
                                                   //gluons (0: small-angular, 1: wide-angular, 2:collinear) (default: 0).

  void SetPDGParticleFile(const Char_t *name) {strncpy(fParticleFilename, name, 255);}//Set the filename containing the particle PDG info
  void SetPDGDecayFile(const Char_t *name) {strncpy(fDecayFilename, name, 255);} //Set the filename containing the PDG decay channels info
  void SetPDGParticleStable(Int_t pdg, Bool_t value) { // Turn on/off the decay flag for a PDG particle
    fStableFlagPDG[fStableFlagged] = pdg;
    fStableFlagStatus[fStableFlagged++] = value;
  }

  // Getters
  Double_t GetEcms() const {return fHydjetParams.fSqrtS;}
  Double_t GetAw() const {return fHydjetParams.fAw;}
  Double_t GetBmin() const {return fHydjetParams.fBmin;}
  Double_t GetBmax() const {return fHydjetParams.fBmax;}
  Double_t GetChFrzTemperature() const {return fHydjetParams.fT;}
  Double_t GetMuB() const {return fHydjetParams.fMuB;}
  Double_t GetMuS() const {return fHydjetParams.fMuS;}
  Double_t GetMuQ() const {return fHydjetParams.fMuI3;}
  Double_t GetThFrzTemperature() const {return fHydjetParams.fThFO;}
  Double_t GetMuPionThermal() const {return fHydjetParams.fMu_th_pip;}
  Int_t    GetSeed() const {return fHydjetParams.fSeed;}
  Double_t GetTauB() const {return fHydjetParams.fTau;}
  Double_t GetSigmaTau() const {return fHydjetParams.fSigmaTau;}
  Double_t GetRmaxB() const {return fHydjetParams.fR;}
  Double_t GetYlMax() const {return fHydjetParams.fYlmax;}
  Double_t GetEtaRMax() const {return fHydjetParams.fUmax;}
  Double_t GetMomAsymmPar() const {return fHydjetParams.fDelta;}
  Double_t GetCoordAsymmPar() const {return fHydjetParams.fEpsilon;}
  Int_t    GetEtaType() const {return fHydjetParams.fEtaType;}
  Double_t GetGammaS() const {return fHydjetParams.fCorrS;}
  Int_t    GetPyquenNhsel() const {return fHydjetParams.fNhsel;}
  Int_t    GetPyquenShad() const {return fHydjetParams.fIshad;}
  Double_t GetPyquenPtmin() const {return fHydjetParams.fPtmin;}
  Double_t GetPyquenT0() const {return fHydjetParams.fT0;}
  Double_t GetPyquenTau0() const {return fHydjetParams.fTau0;}
  Double_t GetPyquenNf() const {return fHydjetParams.fNf;}
  Double_t GetPyquenIenglu() const {return fHydjetParams.fIenglu;}
  Double_t GetPyquenIanglu() const {return fHydjetParams.fIanglu;}
  const Char_t*  GetPDGParticleFile() const {return fParticleFilename;}
  const Char_t*  GetPDGDecayFile() const {return fDecayFilename;}

 protected:
  Int_t       fTrials;         // Number of trials
  TUHKMgen    *fUHKMgen;       // UHKM

  InitialParamsHydjet_t fHydjetParams;    // list of parameters for the initial state
  // details for the PDG database
  Char_t fParticleFilename[256];            // particle list filename
  Char_t fDecayFilename[256];               // decay table filename
  Int_t fStableFlagPDG[500];                // array of PDG codes flagged
  Bool_t fStableFlagStatus[500];            // array of decay flag status
  Int_t fStableFlagged;                     // number of toggled decay flags

  void SetAllParameters();
  void CheckPDGTable();

 private:
  void Copy(TObject &rhs) const;
  AliGenUHKM(const AliGenUHKM&);
  AliGenUHKM & operator = (const AliGenUHKM &);

  ClassDef(AliGenUHKM, 6) // AliGenerator interface to UHKM
};
#endif

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to Elasticsearch under one or more contributor
license agreements. See the NOTICE file distributed with this work for additional
information regarding copyright ownership. Elasticsearch licenses this file to you
under the Apache License, Version 2.0 (the "License"); you may not use this
file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by
applicable law or agreed to in writing, software distributed under the License
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.elasticsearch.plugin</groupId>
        <artifactId>elasticsearch-plugin</artifactId>
        <version>2.0.0.beta1-SNAPSHOT</version>
    </parent>

    <artifactId>elasticsearch-cloud-gce</artifactId>
    <name>Elasticsearch Google Compute Engine cloud plugin</name>
    <description>The Google Compute Engine (GCE) Cloud plugin allows to use GCE API for the unicast discovery mechanism.</description>

    <properties>
        <google.gce.version>v1-rev59-1.20.0</google.gce.version>
        <es.plugin.port>9300</es.plugin.port>
        <!-- currently has no unit tests -->
        <tests.ifNoTests>warn</tests.ifNoTests>
        <tests.jvms>1</tests.jvms>
        <tests.rest.suite>cloud_gce</tests.rest.suite>
        <tests.rest.load_packaged>false</tests.rest.load_packaged>
    </properties>

    <dependencies>
        <!-- Google APIs -->
        <dependency>
          <groupId>com.google.apis</groupId>
          <artifactId>google-api-services-compute</artifactId>
          <version>${google.gce.version}</version>
          <exclusions>
              <exclusion>
                 <groupId>com.google.guava</groupId>
                 <artifactId>guava-jdk5</artifactId>
              </exclusion>
          </exclusions>
        </dependency>
        <!-- We need to force here the compile scope as it was defined as test scope in plugins/pom.xml -->
        <!-- TODO: remove this dependency when we will have a REST Test module -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


text:
{% load i18n staticfiles %}
<!doctype html>

    <meta charset="utf-8">
    <title>Zinnia's Weblog - {% block title %}{% endblock title %}{% block title-page %}{% endblock title-page %}</title>
    <meta name="robots" content="follow, all" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="{% block meta-description %}{% trans "Just another Zinnia weblog." %}{% endblock meta-description %}{% block meta-description-page %}{% endblock meta-description-page %}" />
    <meta name="keywords" content="{% block meta-keywords %}django, blog, weblog, zinnia{% endblock meta-keywords %}" />
    <meta name="author" content="Fantomas42" />
    {% block meta %}{% endblock meta %}
    <link rel="pingback" href="/xmlrpc/" />
    <link rel="home" href="{% url 'zinnia:entry_archive_index' %}" />
    <link rel="stylesheet" href="{% static "zinnia_bootstrap/bootstrap/css/bootstrap.min.css" %}" />

    <link rel="shortcut icon" href="{% static "zinnia/theme/img/favicon.ico" %}" />
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{% static "zinnia_bootstrap/assets/ico/apple-touch-icon-144-precomposed.png" %}" />
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="{% static "zinnia_bootstrap/assets/ico/apple-touch-icon-114-precomposed.png" %}" />
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="{% static "zinnia_bootstrap/assets/ico/apple-touch-icon-72-precomposed.png" %}" />
    <link rel="apple-touch-icon-precomposed" href="{% static "zinnia_bootstrap/assets/ico/apple-touch-icon-57-precomposed.png" %}" />
    {% block link %}{% endblock link %}
    {% block script %}{% endblock script %}

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            {% trans "Toggle navigation" %}

          </button>

            Zinnia's Weblog

            {% url 'zinnia:category_list' as category_list_url %}

                {% trans "Categories" %}

            {% url 'zinnia:author_list' as author_list_url %}

                {% trans "Authors" %}

            {% url 'zinnia:tag_list' as tag_list_url %}

                {% trans "Tags" %}

          <form method="get" action="{% url 'zinnia:entry_search' %}" class="navbar-form navbar-left">

              <input type="text" class="search-query form-control" placeholder="{% trans 'Search' %}" name="pattern" value="{{ pattern }}" />

            <button type="submit" name="submit" class="btn btn-default btn-sm">

            </button>
          </form>

            {% url 'zinnia:sitemap' as sitemap_url %}

                {% trans "Sitemap" %}

                {% trans "RSS Feed" %}

    {% block slider %}{% endblock %}

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

{% trans "Useful links" %}

                  {% trans "Weblog index" %}

                  {% trans "Sitemap" %}

{% trans "Search" %}

            {% include "zinnia/tags/search_form.html" %}

          {% endblock content %}

          {% block sidebar %}
          {% endblock sidebar %}

{% blocktrans %}Powered by Django and Zinnia {{ ZINNIA_VERSION }}.{% endblocktrans %}


text:
package org.esupportail.catapp.admin.web.config;

import org.esupportail.catapp.admin.web.utils.jsf.ViewScope;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Arrays.asList;

@Configuration
@Import({ ControllerConfig.class })
public class ContextConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer(@Value("#{systemProperties['config.location']?:''}") String configLocation) {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();

        Resource[] resources = new Resource[] {
                new ClassPathResource("/properties/defaults.properties")
        };

        if (!configLocation.isEmpty()) {
            final List<Resource> resourceList = new ArrayList<>(asList(resources));
            resourceList.add(new PathResource(configLocation));
            resources = resourceList.toArray(new Resource[resourceList.size()]);
        }

        pspc.setLocations(resources);
        pspc.setIgnoreUnresolvablePlaceholders(true);

        return pspc;
    }

    @Bean
    public static CustomScopeConfigurer customScopeConfigurer() {
        Map<String, Object> scopes = new HashMap<String, Object>() {{
            put("view", new ViewScope());
        }};
        CustomScopeConfigurer configurer = new CustomScopeConfigurer();
        configurer.setScopes(scopes);
        return configurer;
    }
}


text:
var gulp = require('gulp');
var $ = plugins = require('gulp-load-plugins')();
var config = require('./gulp.config').config;

gulp.task('jasmine', function() {
  return gulp
  .src(config.tests.public)
  .pipe($.karma({ configFile: config.tests.karma}));
});

gulp.task('test', function() {
  gulp.watch(config.tests.public, ['jasmine']);
});


text:
<?php

require_once EXHIBIT_BUILDER_DIR . '/helpers/ExhibitPageFunctions.php';

/**
 * Tests for exhibit_builder_is_current_page function
 */
class ExhibitBuilderIsCurrentPageTest extends ExhibitBuilder_ViewTestCase
{
    /**
     * Tests whether exhibit_builder_is_current_page correctly determines which exhibit page is current.
     */
    public function testExhibitBuilderIsCurrentPage()
    {
        $exhibitPageOne = new ExhibitPage;
        $exhibitPageOne->id = 1;
        $exhibitPageTwo = new ExhibitPage;
        $exhibitPageTwo->id = 2;
        $this->assertFalse(exhibit_builder_is_current_page($exhibitPageOne));
        $this->assertFalse(exhibit_builder_is_current_page($exhibitPageTwo));

        $this->view->exhibit_page = $exhibitPageOne;
        $this->assertTrue(exhibit_builder_is_current_page($exhibitPageOne));
        $this->assertFalse(exhibit_builder_is_current_page($exhibitPageTwo));

        $this->view->exhibit_page = $exhibitPageTwo;
        $this->assertFalse(exhibit_builder_is_current_page($exhibitPageOne));
        $this->assertTrue(exhibit_builder_is_current_page($exhibitPageTwo));
    }
}


text:
export * from './Tag';
export default from './Tag';


text:
package ca.corefacility.bioinformatics.irida.ria.web.services;

import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import ca.corefacility.bioinformatics.irida.model.RemoteAPI;
import ca.corefacility.bioinformatics.irida.model.project.Project;
import ca.corefacility.bioinformatics.irida.model.project.ProjectSyncFrequency;
import ca.corefacility.bioinformatics.irida.model.remote.RemoteStatus;
import ca.corefacility.bioinformatics.irida.model.user.User;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.remote.RemoteProjectSettings;
import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.remote.RemoteProjectSettingsUpdateRequest;
import ca.corefacility.bioinformatics.irida.service.ProjectService;
import ca.corefacility.bioinformatics.irida.service.remote.ProjectRemoteService;
import ca.corefacility.bioinformatics.irida.service.user.UserService;

/**
 * A utility class for doing operations on remote project sync settings.
 */

@Component
public class UIRemoteProjectService {
	private final MessageSource messageSource;
	private final ProjectService projectService;
	private final ProjectRemoteService projectRemoteService;
	private final UserService userService;

	@Autowired
	public UIRemoteProjectService(MessageSource messageSource, ProjectService projectService,
			ProjectRemoteService projectRemoteService, UserService userService) {
		this.messageSource = messageSource;
		this.projectService = projectService;
		this.projectRemoteService = projectRemoteService;
		this.userService = userService;
	}

	/**
	 * Update the project sync settings
	 *
	 * @param projectId                          the project id to update
	 * @param remoteProjectSettingsUpdateRequest object which
	 *                                           is used to update frequency, and sync user, as well as
	 *                                           force sync for a project
	 * @param principal                          The current logged in user
	 * @param locale                             user's locale
	 * @return {@link String}
	 * @throws Exception if user cannot read the remote project or project is not found
	 */
	public String updateProjectSyncSettings(Long projectId,
			RemoteProjectSettingsUpdateRequest remoteProjectSettingsUpdateRequest, Principal principal, Locale locale)
			throws Exception {

		try {
			Project project = projectService.read(projectId);
			RemoteStatus remoteStatus = project.getRemoteStatus();
			Map<String, Object> updates = new HashMap<>();
			String message = null;

			if (remoteProjectSettingsUpdateRequest.getProjectSyncFrequency() != null) {
				updates.put("syncFrequency", remoteProjectSettingsUpdateRequest.getProjectSyncFrequency());
				message = messageSource.getMessage("server.ProjectRemote.frequency.change",
						new Object[] { remoteProjectSettingsUpdateRequest.getProjectSyncFrequency() }, locale);
			}

			if (remoteProjectSettingsUpdateRequest.getMarkSync()) {
				remoteStatus.setSyncStatus(RemoteStatus.SyncStatus.MARKED);
				updates.put("remoteStatus", remoteStatus);
				message = messageSource.getMessage("server.ProjectRemote.marked.for.sync", new Object[] {}, locale);
			}

			if (remoteProjectSettingsUpdateRequest.getForceSync()) {
				remoteStatus.setSyncStatus(RemoteStatus.SyncStatus.FORCE);
				updates.put("remoteStatus", remoteStatus);
				message = messageSource.getMessage("server.ProjectRemote.marked.for.sync", new Object[] {}, locale);
			}

			if (remoteProjectSettingsUpdateRequest.getChangeUser()) {
				// ensure the user can read the project
				try {
					projectRemoteService.read(remoteStatus.getURL());

					User user = userService.getUserByUsername(principal.getName());
					remoteStatus.setReadBy(user);
					updates.put("remoteStatus", remoteStatus);

					message = messageSource.getMessage("server.ProjectRemote.userchange", new Object[] {}, locale);
				} catch (Exception ex) {
					throw new Exception(
							messageSource.getMessage("server.ProjectRemote.userchange.error", new Object[] {}, locale));
				}
			}

			projectService.updateProjectSettings(project, updates);

			return message;

		} catch (Exception ex) {
			throw new Exception(
					messageSource.getMessage("server.ProjectRemote.unable.to.find", new Object[] { projectId },
							locale));
		}
	}

	/**
	 * Gets the remote synchronization {@link Project} settings
	 *
	 * @param projectId the ID of the {@link Project} to read
	 * @param locale    user's locale
	 * @return {@link RemoteProjectSettings}
	 * @throws Exception throws Exception if project is not found
	 */
	public RemoteProjectSettings getProjectRemoteSettings(Long projectId, Locale locale) throws Exception {
		try {
			Project project = projectService.read(projectId);

			RemoteStatus remoteStatus = project.getRemoteStatus();
			Date lastUpdate = remoteStatus.getLastUpdate();
			RemoteAPI remoteAPI = remoteStatus.getApi();
			ProjectSyncFrequency[] projectSyncFrequencies = ProjectSyncFrequency.values();
			ProjectSyncFrequency projectSyncFrequency = project.getSyncFrequency();
			User syncUser = remoteStatus.getReadBy();

			return new RemoteProjectSettings(remoteStatus, lastUpdate, remoteAPI, projectSyncFrequencies,
					projectSyncFrequency, syncUser);
		} catch (Exception e) {
			throw new Exception(
					messageSource.getMessage("server.ProjectRemote.unable.to.find", new Object[] { projectId },
							locale));
		}
	}
}


text:
<?php

namespace Symfony\Component\Form\Extension\Validator\Validator;

use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormValidatorInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Util\VirtualFormAwareIterator;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\Validator\ValidatorInterface;
use Symfony\Component\Validator\ExecutionContext;

class DelegatingValidator implements FormValidatorInterface
{
    private $validator;

    public function __construct(ValidatorInterface $validator)
    {
        $this->validator = $validator;
    }

    /**
     * Validates the form and its domain object.
     *
     * @param FormInterface $form A FormInterface instance
     */
    public function validate(FormInterface $form)
    {
        if ($form->isRoot()) {
            $mapping = array();
            $forms = array();

            $this->buildFormPathMapping($form, $mapping);
            $this->buildDataPathMapping($form, $mapping);
            $this->buildNamePathMapping($form, $forms);
            $this->resolveMappingPlaceholders($mapping, $forms);

            // Validate the form in group "Default"
            // Validation of the data in the custom group is done by validateData(),
            // which is constrained by the Execute constraint
            if ($form->hasAttribute('validation_constraint')) {
                $violations = $this->validator->validateValue(
                    $form->getData(),
                    $form->getAttribute('validation_constraint'),
                    self::getFormValidationGroups($form)
                );
            } else {
                $violations = $this->validator->validate($form);
            }

            if ($violations) {
                foreach ($violations as $violation) {
                    $propertyPath = $violation->getPropertyPath();
                    $template = $violation->getMessageTemplate();
                    $parameters = $violation->getMessageParameters();
                    $error = new FormError($template, $parameters);

                    foreach ($mapping as $mappedPath => $child) {
                        if (preg_match($mappedPath, $propertyPath)) {
                            $child->addError($error);
                            continue 2;
                        }
                    }

                    $form->addError($error);
                }
            }
        }
    }

    /**
     * Validates the data of a form
     *
     * This method is called automatically during the validation process.
     *
     * @param FormInterface    $form    The validated form
     * @param ExecutionContext $context The current validation context
     */
    public static function validateFormData(FormInterface $form, ExecutionContext $context)
    {
        if (is_object($form->getData()) || is_array($form->getData())) {
            $propertyPath = $context->getPropertyPath();
            $graphWalker = $context->getGraphWalker();

            // The Execute constraint is called on class level, so we need to
            // set the property manually
            $context->setCurrentProperty('data');

            // Adjust the property path accordingly
            if (!empty($propertyPath)) {
                $propertyPath .= '.';
            }

            $propertyPath .= 'data';

            foreach (self::getFormValidationGroups($form) as $group) {
                $graphWalker->walkReference($form->getData(), $group, $propertyPath, true);
            }
        }
    }

    static protected function getFormValidationGroups(FormInterface $form)
    {
        $groups = null;

        if ($form->hasAttribute('validation_groups')) {
            $groups = $form->getAttribute('validation_groups');
        }

        $currentForm = $form;
        while (!$groups && $currentForm->hasParent()) {
            $currentForm = $currentForm->getParent();

            if ($currentForm->hasAttribute('validation_groups')) {
                $groups = $currentForm->getAttribute('validation_groups');
            }
        }

        if (null === $groups) {
            $groups = array('Default');
        }

        return (array) $groups;
    }

    private function buildFormPathMapping(FormInterface $form, array &$mapping, $formPath = '', $namePath = '')
    {
        if ($formPath) {
            $formPath .= '.';
        }

        if ($namePath) {
            $namePath .= '.';
        }

        foreach ($form->getAttribute('error_mapping') as $nestedDataPath => $nestedNamePath)
        {
            $mapping['/^'.preg_quote($formPath . 'data.' . $nestedDataPath).'(?!\w)/'] = $namePath . $nestedNamePath;
        }

        $iterator = new VirtualFormAwareIterator($form->getChildren());
        $iterator = new \RecursiveIteratorIterator($iterator);

        foreach ($iterator as $child) {
            $path = (string)$child->getAttribute('property_path');
            $parts = explode('.', $path, 2);

            $nestedNamePath = $namePath . $child->getName();
            $nestedFormPath = $formPath . 'children[' . $parts[0] . ']';

            if (isset($parts[1])) {
                $nestedFormPath .= '.data.' . $parts[1];
            }

            $nestedDataPath = $formPath . 'data.' . $path;

            if ($child->hasChildren()) {
                $this->buildFormPathMapping($child, $mapping, $nestedFormPath, $nestedNamePath);
                $this->buildDataPathMapping($child, $mapping, $nestedDataPath, $nestedNamePath);
            }

            $mapping['/^'.preg_quote($nestedFormPath, '/').'(?!\w)/'] = $child;
            $mapping['/^'.preg_quote($nestedDataPath, '/').'(?!\w)/'] = $child;
        }
    }

    private function buildDataPathMapping(FormInterface $form, array &$mapping, $dataPath = 'data', $namePath = '')
    {
        if ($namePath) {
            $namePath .= '.';
        }

        foreach ($form->getAttribute('error_mapping') as $nestedDataPath => $nestedNamePath)
        {
            $mapping['/^'.preg_quote($dataPath . '.' . $nestedDataPath).'(?!\w)/'] = $namePath . $nestedNamePath;
        }

        $iterator = new VirtualFormAwareIterator($form->getChildren());
        $iterator = new \RecursiveIteratorIterator($iterator);

        foreach ($iterator as $child) {
            $path = (string)$child->getAttribute('property_path');

            $nestedNamePath = $namePath . $child->getName();
            $nestedDataPath = $dataPath . '.' . $path;

            if ($child->hasChildren()) {
                $this->buildDataPathMapping($child, $mapping, $nestedDataPath, $nestedNamePath);
            } else {
                $mapping['/^'.preg_quote($nestedDataPath, '/').'(?!\w)/'] = $child;
            }
        }
    }

    private function buildNamePathMapping(FormInterface $form, array &$forms, $namePath = '')
    {
        if ($namePath) {
            $namePath .= '.';
        }

        $iterator = new VirtualFormAwareIterator($form->getChildren());
        $iterator = new \RecursiveIteratorIterator($iterator);

        foreach ($iterator as $child) {
            $nestedNamePath = $namePath . $child->getName();
            $forms[$nestedNamePath] = $child;

            if ($child->hasChildren()) {
                $this->buildNamePathMapping($child, $forms, $nestedNamePath);
            }

        }
    }

    private function resolveMappingPlaceholders(array &$mapping, array $forms)
    {
        foreach ($mapping as $pattern => $form) {
            if (is_string($form)) {
                if (!isset($forms[$form])) {
                    throw new FormException(sprintf('The child form with path "%s" does not exist', $form));
                }

                $mapping[$pattern] = $forms[$form];
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using VkNet.Enums;
using VkNet.Enums.SafetyEnums;
using VkNet.Utils.JsonConverter;

namespace VkNet.Model;

/// <summary>
/// Описание рекламного аккаунта.
/// </summary>
/// <remarks>
/// См. описание https://vk.com/dev/ads.getAccounts
/// </remarks>
[Serializable]
public class Ad
{
	/// <summary>
	/// Идентификатор рекламного объявления.
	/// </summary>
	[JsonProperty("id")]
	public long Id { get; set; }

	/// <summary>
	/// Идентификатор кампании.
	/// </summary>
	[JsonProperty("campaign_id")]
	public long CampaignId { get; set; }

	/// <summary>
	/// Формат объявления
	/// </summary>
	[JsonProperty("ad_format")]
	public AdFormat AdFormat { get; set; }

	/// <summary>
	/// Тип оплаты
	/// </summary>
	[JsonProperty("cost_type")]
	public CostType CostType { get; set; }

	/// <summary>
	/// Цена за переход в копейках. (если cost_type = 0)
	/// </summary>
	[JsonProperty("cpc")]
	public long Cpc { get; set; }

	/// <summary>
	/// Цена за 1000 показов в копейках. (если cost_type = 1)
	/// </summary>
	[JsonProperty("cpm")]
	public long Cpm { get; set; }

	/// <summary>
	/// Цена за 1000 показов в копейках. (если cost_type = 1)
	/// </summary>
	[JsonProperty("ocpm")]
	public long OCpm { get; set; }

	/// <summary>
	/// (если задано) Ограничение количества показов данного объявления на одного пользователя.
	/// Может присутствовать для некоторых форматов объявлений, для которых разрешена установка точного значения.
	/// </summary>
	[JsonProperty("impressions_limit")]
	public long ImpressionsLimit { get; set; }

	/// <summary>
	/// (если задано) Признак того, что количество показов объявления на одного пользователя ограничено.
	/// Может присутствовать для некоторых объявлений, для которых разрешена установка ограничения, но не разрешена установка точного значения.
	/// 1 — не более 100 показов на одного пользователя.
	/// </summary>
	[JsonProperty("impressions_limited")]
	public long ImpressionsLimited { get; set; }

	/// <summary>
	/// Рекламные площадки, на которых будет показываться объявление. (если значение применимо к данному формату объявления)
	/// </summary>
	[JsonProperty("ad_platform")]
	[JsonConverter(typeof(SafetyEnumJsonConverter))]
	public AdPlatform AdPlatform { get; set; }

	/// <summary>
	/// 1 — для объявления задано ограничение «Не показывать на стенах сообществ».
	/// </summary>
	[JsonProperty("ad_platform_no_wall")]
	public bool AdPPlatformNoWall { get; set; }

	/// <summary>
	/// 1 — для объявления задано ограничение «Показывать в рекламной сети».
	/// </summary>
	[JsonProperty("ad_platform_no_ad_network")]
	public bool AdPlatformNoAdNetwork { get; set; }

	/// <summary>
	/// Общий лимит объявления в рублях. 0 — лимит не задан.
	/// </summary>
	[JsonProperty("all_limit")]
	public long AllLimit { get; set; }

	/// <summary>
	/// Дневной лимит объявления в рублях. 0 — лимит не задан.
	/// </summary>
	[JsonProperty("day_limit")]
	public long DayLimit { get; set; }

	/// <summary>
	/// Ограничение по возрасту
	/// </summary>
	[JsonProperty("age_restriction")]
	public AdAgeRestriction AgeRestriction { get; set; }

	/// <summary>
	/// Время создания объявления
	/// </summary>
	[JsonProperty(propertyName: "create_time")]
	[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
	public DateTime? CreateTime { get; set; }

	/// <summary>
	/// Время последнего изменения объявления
	/// </summary>
	[JsonProperty(propertyName: "update_time")]
	[JsonConverter(converterType: typeof(UnixDateTimeConverter))]
	public DateTime? UpdateTime { get; set; }

	/// <summary>
	/// ID тематики или подраздела тематики объявления.
	/// </summary>
	[JsonProperty(propertyName: "category1_id")]
	public long Category1Id { get; set; }

	/// <summary>
	/// ID тематики или подраздела тематики объявления. Дополнительная тематика.
	/// </summary>
	[JsonProperty(propertyName: "category2_id")]
	public long Category2Id { get; set; }

	/// <summary>
	/// Cтатус объявления.
	/// </summary>
	[JsonProperty(propertyName: "status")]
	public AdStatus Status { get; set; }

	/// <summary>
	/// Название объявления.
	/// </summary>
	[JsonProperty(propertyName: "name")]
	public string Name { get; set; }

	/// <summary>
	/// Cтатус модерации объявления
	/// </summary>
	[JsonProperty(propertyName: "approved")]
	public ModerationStatus ModerationStatus { get; set; }

	/// <summary>
	/// Объявление является видеорекламой
	/// </summary>
	[JsonProperty(propertyName: "video")]
	public long Video { get; set; }

	/// <summary>
	/// Включено отображение предупреждения: «Есть противопоказания.Требуется консультация специалиста.»
	/// </summary>
	[JsonProperty(propertyName: "disclaimer_medical")]
	public long DisclaimerMedical { get; set; }

	/// <summary>
	/// Включено отображение предупреждения: «Необходима консультация специалистов.»
	/// </summary>
	[JsonProperty(propertyName: "disclaimer_specialist")]
	public long DisclaimerSpecialist { get; set; }

	/// <summary>
	/// Включено отображение предупреждения: «БАД.Не является лекарственным препаратом.»
	/// </summary>
	[JsonProperty(propertyName: "disclaimer_supplements")]
	public long DisclaimerSupplements { get; set; }

	/// <summary>
	/// Только для ad_format = 9 (Public). Описание событий, собираемых в группы ретаргетинга. Массив объектов, где ключом является id группы ретаргетинга, а значением - массив событий.
	/// </summary>
	/// <remarks>
	/// TODO: выпилить ToNullIfArrayConverter
	/// </remarks>
	[JsonProperty("events_retargeting_groups")]
	[JsonConverter(typeof(ToNullIfArrayConverter<Dictionary<long, List<EventsRetargetingGroup>>>))]
	public Dictionary<long, List<EventsRetargetingGroup>> EventsRetargetingGroups { get; set; }
}


text:
"""[path]
cd /Users/brunoflaven/Documents/01_work/blog_articles/webscraping_with_python

[command]
python seleniumControl_5.py

"""

from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://flaven.fr/')
# searchElem = browser.find_element_by_xpath('//*[@id="search-2"]/form/label/input')
searchElem = browser.find_element_by_xpath('//*[@id="search-2"]/form/label/input')
searchElem.send_keys("Python")
submitElem = browser.find_element_by_css_selector(
    '.search-submit')
submitElem.submit()


text:
using Leak.Common;

namespace Leak.Peer.Coordinator.Events
{
    public class BlockRequested
    {
        public FileHash Hash;

        public PeerHash Peer;

        public BlockIndex Block;
    }
}


text:
<!--

       Copyright 2012-2016 XebiaLabs B.V.

       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.

-->
<domain type='kvm'>
  <name>domain-with-filesystem</name>
  <uuid>9d0f600e-d24f-1ea2-0afe-1c84826de376</uuid>
  <description>Domain with file system</description>
  <memory unit='KiB'>2097152</memory>
  <currentMemory unit='KiB'>2097152</currentMemory>
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-1.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
    <pae/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>restart</on_crash>
  <devices>
    <emulator>/usr/bin/kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/var/lib/libvirt/images/domain-with-filesystem.qcow2'/>
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </disk>
    <disk type='block' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <target dev='hdc' bus='ide'/>
      <readonly/>
      <address type='drive' controller='0' bus='1' target='0' unit='0'/>
    </disk>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <controller type='usb' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <filesystem type='mount' accessmode='passthrough'>
      <source dir='/mnt/data'/>
      <target dir='/data'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </filesystem>
    <filesystem type='mount' accessmode='passthrough'>
      <source dir='/mnt/vagrant'/>
      <target dir='/vagrant'/>
      <readonly/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
    </filesystem>
    <interface type='bridge'>
      <mac address='52:54:00:3a:8f:83'/>
      <source bridge='br0'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>
    <graphics type='vnc' port='-1' autoport='yes'/>
    <video>
      <model type='cirrus' vram='9216' heads='1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </memballoon>
  </devices>
</domain>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingLeft="@dimen/stock_fragment_padding_left"
    android:paddingRight="@dimen/stock_fragment_padding_right">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="left"
        android:orientation="vertical">

        <TextView
            android:id="@+id/stockName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/stock_name"
            android:textSize="@dimen/stock_name" />

        <TextView
            android:id="@+id/stockCode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/stock_id"
            android:textSize="@dimen/stock_code" />

    </LinearLayout>

    <TextView
        android:id="@+id/stockClose"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:gravity="center"
        android:textSize="@dimen/stock_float" />

    <TextView
        android:id="@+id/stockChange"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:textSize="@dimen/stock_float" />

</LinearLayout>


text:
import { ArrowsHorizontal24 } from "../../";

export = ArrowsHorizontal24;


text:
/*
 * Created on 08/10/2006
 */
package llvmmop.parser.ast.visitor;

/**
 * @author Julio Vilmar Gesser
 */
public final class SourcePrinter {

    private int level = 0;

    private boolean indented = false;

    private final StringBuilder buf = new StringBuilder();

    public void indent() {
        level++;
    }

    public void unindent() {
        level--;
    }

    private void makeIndent() {
        for (int i = 0; i < level; i++) {
            buf.append("    ");
        }
    }

    public void print(String arg) {
        if (!indented) {
            makeIndent();
            indented = true;
        }
        buf.append(arg);
    }

    public void printLn(String arg) {
        print(arg);
        printLn();
    }

    public void printLn() {
        buf.append("\n");
        indented = false;
    }

    public String getSource() {
        return buf.toString();
    }

    @Override
    public String toString() {
        return getSource();
    }
}


text:
package org.spongepowered.common.item.recipe.crafting;

import net.minecraft.item.crafting.Ingredient;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.common.item.inventory.util.ItemStackUtil;

import java.util.List;
import java.util.function.Predicate;

import javax.annotation.Nullable;

public class CustomIngredient extends Ingredient {

    public final List<Predicate<ItemStack>> predicates;
    public final List<ItemStack> matchItems;

    public CustomIngredient(final List<Predicate<ItemStack>> predicates, final List<ItemStack> matchItems, final List<ItemStack> displayItems) {
        super(ItemStackUtil.toNative(displayItems));
        this.predicates = predicates;
        this.matchItems = matchItems;
    }

    @Override
    public boolean apply(@Nullable final net.minecraft.item.ItemStack item) {

        // first check for matching predicates
        if (this.predicates.stream().anyMatch(p -> p.test(ItemStackUtil.fromNative(item)))) {
            return true;
        }

        // then apply same logic as super.apply(..) but with this.items
        if (item == null) {
            return false;
        }

        for (final ItemStack itemStack : this.matchItems) {
            final net.minecraft.item.ItemStack nativeItem = ItemStackUtil.toNative(itemStack);
            if (nativeItem.getItem() == item.getItem()) {
                final int i = nativeItem.getMetadata();

                if (i == 32767 || i == item.getMetadata())
                {
                    return true;
                }
            }
        }
        return false;
    }
}


text:
var slideIndex = 0;
showSlides();

function showSlides() {
				    var i;
	var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
				    }
		   slideIndex++;
			    if (slideIndex> slides.length) {slideIndex = 1}
			    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
			    }
			    slides[slideIndex-1].style.display = "block";
			    dots[slideIndex-1].className += " active";
		    setTimeout(showSlides, 2000); // Change image every 2 seconds
			}


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

namespace HTLib3
{
    public static partial class Collections
    {
        public static int HIndexEqual(this string[] values, string item)
        {
            IList<string> _values = values;
            return _values.IndexOf(item);
        }
        public static int HIndexEqualReference<T>(this T values, IList<T> searchFrom)
            where T : class
        {
            for(int i=0; i<searchFrom.Count; i++)
                if(object.ReferenceEquals(values, searchFrom[i]))
                    return i;
            return -1;
        }
        public static List<int> HIndexEqualReference<T>(this IList<T> values, IList<T> searchFrom)
            where T : class
        {
            int[] index = new int[values.Count];
            for(int i=0; i<values.Count; i++)
                index[i] = values[i].HIndexEqualReference(searchFrom);
            return new List<int>(index);
        }
    }
}


text:
import tempfile
from urlparse import urlparse
import math
import fnmatch
import os
import importlib
import time
import datetime
from HTMLParser import HTMLParser

import requests
from pycountry import countries
from fuzzywuzzy import process
import ftputil
from unidecode import unidecode
from PIL import Image
from django.conf import settings
from django.core.urlresolvers import reverse

THUMBNAIL_DIMS = (120, 70)  # preferred width/height of thumbnails

IMAGE_TYPE_GENERAL = 0
IMAGE_TYPE_VENDOR_THUMB = 1
IMAGE_TYPE_PHOTO_THUMB = 2
IMAGE_TYPE_SELECTED_THUMB = 3
IMAGE_TYPE_EXTENDED = 4
IMAGE_TYPE_SPECIALS = 5
IMAGE_TYPE_FEATURES = 6
IMAGE_TYPE_DINING = 7
IMAGE_TYPE_ACTIVITIES = 8
IMAGE_TYPE_AMENITIES = 9

def td2HHMMSSstr(td):
    '''Convert timedelta objects to a HH:MM:SS string with (+/-) sign'''
    if td < datetime.timedelta(seconds=0):
        sign='-'
        td = -td
    else:
        sign = ''
    tdhours, rem = divmod(td.total_seconds(), 3600)
    tdminutes, tdseconds = divmod(rem, 60)
    if int(tdhours) > 0:
        tdstr = '{}{:}:'.format(sign, int(tdhours))
    else:
        tdstr = '{}'.format(sign)
    tdstr = tdstr + '{:02d}:{:02d}'.format(int(tdminutes), int(tdseconds))
    return tdstr

def fetchfile(source):
    '''Return an open file object.  If the source contains a url then the
    requests library is used to download the content and store as a
    temporary file and return that temporary file.
    '''

    if '://' in source:
        ignored, filename = tempfile.mkstemp()
        with open(filename, 'wb') as f:
            r = requests.get(source)
            f.write(r.content)
        return open(filename, 'rb')

    return open(source, 'rb')

def moduleitem(dottedpath):
    mname = '.'.join(dottedpath.split('.')[:-1])
    itemname = dottedpath.split('.')[-1]
    module_ = importlib.import_module(mname)
    item = getattr(module_, itemname)
    return item

def image_path(type_, id, full=True):
    short = '%012i' % int(id)
    target = '%s/%s/%s/%s.jpg' % (type_, short[:4], short[4:8], short)
    if full:
        target = os.path.join(settings.IMAGE_DIR, target)
    return target

def update_image(type_, image, url, width=-1, height=-1):
    target = image_path(type_, image.id)
    local = os.path.dirname(target)
    if not os.path.exists(local):
        os.makedirs(local)
    headers = {
    }
    if os.path.exists(target):
        updated = time.ctime(os.path.getmtime(target))
        headers['If-Modified-Since'] = time.strftime('%a, %d %b %Y %H:%M:%S +0000', time.strptime(updated))
    if width != -1:
        grab_and_scale(url, target, width, height)
    else:
        grab(url, target)

country_names = [x.name for x in countries]

def lookup_country_code(name):
    name = name.replace('St. ', 'Saint ')
    real_name = process.extractOne(name, country_names)
    return countries.get(name=real_name[0]).alpha2

class TreeHelper(object):
    def __init__(self, tree):
        self.tree = tree

    @property
    def root(self):
        return self.tree.getroot()

    def xpath_single(self, xp):
        if self.root.xpath(xp):
            return self.root.xpath(xp)[0]
        else:
            return False

    def xpath_text(self, xp):
        node = self.xpath_single(xp)
        if node != False:
            return node.text
        else:
            return ''

    def xpath_attr(self, xp, attr):
        return self.xpath_single(xp).attrib[attr]

class XMLNodeHelper(object):
    def __init__(self, node, namespaces=None):
        self.node = node
        self.namespaces = namespaces

    def xpath_single(self, xp):
        if self.namespaces:
            res = self.node.xpath(xp, namespaces=self.namespaces)
        else:
            res = self.node.xpath(xp)

        if len(res) == 0:
            return None

        return res[0]

    def xpath_text(self, xp):
        el = self.xpath_single(xp)
        if el is None:
            return ''
        return el.text

    def xpath_attr(self, xp, attr):
        el = self.xpath_single(xp)
        if el is None:
            return ''
        if attr in el.attrib:
            return el.attrib[attr]
        return ''

    def xpath(self, xp):
        if self.namespaces:
            return self.node.xpath(xp, namespaces=self.namespaces)
        return self.node.xpath(xp)

def grab_to_temp(url, verify=True):
    handle, filename = tempfile.mkstemp()
    os.close(handle)
    grab(url, filename, verify)
    return filename

def grab(url, target, verify=True):
    if url.startswith('ftp://'):
        # handle ftp download
        o = urlparse(url)
        pieces = o.netloc.split('@')
        host = pieces[-1]
        parts = [host]
        path = o.path
        if path.startswith('/'):
            path = path[1:]
        if len(pieces) > 1:
            username, password = pieces[0].split(':')
            parts.append(username)
            parts.append(password)
        ftp = ftputil.FTPHost(*parts)
        for filename in ftp.listdir('.'):
            if not fnmatch.fnmatch(filename, path):
                continue
            ftp.download(filename, target)
        return

    headers = {}
    if os.path.exists(target) and os.path.getsize(target) > 0:
        updated = time.ctime(os.path.getmtime(target))
        headers['If-Modified-Since'] = time.strftime(
            '%a, %d %b %Y %H:%M:%S +0000', time.strptime(updated))

    if url.startswith('http'):
        res = requests.get(url, headers=headers, stream=True, verify=verify)
        if res.status_code == 200:
            with open(target, 'wb') as f:
                for chunk in res.iter_content(2048):
                    f.write(chunk)
        elif res.status_code != 304:
            raise IOError('Error (%s) while trying to remotely request: %s'
                          % (res.status_code, url))
    else:
        res = None
        with open(target, 'wb') as fout, open(url, 'rb') as fin:
            chunk = None
            while chunk is None or len(chunk) == 2048:
                chunk = fin.read(2048)
                fout.write(chunk)

    return res

def grab_and_scale(url, target, width, height):
    ignored, tmp1 = tempfile.mkstemp(suffix='.jpg')

    try:
        grab(url, tmp1)
        im = Image.open(tmp1)
        im.thumbnail((width, height), Image.ANTIALIAS)
        im.save(target, "JPEG")
    finally:
        if os.path.exists(tmp1):
            os.remove(tmp1)

def first(query):
    try:
        return query[0]
    except:
        return None

def lookup_location(country_s, region_s=None, city_s=None):

    from cities.models import Country, Region, City
    country = None
    country_opts = [country_s]
    if '/' in country_s:
        country_opts = country_s.split('/')
    for country_s in country_opts:
        if country_s.lower().startswith('us '):
            country_s = 'U.S. ' + country_s[3:]
        if country_s.lower().startswith('st. '):
            country_s = 'Saint ' + country_s[4:]
        if country_s.lower() == 'equador':
            country_s = 'ecuador'
        if country_s == 'USA':
            country_s = 'US'
        if country_s == 'UAE':
            country_s = 'AE'
        if len(country_s) == 2:
            country = first(Country.objects.filter(code=country_s))
        if country is None:
            country = first(Country.objects.filter(slug=country_s))
        if country is None:
            country = first(Country.objects.filter(name__icontains=country_s))
        if country is not None:
            break
    if country is None:
        raise ValueError('Could not find country: ' + country_s)

    if not region_s and not city_s:
        return country

    region = first(Region.objects.filter(code=region_s, country=country))
    if region is None:
        region = first(Region.objects.filter(slug=region_s, country=country))
    if region is None:
        region = first(Region.objects.filter(
            name__icontains=region_s, country=country))
    if region is None:
        q = Region.objects.values('name').filter(country=country)
        values = [x['name'] for x in q.all()]
        if values:
            r = process.extractOne(region_s, values)
            if r is not None and len(r) > 0:
                region = first(Region.objects.filter(
                    name=r[0], country=country))

    if not city_s:
        if region is not None:
            return region
        return country

    city = None
    if region is not None:
        city = first(City.objects.filter(
            slug=city_s, country=country, region=region))
        if city is None:
            city = first(City.objects.filter(
                name__icontains=city_s, country=country, region=region))
        if city is None:
            q = City.objects.values('name').filter(
                country=country, region=region)
            values = [x['name'] for x in q.all()]
            if values:
                r = process.extractOne(city_s, values)[0]
                city = first(City.objects.filter(
                    name=r, country=country, region=region))
    if city is None:
        q = City.objects.values('name').filter(country=country)
        values = [x['name'] for x in q.all()]
        if values:
            r = process.extractOne(city_s, values)
            if r is not None and len(r) > 0:
                city = first(City.objects.filter(name=r[0], country=country))
    if city is None:
        raise ValueError('Could not find city (%s:%i): %s '
                         '[original: %s / %s / %s]'
                         % (region,
                            getattr(region, 'id', -1),
                            city_s, country_s, region_s, city_s))

    return city

def lookup_city(country_s, region_s, city_s):
    from cities.models import Country, Region, City
    country = None
    if country_s == 'USA':
        country_s = 'US'
    if len(country_s) == 2:
        country = first(Country.objects.filter(code=country_s))
    if country is None:
        country = first(Country.objects.filter(slug=country_s))
    if country is None:
        country = first(Country.objects.filter(name__icontains=country_s))
    if country is None:
        raise ValueError('Could not find country: ' + country_s)

    region = first(Region.objects.filter(code=region_s, country=country))
    if region is None:
        region = first(Region.objects.filter(slug=region_s, country=country))
    if region is None:
        region = first(Region.objects.filter(name__icontains=region_s, country=country))
    if region is None:
        values = [x['name'] for x in Region.objects.values('name').filter(country=country).all()]
        if values:
            r = process.extractOne(region_s, values)
            if r is not None and len(r) > 0:
                region = first(Region.objects.filter(name=r[0], country=country))

    city = None
    if region is not None:
        city = first(City.objects.filter(slug=city_s, country=country, region=region))
        if city is None:
            city = first(City.objects.filter(name__icontains=city_s, country=country, region=region))
        if city is None:
            values = [x['name'] for x in City.objects.values('name').filter(country=country, region=region).all()]
            if values:
                possible_city = process.extractOne(city_s, values)
                if possible_city is not None:
                    r = possible_city[0]
                    city = first(City.objects.filter(name=r, country=country, region=region))
    if city is None:
        values = [x['name'] for x in City.objects.values('name').filter(country=country).all()]
        if values:
            r = process.extractOne(city_s, values)
            if r is not None and len(r) > 0:
                city = first(City.objects.filter(name=r[0], country=country))
    if city is None:
        raise ValueError('Could not find city (%s:%i): %s [original: %s / %s / %s]' % (region, getattr(region, 'id', -1), city_s, country_s, region_s, city_s))

    return city

def dict_value(obj, field, d):
    current = obj
    current_d = d
    s = field.split('.')
    for num, y in enumerate(s):
        if current is None:
            return None
        if num < len(s) - 1:
            t = current_d.get(y, {})
            current_d[y] = t
            current_d = current_d[y]
        else:
            current_d[y] = getattr(current, y)
        current = getattr(current, y)

def shorten(text, width, **kwargs):
    text = strip_tags(text or u'')
    if len(text) < width:
        return text
    s = text.strip().split()
    res = u''
    for x in s:
        res += u' ' + unicode(x)
        if len(res) >= width:
            break

    if res >= width:
        res += u' ...'

    return res

def get_location(country_slug, region_slug, city_slug):
    from cities.models import Country, Region, City
    location = None
    if region_slug == '-':
        location = Country.objects.get(slug=country_slug)
    elif city_slug == '-':
        country = Country.objects.get(slug=country_slug)
        location = Region.objects.get(country_id=country.id,
                                      slug=region_slug)
    else:
        country = Country.objects.get(slug=country_slug)
        region = Region.objects.get(slug=region_slug,
                                    country_id=country.id)
        location = City.objects.get(slug=city_slug,
                                    region_id=region.id,
                                    country_id=country.id)
    return Location(location)

class Location(object):
    def __init__(self, id_or_object, type_=None):
        if isinstance(id_or_object, int):
            self.id = id_or_object
            self.type_ = type_
        else:
            self.id = id_or_object.id
            self.type_ = id_or_object.__class__.__name__.lower()

    @property
    def item(self):
        from cities.models import Country, Region, City
        if self.type_ == 'city':
            city = City.objects.get(id=self.id)
            return city
        elif self.type_ == 'region':
            region = Region.objects.get(id=self.id)
            return region
        else:
            country = Country.objects.get(id=self.id)
            return country

    @property
    def slug(self):
        from cities.models import Country, Region, City
        if self.type_ == 'city':
            city = City.objects.get(id=self.id)
            return [str(city.country.slug), str(city.region.slug), str(city.slug)]
        elif self.type_ == 'region':
            region = Region.objects.get(id=self.id)
            return [str(region.country.slug), str(region.slug), '-']
        else:
            country = Country.objects.get(id=self.id)
            return [str(country.slug), '-', '-']

    @property
    def dest_urls(self):
        item = self.item
        if self.type_ == 'city':
            args = [item.country.slug, item.region.slug, item.slug]
        elif self.type_ == 'region':
            args = [item.country.slug, item.slug, '-']
        else:
            args = [item.slug, '-', '-']
        return {
            'destination': reverse('destination', args=args),
            'hotels': reverse('dest_hotels', args=args),
            'vacation_rentals': reverse('dest_vacation_rentals', args=args),
            'activities': reverse('dest_activities', args=args),
            'restaurants': reverse('dest_restaurants', args=args),
            'beaches': reverse('dest_beaches', args=args),
            'deals': reverse('dest_deals', args=args),
        }

    def address(self):
        if self.type_ == 'city':
            return str('%s, %s, %s' % (self.item.country.name,
                                       self.item.region.name,
                                       self.item.name))
        elif self.type_ == 'region':
            return str('%s, %s' % (self.item.country.name,
                                   self.item.name))
        return str('%s' % self.item.name)

    def as_dict(self):
        return {
            'id': self.id,
            'type': self.type_,
            'slug': self.slug,
            'address': self.address(),
        }

def get_api_url(request):
    api_url = os.environ.get('API_URL', None)
    if api_url is None:
        api_url = getattr(settings, 'API_SEARCH_URL', None)
    if api_url is None:
        http_host = request.META['HTTP_HOST']
        if 'cms' not in http_host:
            s = 'http://cms.%s/api/v1/'
        else:
            s = 'http://%s/api/v1/'
        api_url = s % http_host
    return api_url

ignore_slug_words = set([
    'a',
    'the',
    'is',
])

import re
escape_re = re.compile(r'%([0-9a-fA-F][0-9a-fA-F])')

def _unescape_http_code(match):
    code = int(match.group(1), 16)
    return chr(code)

def http_unescape(s):
    if s:
        return escape_re.sub(_unescape_http_code, s)
    else:
        return s

def slugify(s):
    part1 = http_unescape(s)
    if isinstance(part1, str):
        part1 = part1.decode('utf8')
    elif not isinstance(part1, unicode):
        part1 = unicode(part1)

    part1 = unidecode(part1).strip()
    # part1 is now a competely safe ascii string

    part2 = ''
    for x in part1:
        x = x.lower()
        if x.isalnum():
            part2 += x
        else:
            if not part2.endswith('-'):
                part2 += '-'

    words = []
    for word in part2.split('-'):
        if word not in ignore_slug_words:
            words.append(word)
    new_slug = '-'.join(words)
    if new_slug.startswith('-'):
        new_slug = new_slug[1:]
    if new_slug.endswith('-'):
        new_slug = new_slug[:-1]
    new_slug = new_slug.replace('-------', '-').replace('------', '-').replace('-----', '-').replace('----', '-').replace('---', '-').replace('--', '-')
    return new_slug

_range = range(1000)

def unique_resource_slug(resource_class, s):
    orig_slug = slug = slugify(s)
    for x in _range:
        if resource_class.objects.filter(slug=slug).count() == 0:
            return slug
        slug = orig_slug + '-' + str(x+1)

def unique_slugify(obj, value, slug_field_name='slug', times_to_try=1000):
    if not value:
        return False
    slug_field = obj._meta.get_field(slug_field_name)
    slug_len = slug_field.max_length

    orig_slug = slugify(value)
    if orig_slug.startswith('-'):
        orig_slug = orig_slug[1:]
    slug = orig_slug

    # This line is not needed in cases where developer calls unique slugify again and needs to resolve conflicts
    # if getattr(obj, slug_field_name) == slug:
    #     return False

    base_q = obj.__class__.objects.only('id', 'slug').exclude(id=obj.id)

    slug = _ensure_slug_len(slug, slug_len)
    q = base_q.filter(slug=slug)
    if q.count() == 0:
        obj.slug = slug
        return True

    if obj.id is not None:
        slug = slug + '-' + str(obj.id)

    slug = _ensure_slug_len(slug, slug_len)
    q = base_q.filter(slug=slug)
    if q.count() == 0:
        obj.slug = slug
        return True

    for x in xrange(times_to_try):
        if q.count() == 0:
            obj.slug = slug
            return True

        slug = orig_slug + '-' + str(x+1)
        slug = _ensure_slug_len(slug, slug_len)

        q = base_q.filter(slug=slug)

    raise ValueError('Was not able to find a unique slug for %s' % str(obj))

def _ensure_slug_len(slug, slug_len):
    if len(slug) > slug_len:
        slug = slug[:slug_len-(len(str(x)) + 1)]
        slug = _slug_strip(slug, '-')

    return slug

def _slug_strip(value, separator='-'):
    """
    Cleans up a slug by removing slug separator characters that occur at the
    beginning or end of a slug.

    If an alternate separator is used, it will also replace any instances of
    the default '-' separator with the new separator.
    """
    separator = separator or ''
    if separator == '-' or not separator:
        re_sep = '-'
    else:
        re_sep = '(?:-|%s)' % re.escape(separator)
    # Remove multiple instances and if an alternate separator is provided,
    # replace the default '-' separator.
    if separator != re_sep:
        value = re.sub('%s+' % re_sep, separator, value)
    # Remove separator from the beginning and end of the slug.
    if separator:
        if separator != '-':
            re_sep = re.escape(separator)
        value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
    return value

class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return u''.join(self.fed)

def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()

def distance_on_unit_sphere(lat1, long1, lat2, long2):
    lat1 = float(lat1)
    long1 = float(long1)
    lat2 = float(lat2)
    long2 = float(long2)

    # Convert latitude and longitude to
    # spherical coordinates in radians.
    degrees_to_radians = math.pi/180.0

    # phi = 90 - latitude
    phi1 = (90.0 - lat1)*degrees_to_radians
    phi2 = (90.0 - lat2)*degrees_to_radians

    # theta = longitude
    theta1 = long1*degrees_to_radians
    theta2 = long2*degrees_to_radians

    # Compute spherical distance from spherical coordinates.

    # For two locations in spherical coordinates
    # (1, theta, phi) and (1, theta, phi)
    # cosine( arc length ) =
    #    sin phi sin phi' cos(theta-theta') + cos phi cos phi'
    # distance = rho * arc length
    try:
        if lat1 != lat2 and long1 != long2:
            cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) +
                   math.cos(phi1)*math.cos(phi2))
            arc = math.acos(cos)
        else:
            # values being the same will cause a math domain error
            arc = None
    except ValueError:
        arc = None
    # Remember to multiply arc by the radius of the earth
    # in your favorite set of units to get length.
    return arc

def distance_in_miles(lat1, long1, lat2, long2):
    distance = distance_on_unit_sphere(lat1, long1, lat2, long2)
    if distance is not None:
        return distance * 3960
    else:
        return None


text:
#include "core/html/forms/RadioButtonGroupScope.h"

#include "core/InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "wtf/HashMap.h"

namespace blink {

class RadioButtonGroup : public NoBaseWillBeGarbageCollected<RadioButtonGroup> {
    USING_FAST_MALLOC_WILL_BE_REMOVED(RadioButtonGroup);
public:
    static PassOwnPtrWillBeRawPtr<RadioButtonGroup> create();
    bool isEmpty() const { return m_members.isEmpty(); }
    bool isRequired() const { return m_requiredCount; }
    HTMLInputElement* checkedButton() const { return m_checkedButton; }
    void add(HTMLInputElement*);
    void updateCheckedState(HTMLInputElement*);
    void requiredAttributeChanged(HTMLInputElement*);
    void remove(HTMLInputElement*);
    bool contains(HTMLInputElement*) const;

    DECLARE_TRACE();

private:
    RadioButtonGroup();
    void setNeedsValidityCheckForAllButtons();
    bool isValid() const;
    void setCheckedButton(HTMLInputElement*);

    // The map records the 'required' state of each (button) element.
    using Members = WillBeHeapHashMap<RawPtrWillBeMember<HTMLInputElement>, bool>;

#if ENABLE(OILPAN)
    using MemberKeyValue = WTF::KeyValuePair<Member<HTMLInputElement>, bool>;
#else
    using MemberKeyValue = WTF::KeyValuePair<HTMLInputElement*, bool>;
#endif

    void updateRequiredButton(MemberKeyValue&, bool isRequired);

    Members m_members;
    RawPtrWillBeMember<HTMLInputElement> m_checkedButton;
    size_t m_requiredCount;
};

RadioButtonGroup::RadioButtonGroup()
    : m_checkedButton(nullptr)
    , m_requiredCount(0)
{
}

PassOwnPtrWillBeRawPtr<RadioButtonGroup> RadioButtonGroup::create()
{
    return adoptPtrWillBeNoop(new RadioButtonGroup);
}

inline bool RadioButtonGroup::isValid() const
{
    return !isRequired() || m_checkedButton;
}

void RadioButtonGroup::setCheckedButton(HTMLInputElement* button)
{
    HTMLInputElement* oldCheckedButton = m_checkedButton;
    if (oldCheckedButton == button)
        return;
    m_checkedButton = button;
    if (oldCheckedButton)
        oldCheckedButton->setChecked(false);
}

void RadioButtonGroup::updateRequiredButton(MemberKeyValue& it, bool isRequired)
{
    if (it.value == isRequired)
        return;

    it.value = isRequired;
    if (isRequired) {
        m_requiredCount++;
    } else {
        ASSERT(m_requiredCount);
        m_requiredCount--;
    }
}

void RadioButtonGroup::add(HTMLInputElement* button)
{
    ASSERT(button->type() == InputTypeNames::radio);
    auto addResult = m_members.add(button, false);
    if (!addResult.isNewEntry)
        return;
    bool groupWasValid = isValid();
    updateRequiredButton(*addResult.storedValue, button->isRequired());
    if (button->checked())
        setCheckedButton(button);

    bool groupIsValid = isValid();
    if (groupWasValid != groupIsValid) {
        setNeedsValidityCheckForAllButtons();
    } else if (!groupIsValid) {
        // A radio button not in a group is always valid. We need to make it
        // invalid only if the group is invalid.
        button->setNeedsValidityCheck();
    }
}

void RadioButtonGroup::updateCheckedState(HTMLInputElement* button)
{
    ASSERT(button->type() == InputTypeNames::radio);
    ASSERT(m_members.contains(button));
    bool wasValid = isValid();
    if (button->checked()) {
        setCheckedButton(button);
    } else {
        if (m_checkedButton == button)
            m_checkedButton = nullptr;
    }
    if (wasValid != isValid())
        setNeedsValidityCheckForAllButtons();
    for (auto& member : m_members) {
        HTMLInputElement* const inputElement = member.key;
        inputElement->pseudoStateChanged(CSSSelector::PseudoIndeterminate);
    }
}

void RadioButtonGroup::requiredAttributeChanged(HTMLInputElement* button)
{
    ASSERT(button->type() == InputTypeNames::radio);
    auto it = m_members.find(button);
    ASSERT(it != m_members.end());
    bool wasValid = isValid();
    // Synchronize the 'required' flag for the button, along with
    // updating the overall count.
    updateRequiredButton(*it, button->isRequired());
    if (wasValid != isValid())
        setNeedsValidityCheckForAllButtons();
}

void RadioButtonGroup::remove(HTMLInputElement* button)
{
    ASSERT(button->type() == InputTypeNames::radio);
    auto it = m_members.find(button);
    if (it == m_members.end())
        return;
    bool wasValid = isValid();
    ASSERT(it->value == button->isRequired());
    updateRequiredButton(*it, false);
    m_members.remove(it);
    if (m_checkedButton == button)
        m_checkedButton = nullptr;

    if (m_members.isEmpty()) {
        ASSERT(!m_requiredCount);
        ASSERT(!m_checkedButton);
    } else if (wasValid != isValid()) {
        setNeedsValidityCheckForAllButtons();
    }
    if (!wasValid) {
        // A radio button not in a group is always valid. We need to make it
        // valid only if the group was invalid.
        button->setNeedsValidityCheck();
    }
}

void RadioButtonGroup::setNeedsValidityCheckForAllButtons()
{
    for (auto& element : m_members) {
        HTMLInputElement* const button = element.key;
        ASSERT(button->type() == InputTypeNames::radio);
        button->setNeedsValidityCheck();
    }
}

bool RadioButtonGroup::contains(HTMLInputElement* button) const
{
    return m_members.contains(button);
}

DEFINE_TRACE(RadioButtonGroup)
{
#if ENABLE(OILPAN)
    visitor->trace(m_members);
    visitor->trace(m_checkedButton);
#endif
}

// ----------------------------------------------------------------

// Explicity define empty constructor and destructor in order to prevent the
// compiler from generating them as inlines. So we don't need to to define
// RadioButtonGroup in the header.
RadioButtonGroupScope::RadioButtonGroupScope()
{
}

RadioButtonGroupScope::~RadioButtonGroupScope()
{
}

void RadioButtonGroupScope::addButton(HTMLInputElement* element)
{
    ASSERT(element->type() == InputTypeNames::radio);
    if (element->name().isEmpty())
        return;

    if (!m_nameToGroupMap)
        m_nameToGroupMap = adoptPtrWillBeNoop(new NameToGroupMap);

    OwnPtrWillBeMember<RadioButtonGroup>& group = m_nameToGroupMap->add(element->name(), nullptr).storedValue->value;
    if (!group)
        group = RadioButtonGroup::create();
    group->add(element);
}

void RadioButtonGroupScope::updateCheckedState(HTMLInputElement* element)
{
    ASSERT(element->type() == InputTypeNames::radio);
    if (element->name().isEmpty())
        return;
    ASSERT(m_nameToGroupMap);
    if (!m_nameToGroupMap)
        return;
    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
    ASSERT(group);
    group->updateCheckedState(element);
}

void RadioButtonGroupScope::requiredAttributeChanged(HTMLInputElement* element)
{
    ASSERT(element->type() == InputTypeNames::radio);
    if (element->name().isEmpty())
        return;
    ASSERT(m_nameToGroupMap);
    if (!m_nameToGroupMap)
        return;
    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
    ASSERT(group);
    group->requiredAttributeChanged(element);
}

HTMLInputElement* RadioButtonGroupScope::checkedButtonForGroup(const AtomicString& name) const
{
    if (!m_nameToGroupMap)
        return nullptr;
    RadioButtonGroup* group = m_nameToGroupMap->get(name);
    return group ? group->checkedButton() : nullptr;
}

bool RadioButtonGroupScope::isInRequiredGroup(HTMLInputElement* element) const
{
    ASSERT(element->type() == InputTypeNames::radio);
    if (element->name().isEmpty())
        return false;
    if (!m_nameToGroupMap)
        return false;
    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
    return group && group->isRequired() && group->contains(element);
}

void RadioButtonGroupScope::removeButton(HTMLInputElement* element)
{
    ASSERT(element->type() == InputTypeNames::radio);
    if (element->name().isEmpty())
        return;
    if (!m_nameToGroupMap)
        return;

    RadioButtonGroup* group = m_nameToGroupMap->get(element->name());
    if (!group)
        return;
    group->remove(element);
    if (group->isEmpty()) {
        // We don't remove an empty RadioButtonGroup from m_nameToGroupMap for
        // better performance.
        ASSERT(!group->isRequired());
        ASSERT_WITH_SECURITY_IMPLICATION(!group->checkedButton());
    }
}

DEFINE_TRACE(RadioButtonGroupScope)
{
#if ENABLE(OILPAN)
    visitor->trace(m_nameToGroupMap);
#endif
}

} // namespace blink


text:
<html>
<head><title>Page with unsafe image loaded dynamically</title>
<script>
  var url = "https://REPLACE_WITH_HOST_AND_PORT/ssl/google_files/logo.gif";

  function AddImage() {
    var img = document.createElement("img");
    img.src = url;
    document.body.appendChild(img);
  }
</script>
<body></body>
</html>


text:
'use strict'

const validate = require('./configValidator')
const deepClone = require('rfdc')({ circles: true, proto: false })
const {
  codes: {
    FST_ERR_INIT_OPTS_INVALID
  }
} = require('./errors')

function validateInitialConfig (options) {
  const opts = deepClone(options)

  if (!validate(opts)) {
    const error = new FST_ERR_INIT_OPTS_INVALID(JSON.stringify(validate.errors.map(e => e.message)))
    error.errors = validate.errors
    throw error
  }

  return deepFreezeObject(opts)
}

function deepFreezeObject (object) {
  const properties = Object.getOwnPropertyNames(object)

  for (const name of properties) {
    const value = object[name]

    if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
      continue
    }

    object[name] = value && typeof value === 'object' ? deepFreezeObject(value) : value
  }

  return Object.freeze(object)
}

module.exports = validateInitialConfig
module.exports.defaultInitOptions = validate.defaultInitOptions
module.exports.utils = { deepFreezeObject }


text:
'use strict';

/**
 * Role assignment properties.
 *
 */
class RoleAssignmentProperties {
  /**
   * Create a RoleAssignmentProperties.
   * @member {string} [roleDefinitionId] The role definition ID used in the
   * role assignment.
   * @member {string} [principalId] The principal ID assigned to the role. This
   * maps to the ID inside the Active Directory. It can point to a user,
   * service principal, or security group.
   */
  constructor() {
  }

  /**
   * Defines the metadata of RoleAssignmentProperties
   *
   * @returns {object} metadata of RoleAssignmentProperties
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'RoleAssignmentProperties',
      type: {
        name: 'Composite',
        className: 'RoleAssignmentProperties',
        modelProperties: {
          roleDefinitionId: {
            required: false,
            serializedName: 'roleDefinitionId',
            type: {
              name: 'String'
            }
          },
          principalId: {
            required: false,
            serializedName: 'principalId',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = RoleAssignmentProperties;