# -*- coding: utf-8 -*-
# Gitless - a version control system built on top of Git
# Licensed under MIT

"""gl diff - Show changes in files."""

import os
import tempfile

from . import helpers, pprint

def parser(subparsers, repo):
  """Adds the diff parser to the given subparsers object."""
  desc = 'show changes to files'
  diff_parser = subparsers.add_parser(
      'diff', help=desc, description=(
        desc.capitalize() + '. ' +
        'By default all tracked modified files are diffed. To customize the '
        ' set of files to diff use the only, exclude, and include flags'), aliases=['df'])
  helpers.oei_flags(diff_parser, repo)
  diff_parser.set_defaults(func=main)

def main(args, repo):
  files = helpers.oei_fs(args, repo)
  if not files:
    pprint.warn('No files to diff')

  success = True
  curr_b = repo.current_branch
  with tempfile.NamedTemporaryFile(mode='w', delete=False) as tf:
    total_additions = 0
    total_deletions = 0
    patches = []
    for fp in files:
      try:
        patch = curr_b.diff_file(fp)
      except KeyError:
        pprint.err('Can\'t diff non-existent file {0}'.format(fp))
        success = False
        continue

      if patch.delta.is_binary:
        pprint.warn('Not showing diffs for binary file {0}'.format(fp))
        continue

      additions = patch.line_stats[1]
      deletions = patch.line_stats[2]
      total_additions += additions
      total_deletions += deletions
      if (not additions) and (not deletions):
        pprint.warn('No diffs to output for {0}'.format(fp))
        continue
      patches.append(patch)
    if patches:
      pprint.diff_totals(total_additions, total_deletions, stream=tf.write)
      for patch in patches:
        pprint.diff(patch, stream=tf.write)

  if os.path.getsize(tf.name) > 0:
    helpers.page(tf.name, repo)
  os.remove(tf.name)

  return success

{'repo_name': 'gitless-vcs/gitless', 'stars': '1518', 'repo_language': 'Python', 'file_name': 'test_core.py', 'mime_type': 'text/x-python', 'hash': 8476254034604390553, 'source_dataset': 'data'}


/*
    Copyright (C) 2014-2016 Leosac

    This file is part of Leosac.

    Leosac is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Leosac is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <boost/property_tree/ptree.hpp>
#include <unordered_map>
#include <vector>

namespace Leosac
{

class Kernel;

/**
* Provide some kind of security framework to the Remote Control service.
*
* This allows relatively fine-grained permissions and allows user
* to chose who has access to the remote control, and how much permission they got.
*
* Remote user are identified using the curve private key they use to connect.
*
* Implementation Notes:
*     We store a map of z85-encoded-pubkey <--> list (command name);
*     The meaning of this map depends on the default permission for user.
*
*     If the user is by default granted permission, then the map holds a list command
*     the user isn't allowed to perform. Otherwise, we store a list of allowed
* command.
*
*/
class RemoteControlSecurity
{
  public:
    /**
    * The config tree is the same tree that the RemoteControl object has.
    */
    RemoteControlSecurity(const boost::property_tree::ptree &cfg);

    bool allow_request(const std::string &user_pubkey, const std::string &req);

    /**
    * Map user public key to a set of command
    */
    using KeyCommandsMap = std::unordered_map<std::string, std::vector<std::string>>;

  private:
    void process_config();

    /**
    * Process one `<map>` entry.
    */
    void process_security_entry(const boost::property_tree::ptree &);

    boost::property_tree::ptree cfg_;

    std::unordered_map<std::string, bool> default_permissions_;
    KeyCommandsMap permissions_;

    /**
    * If everyone has access to everything.
    */
    bool unrestricted_;
};
}

{'repo_name': 'leosac/leosac', 'stars': '154', 'repo_language': 'C++', 'file_name': 'rpi-sysfs.xml', 'mime_type': 'text/xml', 'hash': -3243531215861319539, 'source_dataset': 'data'}


# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

# Project target.
target=android-19

{'repo_name': 'udacity/ud405', 'stars': '160', 'repo_language': 'Java', 'file_name': 'IciclesScreen.java', 'mime_type': 'text/x-java', 'hash': 2610610298428651341, 'source_dataset': 'data'}


// Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------

//! \addtogroup op_var
//! @{

//! \brief
//! For each row or for each column, find the variance.
//! The result is stored in a dense matrix that has either one column or one row.
//! The dimension, for which the variances are found, is set via the var() function.
template<typename T1>
inline
void
op_var::apply(Mat<typename T1::pod_type>& out, const mtOp<typename T1::pod_type, T1, op_var>& in)
  {
  arma_extra_debug_sigprint();

  typedef typename T1::elem_type  in_eT;
  typedef typename T1::pod_type  out_eT;

  const unwrap_check_mixed<T1> tmp(in.m, out);
  const Mat<in_eT>&        X = tmp.M;

  const uword norm_type = in.aux_uword_a;
  const uword dim       = in.aux_uword_b;

  arma_debug_check( (norm_type > 1), "var(): parameter 'norm_type' must be 0 or 1" );
  arma_debug_check( (dim > 1),       "var(): parameter 'dim' must be 0 or 1"       );

  const uword X_n_rows = X.n_rows;
  const uword X_n_cols = X.n_cols;

  if(dim == 0)
    {
    arma_extra_debug_print("op_var::apply(): dim = 0");

    out.set_size((X_n_rows > 0) ? 1 : 0, X_n_cols);

    if(X_n_rows > 0)
      {
      out_eT* out_mem = out.memptr();

      for(uword col=0; col<X_n_cols; ++col)
        {
        out_mem[col] = op_var::direct_var( X.colptr(col), X_n_rows, norm_type );
        }
      }
    }
  else
  if(dim == 1)
    {
    arma_extra_debug_print("op_var::apply(): dim = 1");

    out.set_size(X_n_rows, (X_n_cols > 0) ? 1 : 0);

    if(X_n_cols > 0)
      {
      podarray<in_eT> dat(X_n_cols);

      in_eT*  dat_mem = dat.memptr();
      out_eT* out_mem = out.memptr();

      for(uword row=0; row<X_n_rows; ++row)
        {
        dat.copy_row(X, row);

        out_mem[row] = op_var::direct_var( dat_mem, X_n_cols, norm_type );
        }
      }
    }
  }

template<typename T1>
inline
typename T1::pod_type
op_var::var_vec(const Base<typename T1::elem_type, T1>& X, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  arma_debug_check( (norm_type > 1), "var(): parameter 'norm_type' must be 0 or 1" );

  const quasi_unwrap<T1> U(X.get_ref());

  return op_var::direct_var(U.M.memptr(), U.M.n_elem, norm_type);
  }

template<typename eT>
inline
typename get_pod_type<eT>::result
op_var::var_vec(const subview_col<eT>& X, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  arma_debug_check( (norm_type > 1), "var(): parameter 'norm_type' must be 0 or 1" );

  return op_var::direct_var(X.colptr(0), X.n_rows, norm_type);
  }

template<typename eT>
inline
typename get_pod_type<eT>::result
op_var::var_vec(const subview_row<eT>& X, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  arma_debug_check( (norm_type > 1), "var(): parameter 'norm_type' must be 0 or 1" );

  const Mat<eT>& A = X.m;

  const uword start_row = X.aux_row1;
  const uword start_col = X.aux_col1;

  const uword end_col_p1 = start_col + X.n_cols;

  podarray<eT> tmp(X.n_elem);
  eT* tmp_mem = tmp.memptr();

  for(uword i=0, col=start_col; col < end_col_p1; ++col, ++i)
    {
    tmp_mem[i] = A.at(start_row, col);
    }

  return op_var::direct_var(tmp.memptr(), tmp.n_elem, norm_type);
  }

//! find the variance of an array
template<typename eT>
inline
eT
op_var::direct_var(const eT* const X, const uword n_elem, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  if(n_elem >= 2)
    {
    const eT acc1 = op_mean::direct_mean(X, n_elem);

    eT acc2 = eT(0);
    eT acc3 = eT(0);

    uword i,j;

    for(i=0, j=1; j<n_elem; i+=2, j+=2)
      {
      const eT Xi = X[i];
      const eT Xj = X[j];

      const eT tmpi = acc1 - Xi;
      const eT tmpj = acc1 - Xj;

      acc2 += tmpi*tmpi + tmpj*tmpj;
      acc3 += tmpi      + tmpj;
      }

    if(i < n_elem)
      {
      const eT Xi = X[i];

      const eT tmpi = acc1 - Xi;

      acc2 += tmpi*tmpi;
      acc3 += tmpi;
      }

    const eT norm_val = (norm_type == 0) ? eT(n_elem-1) : eT(n_elem);
    const eT var_val  = (acc2 - acc3*acc3/eT(n_elem)) / norm_val;

    return arma_isfinite(var_val) ? var_val : op_var::direct_var_robust(X, n_elem, norm_type);
    }
  else
    {
    return eT(0);
    }
  }

//! find the variance of an array (robust but slow)
template<typename eT>
inline
eT
op_var::direct_var_robust(const eT* const X, const uword n_elem, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  if(n_elem > 1)
    {
    eT r_mean = X[0];
    eT r_var  = eT(0);

    for(uword i=1; i<n_elem; ++i)
      {
      const eT tmp      = X[i] - r_mean;
      const eT i_plus_1 = eT(i+1);

      r_var  = eT(i-1)/eT(i) * r_var + (tmp*tmp)/i_plus_1;

      r_mean = r_mean + tmp/i_plus_1;
      }

    return (norm_type == 0) ? r_var : (eT(n_elem-1)/eT(n_elem)) * r_var;
    }
  else
    {
    return eT(0);
    }
  }

//! find the variance of an array (version for complex numbers)
template<typename T>
inline
T
op_var::direct_var(const std::complex<T>* const X, const uword n_elem, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  typedef typename std::complex<T> eT;

  if(n_elem >= 2)
    {
    const eT acc1 = op_mean::direct_mean(X, n_elem);

    T  acc2 =  T(0);
    eT acc3 = eT(0);

    for(uword i=0; i<n_elem; ++i)
      {
      const eT tmp = acc1 - X[i];

      acc2 += std::norm(tmp);
      acc3 += tmp;
      }

    const T norm_val = (norm_type == 0) ? T(n_elem-1) : T(n_elem);
    const T var_val  = (acc2 - std::norm(acc3)/T(n_elem)) / norm_val;

    return arma_isfinite(var_val) ? var_val : op_var::direct_var_robust(X, n_elem, norm_type);
    }
  else
    {
    return T(0);
    }
  }

//! find the variance of an array (version for complex numbers) (robust but slow)
template<typename T>
inline
T
op_var::direct_var_robust(const std::complex<T>* const X, const uword n_elem, const uword norm_type)
  {
  arma_extra_debug_sigprint();

  typedef typename std::complex<T> eT;

  if(n_elem > 1)
    {
    eT r_mean = X[0];
     T r_var  = T(0);

    for(uword i=1; i<n_elem; ++i)
      {
      const eT tmp      = X[i] - r_mean;
      const  T i_plus_1 = T(i+1);

      r_var  = T(i-1)/T(i) * r_var + std::norm(tmp)/i_plus_1;

      r_mean = r_mean + tmp/i_plus_1;
      }

    return (norm_type == 0) ? r_var : (T(n_elem-1)/T(n_elem)) * r_var;
    }
  else
    {
    return T(0);
    }
  }

//! @}

{'repo_name': 'RcppCore/RcppArmadillo', 'stars': '111', 'repo_language': 'C++', 'file_name': 'format', 'mime_type': 'text/plain', 'hash': -4960806367199147456, 'source_dataset': 'data'}


# Copyright 1999-2019 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

EAPI=7

DESCRIPTION="OpenSource 2D MMORPG client for Evol Online and The Mana World"
HOMEPAGE="http://manaplus.evolonline.org"
if [[ ${PV} == 9999 ]] ; then
	inherit autotools git-r3
	EGIT_REPO_URI="https://github.com/ManaPlus/ManaPlus.git"
else
	SRC_URI="http://download.evolonline.org/manaplus/download/${PV}/${P}.tar.xz"
	KEYWORDS="~amd64 ~x86"
fi

LICENSE="GPL-2+"
SLOT="0"
IUSE="mumble nls opengl pugixml +sdl2 test"
RESTRICT="!test? ( test )"

RDEPEND="
	>=dev-games/physfs-1.0.0
	media-fonts/dejavu
	media-fonts/liberation-fonts
	media-fonts/mplus-outline-fonts
	media-fonts/wqy-microhei
	media-libs/libpng:0=
	net-misc/curl
	sys-libs/zlib
	x11-apps/xmessage
	x11-libs/libX11
	x11-misc/xdg-utils
	mumble? ( media-sound/mumble )
	nls? ( virtual/libintl )
	opengl? ( virtual/opengl )
	pugixml? ( dev-libs/pugixml )
	!pugixml? ( dev-libs/libxml2 )
	sdl2? (
		media-libs/libsdl2[X,opengl?,video]
		media-libs/sdl2-gfx
		media-libs/sdl2-image[png]
		media-libs/sdl2-mixer[vorbis]
		media-libs/sdl2-net
		media-libs/sdl2-ttf
	)
	!sdl2? (
		media-libs/libsdl[X,opengl?,video]
		media-libs/sdl-gfx
		media-libs/sdl-image[png]
		media-libs/sdl-mixer[vorbis]
		media-libs/sdl-net
		media-libs/sdl-ttf
	)"
DEPEND="${RDEPEND}
	virtual/pkgconfig
	nls? ( sys-devel/gettext )"

src_prepare() {
	default
	if [[ ${PV} == 9999 ]] ; then
		eautoreconf
	fi
}

src_configure() {
	local myeconfargs=(
		--localedir=/usr/share/locale
		--without-internalsdlgfx
		$(use_with mumble)
		$(use_enable nls)
		$(use_with opengl)
		--enable-libxml=$(usex pugixml pugixml libxml)
		$(use_with sdl2)
		$(use_enable test unittests)
	)
	CONFIG_SHELL=/bin/bash econf "${myeconfargs[@]}"
}

src_install() {
	default

	local destpath="/usr/share/${PN}"
	dosym ../../../fonts/dejavu/DejaVuSans-Bold.ttf "${destpath}"/data/fonts/dejavusans-bold.ttf
	dosym ../../../fonts/dejavu/DejaVuSans.ttf "${destpath}"/data/fonts/dejavusans.ttf
	dosym ../../../fonts/dejavu/DejaVuSansMono-Bold.ttf "${destpath}"/data/fonts/dejavusansmono-bold.ttf
	dosym ../../../fonts/dejavu/DejaVuSansMono.ttf "${destpath}"/data/fonts/dejavusansmono.ttf
	dosym ../../../fonts/dejavu/DejaVuSerifCondensed-Bold.ttf "${destpath}"/data/fonts/dejavuserifcondensed-bold.ttf
	dosym ../../../fonts/dejavu/DejaVuSerifCondensed.ttf "${destpath}"/data/fonts/dejavuserifcondensed.ttf
	dosym ../../../fonts/liberation-fonts/LiberationMono-Bold.ttf "${destpath}"/data/fonts/liberationsansmono-bold.ttf
	dosym ../../../fonts/liberation-fonts/LiberationMono-Regular.ttf "${destpath}"/data/fonts/liberationsansmono.ttf
	dosym ../../../fonts/liberation-fonts/LiberationSans-Bold.ttf "${destpath}"/data/fonts/liberationsans-bold.ttf
	dosym ../../../fonts/liberation-fonts/LiberationSans-Regular.ttf "${destpath}"/data/fonts/liberationsans.ttf
	dosym ../../../fonts/mplus-outline-fonts/mplus-1p-bold.ttf "${destpath}"/data/fonts/mplus-1p-bold.ttf
	dosym ../../../fonts/mplus-outline-fonts/mplus-1p-regular.ttf "${destpath}"/data/fonts/mplus-1p-regular.ttf
	dosym ../../../fonts/wqy-microhei/wqy-microhei.ttc "${destpath}"/data/fonts/wqy-microhei.ttf
}

src_test() {
	make check
}

{'repo_name': 'gentoo/gentoo', 'stars': '1217', 'repo_language': 'Shell', 'file_name': 'perl-Attribute-Handlers-1.10.0-r3.ebuild', 'mime_type': 'text/plain', 'hash': 5497215990374569627, 'source_dataset': 'data'}


fileFormatVersion: 2
guid: e59f86a8f1f943e3b9725f096c82559e
MonoImporter:
  externalObjects: {}
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:

{'repo_name': 'sebastianstarke/AI4Animation', 'stars': '3141', 'repo_language': 'C++', 'file_name': 'ProjectVersion.txt', 'mime_type': 'text/plain', 'hash': 1593499180278583488, 'source_dataset': 'data'}


//
//  ex8_05.cpp
//  Exercise 8.5
//
//  Created by pezy on 11/9/14.
//  Copyright (c) 2014 pezy. All rights reserved.
//
//  @Brief  Rewrite the previous program to store each word in a separate
//  element.
//  @See    ex8_04.cpp

#include <fstream>
#include <string>
#include <vector>
#include <iostream>

using std::vector;
using std::string;
using std::ifstream;
using std::cout;
using std::endl;

void ReadFileToVec(const string& fileName, vector<string>& vec)
{
    ifstream ifs(fileName);
    if (ifs) {
        string buf;
        while (ifs >> buf) vec.push_back(buf);
    }
}

int main()
{
    vector<string> vec;
    ReadFileToVec("../data/book.txt", vec);
    for (const auto& str : vec) cout << str << endl;
    return 0;
}

{'repo_name': 'pezy/CppPrimer', 'stars': '2226', 'repo_language': 'C++', 'file_name': 'letter.txt', 'mime_type': 'text/plain', 'hash': 7404865346486266105, 'source_dataset': 'data'}


"resource/layout/musiclibrarypanel.layout" {
	styles {
		CMusicLibraryPanel {
			minimum-width=296
			minimum-height=300

			render {
				0="image_tiled(x0,y0+34,x1,y0+38, graphics/material/shadows/top)"
				1="image_tiled(x0,y0+79,x1,y0+83, graphics/material/shadows/top)"
			}

			render_bg {
				0="fill(x0,y0+34,x1,y0+79, color__submenuBackground)"
			}
		}

		LibrarySearch {
			bgcolor=color__textInputBackground
			textcolor=color__text
			font-family=font__basefont
			font-size = 18
font-size = 16 [$LINUX]
font-size = 19 [$OSX]

			font-weight=400
			inset-left=1
			inset-top=0
			padding-left=0

			render {}
		}

			LibrarySearch:selected {}

			LibrarySearch:empty {
				font-style=italic
				textcolor=color__disabled
			}

				LibrarySearch:empty:hover {
					textcolor=color__secondaryText
				}

			LibrarySearch:hover {
				textcolor=color__text
			}

			LibrarySearch:disabled {
				font-style=italic
				textcolor=color__disabled
			}

		LibrarySearchIcon {
			bgcolor=color__textInputBackground
			textcolor=none

			render_bg {
				-1="fill(x1,y0,x1+10,y1, color__textInputBackground)"
				0="image(x0+14,y0+13,x1,y1, graphics/icons/search/standard)"
			}
		}

			LibrarySearchIcon:disabled {}

		MusicAddButton {
			render_bg{
				0="image(x0,y0,x1,y1, graphics/icons/addmusic/hover/addmusic)"
			}
		}

			MusicAddButton:hover {
				render_bg{
					0="image(x0,y0,x1,y1, graphics/icons/addmusic/standard/addmusic)"
				}
			}

			MusicAddButton:disabled {
				render_bg {}
			}

			MusicAddButton:active {
				bgcolor=none

				render_bg{
					-3="image(x0-7,y0-7,x0+12,y0+12, graphics/material/selectionbubbles/hover/blue/topleft)"
					-2="image(x0-7,y0+12,x0+12,y0+24, graphics/material/selectionbubbles/hover/blue/bottomleft)"
					-1="image(x0+12,y0-7,x0+31,y0+12, graphics/material/selectionbubbles/hover/blue/topright)"
					0="image(x0+12,y0+12,x0+31,y0+31, graphics/material/selectionbubbles/hover/blue/bottomright)"
					1="image(x0,y0,x1,y1, graphics/icons/addmusic/active/addmusic)"
				}
			}

		MusicPlayerIcon {
			textcolor=none

			render_bg{
				0="image(x0,y0,x1,y1, graphics/icons/musicplayer/standard/musicplayer)"
			}
		}

			MusicPlayerIcon:hover {
				render_bg{
					0="image(x0,y0,x1,y1, graphics/icons/musicplayer/hover/musicplayer)"
				}
			}

			MusicPlayerIcon:active {
				bgcolor=none

				render_bg{
					-3="image(x0-7,y0-7,x0+12,y0+12, graphics/material/selectionbubbles/hover/blue/topleft)"
					-2="image(x0-7,y0+12,x0+12,y0+24, graphics/material/selectionbubbles/hover/blue/bottomleft)"
					-1="image(x0+12,y0-7,x0+31,y0+12, graphics/material/selectionbubbles/hover/blue/topright)"
					0="image(x0+12,y0+12,x0+31,y0+31, graphics/material/selectionbubbles/hover/blue/bottomright)"
					1="image(x0,y0,x1,y1, graphics/icons/musicplayer/hover/musicplayer)"
				}
			}

		NavLabel2 {
			bgcolor=none
			textcolor=color__secondaryText__alternate
			font-family=font__basefont
			font-size = 20
font-size = 16 [$LINUX]
font-size = 21 [$OSX]

			font-weight=400
			font-style=normal
			padding-left=10
			padding-right=35

			render_bg {
				0="image(x1-35, y0+21, x1, y1, graphics/icons/dropdown/standard/down)"
			}
		}

			NavLabel2:hover {
				textcolor=color__text__alternate

				render_bg {
					0="image(x1-35, y0+21, x1, y1, graphics/icons/dropdown/hover/down)"
				}
			}

			NavLabel2:selected {
				textcolor=color__text__alternate

				render_bg {
					0="fill(x0,y0,x1,y1, color__disabled__alternate)"
					1="image(x1-35, y0+21, x1, y1, graphics/icons/dropdown/hover/down)"
				}
			}

		grouper {}
	}

	layout {
		place {
			control=subnavgroup_library
			height=0
		}

		region {
			name=subnav
			y=34
			width=max
			height=45
		}

		place {
			control=library_search
			width=269
			width=254 [$LINUX]
		}

		place {
			control=label_search_icon
			width=40
		}

		place {
			control=label_search_icon,library_search
			region=subnav
			align=left
			height=max
			spacing=8
		}

		place {
			control=library_filters,library_music_menu
			region=subnav
			align=left
			start=library_search
			dir=right
			height=max
		}

		place {
			control=library_music_add_button,library_music_player_icon
			region=subnav
			align=right
			y=10
			width=24
			height=24
			margin-right=18
			spacing=24
		}

		place {
			control=MusicPage_Details_Content
			y=79
			dir=down
			width=max
			height=max
		}
	}
}

{'repo_name': 'DirtDiglett/Pressure2', 'stars': '263', 'repo_language': 'CSS', 'file_name': 'screenshotnotification.res', 'mime_type': 'text/plain', 'hash': 8959851912526938871, 'source_dataset': 'data'}


"""
Testing for mean shift clustering methods

"""

import numpy as np
import warnings
import pytest

from scipy import sparse

from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_raise_message
from sklearn.utils._testing import assert_allclose

from sklearn.cluster import MeanShift
from sklearn.cluster import mean_shift
from sklearn.cluster import estimate_bandwidth
from sklearn.cluster import get_bin_seeds
from sklearn.datasets import make_blobs
from sklearn.metrics import v_measure_score

n_clusters = 3
centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10
X, _ = make_blobs(n_samples=300, n_features=2, centers=centers,
                  cluster_std=0.4, shuffle=True, random_state=11)

def test_estimate_bandwidth():
    # Test estimate_bandwidth
    bandwidth = estimate_bandwidth(X, n_samples=200)
    assert 0.9 <= bandwidth <= 1.5

def test_estimate_bandwidth_1sample():
    # Test estimate_bandwidth when n_samples=1 and quantile<1, so that
    # n_neighbors is set to 1.
    bandwidth = estimate_bandwidth(X, n_samples=1, quantile=0.3)
    assert bandwidth == pytest.approx(0., abs=1e-5)

@pytest.mark.parametrize("bandwidth, cluster_all, expected, "
                         "first_cluster_label",
                         [(1.2, True, 3, 0), (1.2, False, 4, -1)])
def test_mean_shift(bandwidth, cluster_all, expected, first_cluster_label):
    # Test MeanShift algorithm
    ms = MeanShift(bandwidth=bandwidth, cluster_all=cluster_all)
    labels = ms.fit(X).labels_
    labels_unique = np.unique(labels)
    n_clusters_ = len(labels_unique)
    assert n_clusters_ == expected
    assert labels_unique[0] == first_cluster_label

    cluster_centers, labels_mean_shift = mean_shift(X, cluster_all=cluster_all)
    labels_mean_shift_unique = np.unique(labels_mean_shift)
    n_clusters_mean_shift = len(labels_mean_shift_unique)
    assert n_clusters_mean_shift == expected
    assert labels_mean_shift_unique[0] == first_cluster_label

def test_mean_shift_negative_bandwidth():
    bandwidth = -1
    ms = MeanShift(bandwidth=bandwidth)
    msg = (r"bandwidth needs to be greater than zero or None,"
           r" got -1\.000000")
    with pytest.raises(ValueError, match=msg):
        ms.fit(X)

def test_estimate_bandwidth_with_sparse_matrix():
    # Test estimate_bandwidth with sparse matrix
    X = sparse.lil_matrix((1000, 1000))
    msg = "A sparse matrix was passed, but dense data is required."
    assert_raise_message(TypeError, msg, estimate_bandwidth, X)

def test_parallel():
    centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10
    X, _ = make_blobs(n_samples=50, n_features=2, centers=centers,
                      cluster_std=0.4, shuffle=True, random_state=11)

    ms1 = MeanShift(n_jobs=2)
    ms1.fit(X)

    ms2 = MeanShift()
    ms2.fit(X)

    assert_array_almost_equal(ms1.cluster_centers_, ms2.cluster_centers_)
    assert_array_equal(ms1.labels_, ms2.labels_)

def test_meanshift_predict():
    # Test MeanShift.predict
    ms = MeanShift(bandwidth=1.2)
    labels = ms.fit_predict(X)
    labels2 = ms.predict(X)
    assert_array_equal(labels, labels2)

def test_meanshift_all_orphans():
    # init away from the data, crash with a sensible warning
    ms = MeanShift(bandwidth=0.1, seeds=[[-9, -9], [-10, -10]])
    msg = "No point was within bandwidth=0.1"
    assert_raise_message(ValueError, msg, ms.fit, X,)

def test_unfitted():
    # Non-regression: before fit, there should be not fitted attributes.
    ms = MeanShift()
    assert not hasattr(ms, "cluster_centers_")
    assert not hasattr(ms, "labels_")

def test_cluster_intensity_tie():
    X = np.array([[1, 1], [2, 1], [1, 0],
                  [4, 7], [3, 5], [3, 6]])
    c1 = MeanShift(bandwidth=2).fit(X)

    X = np.array([[4, 7], [3, 5], [3, 6],
                  [1, 1], [2, 1], [1, 0]])
    c2 = MeanShift(bandwidth=2).fit(X)
    assert_array_equal(c1.labels_, [1, 1, 1, 0, 0, 0])
    assert_array_equal(c2.labels_, [0, 0, 0, 1, 1, 1])

def test_bin_seeds():
    # Test the bin seeding technique which can be used in the mean shift
    # algorithm
    # Data is just 6 points in the plane
    X = np.array([[1., 1.], [1.4, 1.4], [1.8, 1.2],
                  [2., 1.], [2.1, 1.1], [0., 0.]])

    # With a bin coarseness of 1.0 and min_bin_freq of 1, 3 bins should be
    # found
    ground_truth = {(1., 1.), (2., 1.), (0., 0.)}
    test_bins = get_bin_seeds(X, 1, 1)
    test_result = set(tuple(p) for p in test_bins)
    assert len(ground_truth.symmetric_difference(test_result)) == 0

    # With a bin coarseness of 1.0 and min_bin_freq of 2, 2 bins should be
    # found
    ground_truth = {(1., 1.), (2., 1.)}
    test_bins = get_bin_seeds(X, 1, 2)
    test_result = set(tuple(p) for p in test_bins)
    assert len(ground_truth.symmetric_difference(test_result)) == 0

    # With a bin size of 0.01 and min_bin_freq of 1, 6 bins should be found
    # we bail and use the whole data here.
    with warnings.catch_warnings(record=True):
        test_bins = get_bin_seeds(X, 0.01, 1)
    assert_array_almost_equal(test_bins, X)

    # tight clusters around [0, 0] and [1, 1], only get two bins
    X, _ = make_blobs(n_samples=100, n_features=2, centers=[[0, 0], [1, 1]],
                      cluster_std=0.1, random_state=0)
    test_bins = get_bin_seeds(X, 1)
    assert_array_equal(test_bins, [[0, 0], [1, 1]])

@pytest.mark.parametrize('max_iter', [1, 100])
def test_max_iter(max_iter):
    clusters1, _ = mean_shift(X, max_iter=max_iter)
    ms = MeanShift(max_iter=max_iter).fit(X)
    clusters2 = ms.cluster_centers_

    assert ms.n_iter_ <= ms.max_iter
    assert len(clusters1) == len(clusters2)

    for c1, c2 in zip(clusters1, clusters2):
        assert np.allclose(c1, c2)

def test_mean_shift_zero_bandwidth():
    # Check that mean shift works when the estimated bandwidth is 0.
    X = np.array([1, 1, 1, 2, 2, 2, 3, 3]).reshape(-1, 1)

    # estimate_bandwidth with default args returns 0 on this dataset
    bandwidth = estimate_bandwidth(X)
    assert bandwidth == 0

    # get_bin_seeds with a 0 bin_size should return the dataset itself
    assert get_bin_seeds(X, bin_size=bandwidth) is X

    # MeanShift with binning and a 0 estimated bandwidth should be equivalent
    # to no binning.
    ms_binning = MeanShift(bin_seeding=True, bandwidth=None).fit(X)
    ms_nobinning = MeanShift(bin_seeding=False).fit(X)
    expected_labels = np.array([0, 0, 0, 1, 1, 1, 2, 2])

    assert v_measure_score(ms_binning.labels_, expected_labels) == 1
    assert v_measure_score(ms_nobinning.labels_, expected_labels) == 1
    assert_allclose(ms_binning.cluster_centers_, ms_nobinning.cluster_centers_)

{'repo_name': 'scikit-learn/scikit-learn', 'stars': '41564', 'repo_language': 'Python', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 8008390782379388631, 'source_dataset': 'data'}


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

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean class="org.apache.servicecomb.bizkeeper.BeansHolder" init-method="init"/>
</beans>

{'repo_name': 'apache/servicecomb-java-chassis', 'stars': '1582', 'repo_language': 'Java', 'file_name': 'archetype-metadata.xml', 'mime_type': 'text/plain', 'hash': 3854874436996458241, 'source_dataset': 'data'}


##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
# Version 0.2 by Andrew Horton
# Replaced matches, replaced Google dork, replaced examples
# Plugin still needs to be tested on all versions of MRTG

Plugin.define "MRTG" do
author "Aung Khant <http://yehg.net/>" # 2012-02-10
version "0.2"
description "MRTG - Multi Router Traffic Grapher - http://oss.oetiker.ch/mrtg/"

# Google results as at 2012-08-09 #
# 8330 for intitle:"MRTG Index Page"

# Matches #
matches [
{:name=>"Title", :regexp=>/<TITLE>MRTG Index Page<\/TITLE>/i},
{:name=>"Logo in footer", :regexp=>/HREF="http:\/\/oss.oetiker.ch\/mrtg\/"><IMG[\s]*BORDER=0 SRC="mrtg-l.png"/mi},

{:name=>"Logo in footer2", :regexp=>/HREF="http:\/\/www.ee.ethz.ch\/~oetiker\/webtools\/mrtg\/">.*src=mrtg-l.png alt=MRTG/mi},

{:name=>"Logo image", :url=>"/mrtg-l.png", :md5=>"241244d0d8845dcad7e891e84e79d63f"},
{:version=>/<title>MRTG Index Page.*version ([^<]+)<\/font><\/td>/mi}

]

end

{'repo_name': 'TideSec/FuzzScanner', 'stars': '567', 'repo_language': 'Ruby', 'file_name': 'dicc.txt', 'mime_type': 'text/troff', 'hash': 2716674625366214308, 'source_dataset': 'data'}


/*!
 * \brief Unit tests for \ref DiagnosisModel
 *
 * \copyright Copyright (c) 2018-2020 Governikus GmbH & Co. KG, Germany
 */

#include "DiagnosisModel.h"

#include "TestFileHelper.h"

#include <QtTest>

using namespace governikus;

class test_DiagnosisModel
	: public QObject
{
	Q_OBJECT
	QSharedPointer<DiagnosisContext> mContext;
	QSharedPointer<DiagnosisModel> mModel;

	private:
		QString getTestData(const QString& pFilename)
		{
			QString filePath = QStringLiteral(":/core/diagnosis/") + pFilename;
			QByteArray rawData = TestFileHelper::readFile(filePath);
			return QString::fromUtf8(rawData);
		}

		bool verifyOrder(const QSharedPointer<SectionModel>& pSection,
			const QVector<QSharedPointer<SectionModel> >& pSectionOrder)
		{
			QVector<QVector<QSharedPointer<ContentItem> > > contentOrder;
			for (const auto& section : pSectionOrder)
			{
				contentOrder.append(section->mContentItems);
			}

			return verifyOrder(pSection->mContentItems, contentOrder);
		}

		bool verifyOrder(const QVector<QSharedPointer<ContentItem> >& pSection,
			const QVector<QVector<QSharedPointer<ContentItem> > >& pOrder)
		{
			int offset = 0;
			for (const auto& subsection : pOrder)
			{
				const auto& slice = pSection.mid(offset, subsection.size());
				if (slice != subsection)
				{
					return false;
				}
				offset += subsection.size();
			}

			return offset == pSection.size();
		}

	private Q_SLOTS:
		void init()
		{
			mContext.reset(new DiagnosisContext());
			mModel.reset(new DiagnosisModel(mContext));
		}

		void cleanup()
		{
			mModel.clear();
			mContext.clear();
		}

		void test_newDiagnosisModel()
		{
			QCOMPARE(mModel->mContext, mContext);
			QCOMPARE(mModel->mSections.size(), 4);

			QCOMPARE(mModel->mSections.at(0).first, QCoreApplication::applicationName());
			QCOMPARE(mModel->mSections.at(1).first, QString("Card reader"));
			QCOMPARE(mModel->mSections.at(2).first, QString("Network"));
			QCOMPARE(mModel->mSections.at(3).first, QString("Antivirus and firewall"));

			QCOMPARE(mModel->mSections.at(0).second->mContentItems.last(), mModel->mTimestampItem);

			QCOMPARE(mModel->mSections.at(1).second, mModel->mCombinedReaderSection);
			QCOMPARE(mModel->mSections.at(2).second, mModel->mCombinedNetworkSection);
			QCOMPARE(mModel->mSections.at(3).second, mModel->mCombinedAntivirusFirewallSection);

			QCOMPARE(mModel->mSections.at(1).second->mContentItems.at(0)->mTitle, QString("Paired smartphones"));
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.at(1)->mContent, QString("No devices paired."));
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.at(2)->mTitle, QString("Card reader"));
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.at(3)->mContent, QString("Diagnosis is running..."));
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.at(4)->mTitle, QString("PC/SC driver information"));
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.at(5)->mContent, QString("Diagnosis is running..."));
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.mid(0, 2), mModel->mRemoteDeviceSection->mContentItems);
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.mid(2, 2), mModel->mCardReaderSection->mContentItems);
			QCOMPARE(mModel->mSections.at(1).second->mContentItems.mid(4, 2), mModel->mPcscSection->mContentItems);

			QCOMPARE(true, verifyOrder(mModel->mSections.at(1).second,
					{mModel->mRemoteDeviceSection, mModel->mCardReaderSection, mModel->mPcscSection}));
			QCOMPARE(true, verifyOrder(mModel->mSections.at(2).second,
					{mModel->mNetworkConnectionSection, mModel->mNetworkInterfaceSection}));
			QCOMPARE(true, verifyOrder(mModel->mSections.at(3).second,
					{mModel->mAntivirusSection, mModel->mFirewallSection}));
		}

		void test_OnReaderInfosChanged()
		{
			mModel->onReaderInfosChanged();
			QCOMPARE(mModel->mCardReaderSection->mContentItems.size(), 2);
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(1)->mContent, QString("No supported reader found."));

			ReaderInfo defaultInfo;
			ReaderInfo infoEidCard(QString("testInfo"), ReaderManagerPlugInType::PCSC, CardInfo(CardType::EID_CARD));
			ReaderInfo comfortReaderInfo(QString("name"), ReaderManagerPlugInType::BLUETOOTH, CardInfo(CardType::UNKNOWN));
			comfortReaderInfo.setBasicReader(false);
			const QVector<ReaderInfo> readerInfos = {defaultInfo, infoEidCard, comfortReaderInfo};
			mContext->setReaderInfos(readerInfos);
			mModel->onReaderInfosChanged();

			QCOMPARE(mModel->mCardReaderSection->mContentItems.size(), 4);

			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(0)->mTitle, QString("Connected Card reader"));
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(1)->mTitle, QString());
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(2)->mTitle, QString("testInfo"));
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(3)->mTitle, QString("name"));

			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(0)->mContent, QString());
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(1)->mContent, QString("Type: Basic card reader\nCard: not inserted"));
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(2)->mContent, QString("Type: Basic card reader\nCard: ID card (PA/eAT)\nRetry counter: -1"));
			QCOMPARE(mModel->mCardReaderSection->mContentItems.at(3)->mContent, QString("Type: Standard / comfort card reader\nCard: unknown type"));

			QCOMPARE(true, verifyOrder(mModel->mCombinedReaderSection->mContentItems, {
						mModel->mRemoteDeviceSection->mContentItems,
						mModel->mCardReaderSection->mContentItems,
						mModel->mPcscSection->mContentItems}));
		}

		void test_OnRemoteInfosChanged()
		{
			mModel->onRemoteInfosChanged();
			QCOMPARE(mModel->mRemoteDeviceSection->mContentItems.size(), 2);
			QCOMPARE(mModel->mRemoteDeviceSection->mContentItems.at(0)->mTitle, QString("Paired smartphones"));
			QCOMPARE(mModel->mRemoteDeviceSection->mContentItems.at(1)->mContent, QString("No devices paired."));
			QCOMPARE(true, verifyOrder(mModel->mCombinedReaderSection->mContentItems, {
						mModel->mRemoteDeviceSection->mContentItems,
						mModel->mCardReaderSection->mContentItems,
						mModel->mPcscSection->mContentItems}));
		}

		void test_OnPcscInfoChanged()
		{
			const QString version("Version");
			const DiagnosisContext::ComponentInfo component1(QString("/path/to/component1"), QString("description1"), QString("version1"), QString("vendor1"));
			const DiagnosisContext::ComponentInfo component2(QString("/path/to/component2"), QString("description2"), QString("version2"), QString("vendor2"));
			const DiagnosisContext::ComponentInfo driver1(QString("/path/to/driver1"), QString("description1"), QString("version1"), QString("vendor1"));
			const DiagnosisContext::ComponentInfo driver2(QString("/path/to/driver2"), QString("description2"), QString("version2"), QString("vendor2"));
			QVector<DiagnosisContext::ComponentInfo> components = {component1, component2};
			QVector<DiagnosisContext::ComponentInfo> drivers = {driver1, driver2};
			mContext->setPcscInfo(version, components, drivers);
			mModel->onPcscInfoChanged();

			QCOMPARE(mModel->mPcscSection->mContentItems.size(), 4);

			QCOMPARE(mModel->mPcscSection->mContentItems.at(0)->mTitle, QString("PC/SC information"));
			QCOMPARE(mModel->mPcscSection->mContentItems.at(1)->mContent, QString("Version"));
			QCOMPARE(mModel->mPcscSection->mContentItems.at(2)->mTitle, QString("Components"));
			QCOMPARE(mModel->mPcscSection->mContentItems.at(2)->mContent, QString("description1\nVendor: vendor1\nVersion: version1\nFile path: /path/to/component1\ndescription2\nVendor: vendor2\nVersion: version2\nFile path: /path/to/component2"));
			QCOMPARE(mModel->mPcscSection->mContentItems.at(3)->mTitle, QString("Driver"));
			QCOMPARE(mModel->mPcscSection->mContentItems.at(3)->mContent, QString("description1\nVendor: vendor1\nVersion: version1\nFile path: /path/to/driver1\ndescription2\nVendor: vendor2\nVersion: version2\nFile path: /path/to/driver2"));
			QCOMPARE(true, verifyOrder(mModel->mCombinedReaderSection->mContentItems, {
						mModel->mRemoteDeviceSection->mContentItems,
						mModel->mCardReaderSection->mContentItems,
						mModel->mPcscSection->mContentItems}));
		}

		void test_OnTimestampChanged()
		{
			const QDateTime invalid;
			const QDate date(2018, 10, 12);
			const QTime time(12, 0);
			const QDateTime valid(date, time);

			mContext->setTimestamp(invalid);
			mModel->onTimestampChanged();
			QCOMPARE(mModel->mTimestampItem->mTitle, QString("Time of diagnosis"));
			QCOMPARE(mModel->mTimestampItem->mContent, QString("Failed to retrieve date & time"));

			mContext->setTimestamp(valid);
			mModel->onTimestampChanged();
			QCOMPARE(mModel->mTimestampItem->mTitle, QString("Time of diagnosis"));
			QCOMPARE(mModel->mTimestampItem->mContent, QString("12. October 2018, 12:00:00 PM"));
		}

		void test_OnNetworkInfoChanged()
		{
			const QNetworkInterface interface1;
			const QNetworkInterface interface2;
			const QNetworkInterface interface3;
			QList<QNetworkInterface> interfaces = {interface1, interface2, interface3};
			mContext->setNetworkInterfaces(interfaces);
			mModel->onNetworkInfoChanged();

			QCOMPARE(mModel->mNetworkInterfaceSection->mContentItems.size(), 3);
			for (const auto& item : qAsConst(mModel->mNetworkInterfaceSection->mContentItems))
			{
				QCOMPARE(item->mTitle, QString(""));
				QCOMPARE(item->mContent, QString("Hardware address: <Not set>\nNo IP addresses assigned"));
			}

			QCOMPARE(true, verifyOrder(mModel->mCombinedNetworkSection, {mModel->mNetworkConnectionSection, mModel->mNetworkInterfaceSection}));
		}

		void test_OnAntivirusDetectionFailed()
		{
			mModel->onAntivirusDetectionFailed();
			QCOMPARE(mModel->mAntivirusSection->mContentItems.size(), 1);
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(0)->mTitle, QString("Antivirus information"));
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(0)->mContent, QString("Antivirus detection failed."));
			QCOMPARE(true, verifyOrder(mModel->mCombinedAntivirusFirewallSection, {mModel->mAntivirusSection, mModel->mFirewallSection}));
		}

		void test_OnAntivirusInformationChanged()
		{
			mModel->onAntivirusInformationChanged();
			QCOMPARE(mModel->mAntivirusSection->mContentItems.size(), 1);
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(0)->mTitle, QString("Antivirus information"));
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(0)->mContent, QString("No Antivirus software detected."));
			QCOMPARE(true, verifyOrder(mModel->mCombinedAntivirusFirewallSection, {mModel->mAntivirusSection, mModel->mFirewallSection}));

			const QString& fileContent = getTestData(QStringLiteral("antivir_two_antivirus.txt"));
			mModel->mAntivirusDetection.parseAntivirInfos(fileContent);
			mModel->onAntivirusInformationChanged();

			QCOMPARE(mModel->mAntivirusSection->mContentItems.size(), 3);
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(0)->mTitle, QString("Antivirus information"));
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(1)->mTitle, QString("BullGuard Antivirus"));
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(1)->mContent, QString("Last updated: Fri, 30 Nov 2018 15:04:13 GMT\nExecutable path: C:\\Program Files\\BullGuard Ltd\\BullGuard\\BullGuard.exe"));
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(2)->mTitle, QString("Windows Defender"));
			QCOMPARE(mModel->mAntivirusSection->mContentItems.at(2)->mContent, QString("Last updated: Mon, 26 Nov 2018 10:34:23 GMT\nExecutable path: windowsdefender://"));
			QCOMPARE(true, verifyOrder(mModel->mCombinedAntivirusFirewallSection, {mModel->mAntivirusSection, mModel->mFirewallSection}));
		}

		void test_OnFirewallInformationFailed()
		{
			mModel->onFirewallInformationFailed();
			QCOMPARE(mModel->mFirewallSection->mContentItems.size(), 1);
			QCOMPARE(mModel->mFirewallSection->mContentItems.at(0)->mTitle, QString("Firewall information"));
			QCOMPARE(mModel->mFirewallSection->mContentItems.at(0)->mContent, QString("An error occurred while trying to gather firewall information. Please check the log for more information."));
			QCOMPARE(true, verifyOrder(mModel->mCombinedAntivirusFirewallSection, {mModel->mAntivirusSection, mModel->mFirewallSection}));
		}

		void test_OnConnectionTestDone_data()
		{
			QTest::addColumn<bool>("proxySet");
			QTest::addColumn<bool>("pingTestOnProxy");
			QTest::addColumn<bool>("connectionTestOnProxy");
			QTest::addColumn<bool>("connectionTestWithoutProxy");

			QTest::newRow("proxyConnectionSuccessful") << true << true << true << false;
			QTest::newRow("connectionWithoutProxySuccessful") << false << false << false << true;
			QTest::newRow("proxyConnectionNotSuccessful") << true << false << false << false;
			QTest::newRow("noConnection") << false << false << false << false;
		}

		void test_OnConnectionTestDone()
		{
			QFETCH(bool, proxySet);
			QFETCH(bool, pingTestOnProxy);
			QFETCH(bool, connectionTestOnProxy);
			QFETCH(bool, connectionTestWithoutProxy);

			mModel->mConnectionTest.mIsProxySet = proxySet;
			mModel->mConnectionTest.mPingTestOnProxySuccessful = pingTestOnProxy;
			mModel->mConnectionTest.mConnectionTestWithProxySuccessful = connectionTestOnProxy;
			mModel->mConnectionTest.mConnectionTestWithoutProxySuccessful = connectionTestWithoutProxy;

			mModel->onConnectionTestDone();
			QCOMPARE(mModel->mNetworkConnectionSection->mContentItems.size(), 1);
			QCOMPARE(mModel->mNetworkConnectionSection->mContentItems.at(0)->mTitle, QString("Proxy information"));

			QString contentString;
			if (proxySet)
			{
				contentString = QString("Hostname: \nPort: \nType: \nCapabilities: \nPing test to proxy: ");
				contentString += pingTestOnProxy ? QString("Successful") : QString("Failed");
				contentString += QString("\nConnection test with proxy: ");
				contentString += connectionTestOnProxy ? QString("Successful") : QString("Failed");
			}
			else
			{
				contentString = QString("No proxy found");
			}

			contentString += QString("\nConnection test without proxy: ");
			contentString += connectionTestWithoutProxy ? QString("Successful") : QString("Failed");

			QCOMPARE(mModel->mNetworkConnectionSection->mContentItems.at(0)->mContent, contentString);
			QCOMPARE(true, verifyOrder(mModel->mCombinedNetworkSection, {mModel->mNetworkConnectionSection, mModel->mNetworkInterfaceSection}));
		}

};

QTEST_GUILESS_MAIN(test_DiagnosisModel)
#include "test_DiagnosisModel.moc"

{'repo_name': 'Governikus/AusweisApp2', 'stars': '220', 'repo_language': 'C++', 'file_name': 'cmd.cmake', 'mime_type': 'text/plain', 'hash': 3183179573331820446, 'source_dataset': 'data'}


import os

var
  code = if paramCount() > 0: readFile paramStr 1
         else: readAll stdin
  tape = newSeq[char]()
  d    = 0
  i    = 0

proc run(skip = false): bool =
  while d >= 0 and i < code.len:
    if d >= tape.len: tape.add '\0'

    if code[i] == '[':
      inc i
      let p = i
      while run(tape[d] == '\0'): i = p
    elif code[i] == ']':
      return tape[d] != '\0'
    elif not skip:
      case code[i]
      of '+': inc tape[d]
      of '-': dec tape[d]
      of '>': inc d
      of '<': dec d
      of '.': stdout.write tape[d]
      of ',': tape[d] = stdin.readChar
      else: discard

    inc i

discard run()

{'repo_name': 'acmeism/RosettaCodeData', 'stars': '336', 'repo_language': 'None', 'file_name': 'loops-downward-for.cobol', 'mime_type': 'text/plain', 'hash': -3988967723362961051, 'source_dataset': 'data'}


package io.casperlabs.storage.era

import cats._
import cats.implicits._
import cats.effect.Sync
import com.google.common.cache.{Cache, CacheBuilder}
import java.util.concurrent.TimeUnit
import io.casperlabs.storage.BlockHash
import io.casperlabs.casper.consensus.Era

class CachingEraStorage[F[_]: Sync](
    underlying: EraStorage[F],
    eraCache: Cache[BlockHash, Era]
) extends EraStorage[F] {
  private def cacheEra(era: Era) = Sync[F].delay {
    eraCache.put(era.keyBlockHash, era)
  }

  override def addEra(era: Era) =
    for {
      isNew <- underlying.addEra(era)
      _     <- cacheEra(era).whenA(isNew)
    } yield isNew

  override def getEra(keyBlockHash: BlockHash): F[Option[Era]] =
    Sync[F].delay(Option(eraCache.getIfPresent(keyBlockHash))) flatMap {
      case Some(era) => era.some.pure[F]
      case None =>
        underlying.getEra(keyBlockHash) flatMap {
          case Some(era) => cacheEra(era).as(era.some)
          case None      => none.pure[F]
        }
    }

  override def getChildEras(keyBlockHash: BlockHash) =
    underlying.getChildEras(keyBlockHash)

  override def getChildlessEras =
    underlying.getChildlessEras
}

object CachingEraStorage {
  def apply[F[_]: Sync](underlying: EraStorage[F]): F[CachingEraStorage[F]] = Sync[F].delay {
    val cache = CacheBuilder
      .newBuilder()
      .expireAfterAccess(1, TimeUnit.HOURS)
      .build[BlockHash, Era]
    new CachingEraStorage[F](underlying, cache)
  }
}

{'repo_name': 'CasperLabs/CasperLabs', 'stars': '102', 'repo_language': 'Scala', 'file_name': 'ObservableOpsSpec.scala', 'mime_type': 'text/plain', 'hash': 8851066459390605598, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * Base class for DOM Core's nsIDOMComment, nsIDOMDocumentType, nsIDOMText,
 * nsIDOMCDATASection, and nsIDOMProcessingInstruction nodes.
 */

#include "mozilla/DebugOnly.h"

#include "nsGenericDOMDataNode.h"
#include "mozilla/AsyncEventDispatcher.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/dom/Element.h"
#include "mozilla/dom/ShadowRoot.h"
#include "nsIDocument.h"
#include "nsIDOMDocument.h"
#include "nsReadableUtils.h"
#include "mozilla/InternalMutationEvent.h"
#include "nsIURI.h"
#include "nsIDOMEvent.h"
#include "nsIDOMText.h"
#include "nsCOMPtr.h"
#include "nsDOMString.h"
#include "nsIDOMUserDataHandler.h"
#include "nsChangeHint.h"
#include "nsCOMArray.h"
#include "nsNodeUtils.h"
#include "mozilla/dom/DirectionalityUtils.h"
#include "nsBindingManager.h"
#include "nsCCUncollectableMarker.h"
#include "mozAutoDocUpdate.h"

#include "pldhash.h"
#include "prprf.h"
#include "nsWrapperCacheInlines.h"

using namespace mozilla;
using namespace mozilla::dom;

nsGenericDOMDataNode::nsGenericDOMDataNode(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo)
  : nsIContent(aNodeInfo)
{
  NS_ABORT_IF_FALSE(mNodeInfo->NodeType() == nsIDOMNode::TEXT_NODE ||
                    mNodeInfo->NodeType() == nsIDOMNode::CDATA_SECTION_NODE ||
                    mNodeInfo->NodeType() == nsIDOMNode::COMMENT_NODE ||
                    mNodeInfo->NodeType() ==
                      nsIDOMNode::PROCESSING_INSTRUCTION_NODE ||
                    mNodeInfo->NodeType() == nsIDOMNode::DOCUMENT_TYPE_NODE,
                    "Bad NodeType in aNodeInfo");
}

nsGenericDOMDataNode::nsGenericDOMDataNode(already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo)
  : nsIContent(aNodeInfo)
{
  NS_ABORT_IF_FALSE(mNodeInfo->NodeType() == nsIDOMNode::TEXT_NODE ||
                    mNodeInfo->NodeType() == nsIDOMNode::CDATA_SECTION_NODE ||
                    mNodeInfo->NodeType() == nsIDOMNode::COMMENT_NODE ||
                    mNodeInfo->NodeType() ==
                      nsIDOMNode::PROCESSING_INSTRUCTION_NODE ||
                    mNodeInfo->NodeType() == nsIDOMNode::DOCUMENT_TYPE_NODE,
                    "Bad NodeType in aNodeInfo");
}

nsGenericDOMDataNode::~nsGenericDOMDataNode()
{
  NS_PRECONDITION(!IsInDoc(),
                  "Please remove this from the document properly");
  if (GetParent()) {
    NS_RELEASE(mParent);
  }
}

NS_IMPL_CYCLE_COLLECTION_CLASS(nsGenericDOMDataNode)

NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(nsGenericDOMDataNode)

NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsGenericDOMDataNode)
  return Element::CanSkip(tmp, aRemovingAllowed);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END

NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(nsGenericDOMDataNode)
  return Element::CanSkipInCC(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END

NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsGenericDOMDataNode)
  return Element::CanSkipThis(tmp);
NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsGenericDOMDataNode)
  if (MOZ_UNLIKELY(cb.WantDebugInfo())) {
    char name[40];
    PR_snprintf(name, sizeof(name), "nsGenericDOMDataNode (len=%d)",
                tmp->mText.GetLength());
    cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name);
  } else {
    NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsGenericDOMDataNode, tmp->mRefCnt.get())
  }

  // Always need to traverse script objects, so do that before we check
  // if we're uncollectable.
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS

  if (!nsINode::Traverse(tmp, cb)) {
    return NS_SUCCESS_INTERRUPTED_TRAVERSE;
  }

  nsDataSlots *slots = tmp->GetExistingDataSlots();
  if (slots) {
    slots->Traverse(cb);
  }
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsGenericDOMDataNode)
  nsINode::Unlink(tmp);

  nsDataSlots *slots = tmp->GetExistingDataSlots();
  if (slots) {
    slots->Unlink();
  }
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_INTERFACE_MAP_BEGIN(nsGenericDOMDataNode)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsGenericDOMDataNode)
  NS_INTERFACE_MAP_ENTRY(nsIContent)
  NS_INTERFACE_MAP_ENTRY(nsINode)
  NS_INTERFACE_MAP_ENTRY(nsIDOMEventTarget)
  NS_INTERFACE_MAP_ENTRY(mozilla::dom::EventTarget)
  NS_INTERFACE_MAP_ENTRY_TEAROFF(nsISupportsWeakReference,
                                 new nsNodeSupportsWeakRefTearoff(this))
  NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOMXPathNSResolver,
                                 new nsNode3Tearoff(this))
  // DOM bindings depend on the identity pointer being the
  // same as nsINode (which nsIContent inherits).
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIContent)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(nsGenericDOMDataNode)
NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_LAST_RELEASE(nsGenericDOMDataNode,
                                                   nsNodeUtils::LastRelease(this))

void
nsGenericDOMDataNode::GetNodeValueInternal(nsAString& aNodeValue)
{
  DebugOnly<nsresult> rv = GetData(aNodeValue);
  NS_ASSERTION(NS_SUCCEEDED(rv), "GetData() failed!");
}

void
nsGenericDOMDataNode::SetNodeValueInternal(const nsAString& aNodeValue,
                                           ErrorResult& aError)
{
  aError = SetTextInternal(0, mText.GetLength(), aNodeValue.BeginReading(),
                           aNodeValue.Length(), true);
}

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

// Implementation of nsIDOMCharacterData

nsresult
nsGenericDOMDataNode::GetData(nsAString& aData) const
{
  if (mText.Is2b()) {
    aData.Assign(mText.Get2b(), mText.GetLength());
  } else {
    // Must use Substring() since nsDependentCString() requires null
    // terminated strings.

    const char *data = mText.Get1b();

    if (data) {
      CopyASCIItoUTF16(Substring(data, data + mText.GetLength()), aData);
    } else {
      aData.Truncate();
    }
  }

  return NS_OK;
}

nsresult
nsGenericDOMDataNode::SetData(const nsAString& aData)
{
  return SetTextInternal(0, mText.GetLength(), aData.BeginReading(),
                         aData.Length(), true);
}

nsresult
nsGenericDOMDataNode::GetLength(uint32_t* aLength)
{
  *aLength = mText.GetLength();
  return NS_OK;
}

nsresult
nsGenericDOMDataNode::SubstringData(uint32_t aStart, uint32_t aCount,
                                    nsAString& aReturn)
{
  ErrorResult rv;
  SubstringData(aStart, aCount, aReturn, rv);
  return rv.ErrorCode();
}

void
nsGenericDOMDataNode::SubstringData(uint32_t aStart, uint32_t aCount,
                                    nsAString& aReturn, ErrorResult& rv)
{
  aReturn.Truncate();

  uint32_t textLength = mText.GetLength();
  if (aStart > textLength) {
    rv.Throw(NS_ERROR_DOM_INDEX_SIZE_ERR);
    return;
  }

  uint32_t amount = aCount;
  if (amount > textLength - aStart) {
    amount = textLength - aStart;
  }

  if (mText.Is2b()) {
    aReturn.Assign(mText.Get2b() + aStart, amount);
  } else {
    // Must use Substring() since nsDependentCString() requires null
    // terminated strings.

    const char *data = mText.Get1b() + aStart;
    CopyASCIItoUTF16(Substring(data, data + amount), aReturn);
  }
}

NS_IMETHODIMP
nsGenericDOMDataNode::MozRemove()
{
  Remove();
  return NS_OK;
}

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

nsresult
nsGenericDOMDataNode::AppendData(const nsAString& aData)
{
  return SetTextInternal(mText.GetLength(), 0, aData.BeginReading(),
                         aData.Length(), true);
}

nsresult
nsGenericDOMDataNode::InsertData(uint32_t aOffset,
                                 const nsAString& aData)
{
  return SetTextInternal(aOffset, 0, aData.BeginReading(),
                         aData.Length(), true);
}

nsresult
nsGenericDOMDataNode::DeleteData(uint32_t aOffset, uint32_t aCount)
{
  return SetTextInternal(aOffset, aCount, nullptr, 0, true);
}

nsresult
nsGenericDOMDataNode::ReplaceData(uint32_t aOffset, uint32_t aCount,
                                  const nsAString& aData)
{
  return SetTextInternal(aOffset, aCount, aData.BeginReading(),
                         aData.Length(), true);
}

nsresult
nsGenericDOMDataNode::SetTextInternal(uint32_t aOffset, uint32_t aCount,
                                      const char16_t* aBuffer,
                                      uint32_t aLength, bool aNotify,
                                      CharacterDataChangeInfo::Details* aDetails)
{
  NS_PRECONDITION(aBuffer || !aLength,
                  "Null buffer passed to SetTextInternal!");

  // sanitize arguments
  uint32_t textLength = mText.GetLength();
  if (aOffset > textLength) {
    return NS_ERROR_DOM_INDEX_SIZE_ERR;
  }

  if (aCount > textLength - aOffset) {
    aCount = textLength - aOffset;
  }

  uint32_t endOffset = aOffset + aCount;

  // Make sure the text fragment can hold the new data.
  if (aLength > aCount && !mText.CanGrowBy(aLength - aCount)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  nsIDocument *document = GetCurrentDoc();
  mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, aNotify);

  bool haveMutationListeners = aNotify &&
    nsContentUtils::HasMutationListeners(this,
      NS_EVENT_BITS_MUTATION_CHARACTERDATAMODIFIED,
      this);

  nsCOMPtr<nsIAtom> oldValue;
  if (haveMutationListeners) {
    oldValue = GetCurrentValueAtom();
  }

  if (aNotify) {
    CharacterDataChangeInfo info = {
      aOffset == textLength,
      aOffset,
      endOffset,
      aLength,
      aDetails
    };
    nsNodeUtils::CharacterDataWillChange(this, &info);
  }

  Directionality oldDir = eDir_NotSet;
  bool dirAffectsAncestor = (NodeType() == nsIDOMNode::TEXT_NODE &&
                             TextNodeWillChangeDirection(this, &oldDir, aOffset));

  if (aOffset == 0 && endOffset == textLength) {
    // Replacing whole text or old text was empty.  Don't bother to check for
    // bidi in this string if the document already has bidi enabled.
    bool ok = mText.SetTo(aBuffer, aLength, !document || !document->GetBidiEnabled());
    NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);
  }
  else if (aOffset == textLength) {
    // Appending to existing
    bool ok = mText.Append(aBuffer, aLength, !document || !document->GetBidiEnabled());
    NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);
  }
  else {
    // Merging old and new

    // Allocate new buffer
    int32_t newLength = textLength - aCount + aLength;
    char16_t* to = new char16_t[newLength];
    NS_ENSURE_TRUE(to, NS_ERROR_OUT_OF_MEMORY);

    // Copy over appropriate data
    if (aOffset) {
      mText.CopyTo(to, 0, aOffset);
    }
    if (aLength) {
      memcpy(to + aOffset, aBuffer, aLength * sizeof(char16_t));
    }
    if (endOffset != textLength) {
      mText.CopyTo(to + aOffset + aLength, endOffset, textLength - endOffset);
    }

    bool ok = mText.SetTo(to, newLength, !document || !document->GetBidiEnabled());

    delete [] to;

    NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY);
  }

  UnsetFlags(NS_CACHED_TEXT_IS_ONLY_WHITESPACE);

  if (document && mText.IsBidi()) {
    // If we found bidi characters in mText.SetTo() above, indicate that the
    // document contains bidi characters.
    document->SetBidiEnabled();
  }

  if (dirAffectsAncestor) {
    TextNodeChangedDirection(this, oldDir, aNotify);
  }

  // Notify observers
  if (aNotify) {
    CharacterDataChangeInfo info = {
      aOffset == textLength,
      aOffset,
      endOffset,
      aLength,
      aDetails
    };
    nsNodeUtils::CharacterDataChanged(this, &info);

    if (haveMutationListeners) {
      InternalMutationEvent mutation(true, NS_MUTATION_CHARACTERDATAMODIFIED);

      mutation.mPrevAttrValue = oldValue;
      if (aLength > 0) {
        nsAutoString val;
        mText.AppendTo(val);
        mutation.mNewAttrValue = do_GetAtom(val);
      }

      mozAutoSubtreeModified subtree(OwnerDoc(), this);
      (new AsyncEventDispatcher(this, mutation))->RunDOMEventWhenSafe();
    }
  }

  return NS_OK;
}

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

// Implementation of nsIContent

#ifdef DEBUG
void
nsGenericDOMDataNode::ToCString(nsAString& aBuf, int32_t aOffset,
                                int32_t aLen) const
{
  if (mText.Is2b()) {
    const char16_t* cp = mText.Get2b() + aOffset;
    const char16_t* end = cp + aLen;

    while (cp < end) {
      char16_t ch = *cp++;
      if (ch == '&') {
        aBuf.AppendLiteral("&");
      } else if (ch == '<') {
        aBuf.AppendLiteral("<");
      } else if (ch == '>') {
        aBuf.AppendLiteral(">");
      } else if ((ch < ' ') || (ch >= 127)) {
        char buf[10];
        PR_snprintf(buf, sizeof(buf), "\\u%04x", ch);
        AppendASCIItoUTF16(buf, aBuf);
      } else {
        aBuf.Append(ch);
      }
    }
  } else {
    unsigned char* cp = (unsigned char*)mText.Get1b() + aOffset;
    const unsigned char* end = cp + aLen;

    while (cp < end) {
      char16_t ch = *cp++;
      if (ch == '&') {
        aBuf.AppendLiteral("&");
      } else if (ch == '<') {
        aBuf.AppendLiteral("<");
      } else if (ch == '>') {
        aBuf.AppendLiteral(">");
      } else if ((ch < ' ') || (ch >= 127)) {
        char buf[10];
        PR_snprintf(buf, sizeof(buf), "\\u%04x", ch);
        AppendASCIItoUTF16(buf, aBuf);
      } else {
        aBuf.Append(ch);
      }
    }
  }
}
#endif

nsresult
nsGenericDOMDataNode::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
                                 nsIContent* aBindingParent,
                                 bool aCompileEventHandlers)
{
  NS_PRECONDITION(aParent || aDocument, "Must have document if no parent!");
  NS_PRECONDITION(NODE_FROM(aParent, aDocument)->OwnerDoc() == OwnerDoc(),
                  "Must have the same owner document");
  NS_PRECONDITION(!aParent || aDocument == aParent->GetCurrentDoc(),
                  "aDocument must be current doc of aParent");
  NS_PRECONDITION(!GetCurrentDoc() && !IsInDoc(),
                  "Already have a document.  Unbind first!");
  // Note that as we recurse into the kids, they'll have a non-null parent.  So
  // only assert if our parent is _changing_ while we have a parent.
  NS_PRECONDITION(!GetParent() || aParent == GetParent(),
                  "Already have a parent.  Unbind first!");
  NS_PRECONDITION(!GetBindingParent() ||
                  aBindingParent == GetBindingParent() ||
                  (!aBindingParent && aParent &&
                   aParent->GetBindingParent() == GetBindingParent()),
                  "Already have a binding parent.  Unbind first!");
  NS_PRECONDITION(aBindingParent != this,
                  "Content must not be its own binding parent");
  NS_PRECONDITION(!IsRootOfNativeAnonymousSubtree() ||
                  aBindingParent == aParent,
                  "Native anonymous content must have its parent as its "
                  "own binding parent");

  if (!aBindingParent && aParent) {
    aBindingParent = aParent->GetBindingParent();
  }

  // First set the binding parent
  if (aBindingParent) {
    NS_ASSERTION(IsRootOfNativeAnonymousSubtree() ||
                 !HasFlag(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE) ||
                 (aParent && aParent->IsInNativeAnonymousSubtree()),
                 "Trying to re-bind content from native anonymous subtree to "
                 "non-native anonymous parent!");
    DataSlots()->mBindingParent = aBindingParent; // Weak, so no addref happens.
    if (aParent->IsInNativeAnonymousSubtree()) {
      SetFlags(NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE);
    }
    if (aParent->HasFlag(NODE_CHROME_ONLY_ACCESS)) {
      SetFlags(NODE_CHROME_ONLY_ACCESS);
    }
    if (aParent->IsInShadowTree()) {
      ClearSubtreeRootPointer();
      SetFlags(NODE_IS_IN_SHADOW_TREE);
    }
    ShadowRoot* parentContainingShadow = aParent->GetContainingShadow();
    if (parentContainingShadow) {
      DataSlots()->mContainingShadow = parentContainingShadow;
    }
  }

  // Set parent
  if (aParent) {
    if (!GetParent()) {
      NS_ADDREF(aParent);
    }
    mParent = aParent;
  }
  else {
    mParent = aDocument;
  }
  SetParentIsContent(aParent);

  // XXXbz sXBL/XBL2 issue!

  // Set document
  if (aDocument) {
    // We no longer need to track the subtree pointer (and in fact we'll assert
    // if we do this any later).
    ClearSubtreeRootPointer();

    // XXX See the comment in Element::BindToTree
    SetInDocument();
    if (mText.IsBidi()) {
      aDocument->SetBidiEnabled();
    }
    // Clear the lazy frame construction bits.
    UnsetFlags(NODE_NEEDS_FRAME | NODE_DESCENDANTS_NEED_FRAMES);
  } else if (!IsInShadowTree()) {
    // If we're not in the doc and not in a shadow tree,
    // update our subtree pointer.
    SetSubtreeRootPointer(aParent->SubtreeRoot());
  }

  nsNodeUtils::ParentChainChanged(this);

  UpdateEditableState(false);

  NS_POSTCONDITION(aDocument == GetCurrentDoc(), "Bound to wrong document");
  NS_POSTCONDITION(aParent == GetParent(), "Bound to wrong parent");
  NS_POSTCONDITION(aBindingParent == GetBindingParent(),
                   "Bound to wrong binding parent");

  return NS_OK;
}

void
nsGenericDOMDataNode::UnbindFromTree(bool aDeep, bool aNullParent)
{
  // Unset frame flags; if we need them again later, they'll get set again.
  UnsetFlags(NS_CREATE_FRAME_IF_NON_WHITESPACE |
             NS_REFRAME_IF_WHITESPACE);

  nsIDocument *document = GetCurrentDoc();
  if (document) {
    // Notify XBL- & nsIAnonymousContentCreator-generated
    // anonymous content that the document is changing.
    // This is needed to update the insertion point.
    document->BindingManager()->RemovedFromDocument(this, document);
  }

  if (aNullParent) {
    if (GetParent()) {
      NS_RELEASE(mParent);
    } else {
      mParent = nullptr;
    }
    SetParentIsContent(false);
  }
  ClearInDocument();
  UnsetFlags(NODE_IS_IN_SHADOW_TREE);

  // Begin keeping track of our subtree root.
  SetSubtreeRootPointer(aNullParent ? this : mParent->SubtreeRoot());

  nsDataSlots *slots = GetExistingDataSlots();
  if (slots) {
    slots->mBindingParent = nullptr;
    slots->mContainingShadow = nullptr;
  }

  nsNodeUtils::ParentChainChanged(this);
}

already_AddRefed<nsINodeList>
nsGenericDOMDataNode::GetChildren(uint32_t aFilter)
{
  return nullptr;
}

nsresult
nsGenericDOMDataNode::SetAttr(int32_t aNameSpaceID, nsIAtom* aAttr,
                              nsIAtom* aPrefix, const nsAString& aValue,
                              bool aNotify)
{
  return NS_OK;
}

nsresult
nsGenericDOMDataNode::UnsetAttr(int32_t aNameSpaceID, nsIAtom* aAttr,
                                bool aNotify)
{
  return NS_OK;
}

const nsAttrName*
nsGenericDOMDataNode::GetAttrNameAt(uint32_t aIndex) const
{
  return nullptr;
}

uint32_t
nsGenericDOMDataNode::GetAttrCount() const
{
  return 0;
}

uint32_t
nsGenericDOMDataNode::GetChildCount() const
{
  return 0;
}

nsIContent *
nsGenericDOMDataNode::GetChildAt(uint32_t aIndex) const
{
  return nullptr;
}

nsIContent * const *
nsGenericDOMDataNode::GetChildArray(uint32_t* aChildCount) const
{
  *aChildCount = 0;
  return nullptr;
}

int32_t
nsGenericDOMDataNode::IndexOf(const nsINode* aPossibleChild) const
{
  return -1;
}

nsresult
nsGenericDOMDataNode::InsertChildAt(nsIContent* aKid, uint32_t aIndex,
                                    bool aNotify)
{
  return NS_OK;
}

void
nsGenericDOMDataNode::RemoveChildAt(uint32_t aIndex, bool aNotify)
{
}

nsIContent *
nsGenericDOMDataNode::GetBindingParent() const
{
  nsDataSlots *slots = GetExistingDataSlots();
  return slots ? slots->mBindingParent : nullptr;
}

ShadowRoot *
nsGenericDOMDataNode::GetShadowRoot() const
{
  return nullptr;
}

ShadowRoot *
nsGenericDOMDataNode::GetContainingShadow() const
{
  nsDataSlots *slots = GetExistingDataSlots();
  return slots ? slots->mContainingShadow : nullptr;
}

void
nsGenericDOMDataNode::SetShadowRoot(ShadowRoot* aShadowRoot)
{
}

nsTArray<nsIContent*>&
nsGenericDOMDataNode::DestInsertionPoints()
{
  nsDataSlots *slots = DataSlots();
  return slots->mDestInsertionPoints;
}

nsTArray<nsIContent*>*
nsGenericDOMDataNode::GetExistingDestInsertionPoints() const
{
  nsDataSlots *slots = GetExistingDataSlots();
  if (slots) {
    return &slots->mDestInsertionPoints;
  }
  return nullptr;
}

nsXBLBinding *
nsGenericDOMDataNode::GetXBLBinding() const
{
  return nullptr;
}

void
nsGenericDOMDataNode::SetXBLBinding(nsXBLBinding* aBinding,
                                    nsBindingManager* aOldBindingManager)
{
}

nsIContent *
nsGenericDOMDataNode::GetXBLInsertionParent() const
{
  if (HasFlag(NODE_MAY_BE_IN_BINDING_MNGR)) {
    nsDataSlots *slots = GetExistingDataSlots();
    if (slots) {
      return slots->mXBLInsertionParent;
    }
  }

  return nullptr;
}

void
nsGenericDOMDataNode::SetXBLInsertionParent(nsIContent* aContent)
{
  if (aContent) {
    nsDataSlots *slots = DataSlots();
    SetFlags(NODE_MAY_BE_IN_BINDING_MNGR);
    slots->mXBLInsertionParent = aContent;
  } else {
    nsDataSlots *slots = GetExistingDataSlots();
    if (slots) {
      slots->mXBLInsertionParent = nullptr;
    }
  }
}

CustomElementData *
nsGenericDOMDataNode::GetCustomElementData() const
{
  return nullptr;
}

void
nsGenericDOMDataNode::SetCustomElementData(CustomElementData* aData)
{
}

bool
nsGenericDOMDataNode::IsNodeOfType(uint32_t aFlags) const
{
  return !(aFlags & ~(eCONTENT | eDATA_NODE));
}

void
nsGenericDOMDataNode::SaveSubtreeState()
{
}

void
nsGenericDOMDataNode::DestroyContent()
{
  // XXX We really should let cycle collection do this, but that currently still
  //     leaks (see https://bugzilla.mozilla.org/show_bug.cgi?id=406684).
  ReleaseWrapper(this);
}

#ifdef DEBUG
void
nsGenericDOMDataNode::List(FILE* out, int32_t aIndent) const
{
}

void
nsGenericDOMDataNode::DumpContent(FILE* out, int32_t aIndent,
                                  bool aDumpAll) const
{
}
#endif

bool
nsGenericDOMDataNode::IsLink(nsIURI** aURI) const
{
  *aURI = nullptr;
  return false;
}

nsINode::nsSlots*
nsGenericDOMDataNode::CreateSlots()
{
  return new nsDataSlots();
}

nsGenericDOMDataNode::nsDataSlots::nsDataSlots()
  : nsINode::nsSlots(), mBindingParent(nullptr)
{
}

void
nsGenericDOMDataNode::nsDataSlots::Traverse(nsCycleCollectionTraversalCallback &cb)
{
  NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mSlots->mXBLInsertionParent");
  cb.NoteXPCOMChild(mXBLInsertionParent.get());

  NS_CYCLE_COLLECTION_NOTE_EDGE_NAME(cb, "mSlots->mContainingShadow");
  cb.NoteXPCOMChild(NS_ISUPPORTS_CAST(nsIContent*, mContainingShadow));
}

void
nsGenericDOMDataNode::nsDataSlots::Unlink()
{
  mXBLInsertionParent = nullptr;
  mContainingShadow = nullptr;
}

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

// Implementation of the nsIDOMText interface

nsresult
nsGenericDOMDataNode::SplitData(uint32_t aOffset, nsIContent** aReturn,
                                bool aCloneAfterOriginal)
{
  *aReturn = nullptr;
  nsresult rv = NS_OK;
  nsAutoString cutText;
  uint32_t length = TextLength();

  if (aOffset > length) {
    return NS_ERROR_DOM_INDEX_SIZE_ERR;
  }

  uint32_t cutStartOffset = aCloneAfterOriginal ? aOffset : 0;
  uint32_t cutLength = aCloneAfterOriginal ? length - aOffset : aOffset;
  rv = SubstringData(cutStartOffset, cutLength, cutText);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsIDocument* document = GetCurrentDoc();
  mozAutoDocUpdate updateBatch(document, UPDATE_CONTENT_MODEL, true);

  // Use Clone for creating the new node so that the new node is of same class
  // as this node!
  nsCOMPtr<nsIContent> newContent = CloneDataNode(mNodeInfo, false);
  if (!newContent) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  newContent->SetText(cutText, true); // XXX should be false?

  CharacterDataChangeInfo::Details details = {
    CharacterDataChangeInfo::Details::eSplit, newContent
  };
  rv = SetTextInternal(cutStartOffset, cutLength, nullptr, 0, true,
                       aCloneAfterOriginal ? &details : nullptr);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsCOMPtr<nsINode> parent = GetParentNode();
  if (parent) {
    int32_t insertionIndex = parent->IndexOf(this);
    if (aCloneAfterOriginal) {
      ++insertionIndex;
    }
    parent->InsertChildAt(newContent, insertionIndex, true);
  }

  newContent.swap(*aReturn);
  return rv;
}

nsresult
nsGenericDOMDataNode::SplitText(uint32_t aOffset, nsIDOMText** aReturn)
{
  nsCOMPtr<nsIContent> newChild;
  nsresult rv = SplitData(aOffset, getter_AddRefs(newChild));
  if (NS_SUCCEEDED(rv)) {
    rv = CallQueryInterface(newChild, aReturn);
  }
  return rv;
}

/* static */ int32_t
nsGenericDOMDataNode::FirstLogicallyAdjacentTextNode(nsIContent* aParent,
                                                     int32_t aIndex)
{
  while (aIndex-- > 0) {
    nsIContent* sibling = aParent->GetChildAt(aIndex);
    if (!sibling->IsNodeOfType(nsINode::eTEXT))
      return aIndex + 1;
  }
  return 0;
}

/* static */ int32_t
nsGenericDOMDataNode::LastLogicallyAdjacentTextNode(nsIContent* aParent,
                                                    int32_t aIndex,
                                                    uint32_t aCount)
{
  while (++aIndex < int32_t(aCount)) {
    nsIContent* sibling = aParent->GetChildAt(aIndex);
    if (!sibling->IsNodeOfType(nsINode::eTEXT))
      return aIndex - 1;
  }
  return aCount - 1;
}

nsresult
nsGenericDOMDataNode::GetWholeText(nsAString& aWholeText)
{
  nsIContent* parent = GetParent();

  // Handle parent-less nodes
  if (!parent)
    return GetData(aWholeText);

  int32_t index = parent->IndexOf(this);
  NS_WARN_IF_FALSE(index >= 0,
                   "Trying to use .wholeText with an anonymous"
                    "text node child of a binding parent?");
  NS_ENSURE_TRUE(index >= 0, NS_ERROR_DOM_NOT_SUPPORTED_ERR);
  int32_t first =
    FirstLogicallyAdjacentTextNode(parent, index);
  int32_t last =
    LastLogicallyAdjacentTextNode(parent, index, parent->GetChildCount());

  aWholeText.Truncate();

  nsCOMPtr<nsIDOMText> node;
  nsAutoString tmp;
  do {
    node = do_QueryInterface(parent->GetChildAt(first));
    node->GetData(tmp);
    aWholeText.Append(tmp);
  } while (first++ < last);

  return NS_OK;
}

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

// Implementation of the nsIContent interface text functions

const nsTextFragment *
nsGenericDOMDataNode::GetText()
{
  return &mText;
}

uint32_t
nsGenericDOMDataNode::TextLength() const
{
  return mText.GetLength();
}

nsresult
nsGenericDOMDataNode::SetText(const char16_t* aBuffer,
                              uint32_t aLength,
                              bool aNotify)
{
  return SetTextInternal(0, mText.GetLength(), aBuffer, aLength, aNotify);
}

nsresult
nsGenericDOMDataNode::AppendText(const char16_t* aBuffer,
                                 uint32_t aLength,
                                 bool aNotify)
{
  return SetTextInternal(mText.GetLength(), 0, aBuffer, aLength, aNotify);
}

bool
nsGenericDOMDataNode::TextIsOnlyWhitespace()
{
  // FIXME: should this method take content language into account?
  if (mText.Is2b()) {
    // The fragment contains non-8bit characters and such characters
    // are never considered whitespace.
    return false;
  }

  if (HasFlag(NS_CACHED_TEXT_IS_ONLY_WHITESPACE)) {
    return HasFlag(NS_TEXT_IS_ONLY_WHITESPACE);
  }

  const char* cp = mText.Get1b();
  const char* end = cp + mText.GetLength();

  while (cp < end) {
    char ch = *cp;

    if (!dom::IsSpaceCharacter(ch)) {
      UnsetFlags(NS_TEXT_IS_ONLY_WHITESPACE);
      SetFlags(NS_CACHED_TEXT_IS_ONLY_WHITESPACE);
      return false;
    }

    ++cp;
  }

  SetFlags(NS_CACHED_TEXT_IS_ONLY_WHITESPACE | NS_TEXT_IS_ONLY_WHITESPACE);
  return true;
}

bool
nsGenericDOMDataNode::HasTextForTranslation()
{
  if (NodeType() != nsIDOMNode::TEXT_NODE &&
      NodeType() != nsIDOMNode::CDATA_SECTION_NODE) {
    return false;
  }

  if (mText.Is2b()) {
    // The fragment contains non-8bit characters which means there
    // was at least one "interesting" character to trigger non-8bit.
    return true;
  }

  if (HasFlag(NS_CACHED_TEXT_IS_ONLY_WHITESPACE) &&
      HasFlag(NS_TEXT_IS_ONLY_WHITESPACE)) {
    return false;
  }

  const char* cp = mText.Get1b();
  const char* end = cp + mText.GetLength();

  unsigned char ch;
  for (; cp < end; cp++) {
    ch = *cp;

    // These are the characters that are letters
    // in the first 256 UTF-8 codepoints.
    if ((ch >= 'a' && ch <= 'z') ||
       (ch >= 'A' && ch <= 'Z') ||
       (ch >= 192 && ch <= 214) ||
       (ch >= 216 && ch <= 246) ||
       (ch >= 248)) {
      return true;
    }
  }

  return false;
}

void
nsGenericDOMDataNode::AppendTextTo(nsAString& aResult)
{
  mText.AppendTo(aResult);
}

bool
nsGenericDOMDataNode::AppendTextTo(nsAString& aResult, const mozilla::fallible_t&)
{
  return mText.AppendTo(aResult, mozilla::fallible_t());
}

already_AddRefed<nsIAtom>
nsGenericDOMDataNode::GetCurrentValueAtom()
{
  nsAutoString val;
  GetData(val);
  return NS_NewAtom(val);
}

NS_IMETHODIMP
nsGenericDOMDataNode::WalkContentStyleRules(nsRuleWalker* aRuleWalker)
{
  return NS_OK;
}

NS_IMETHODIMP_(bool)
nsGenericDOMDataNode::IsAttributeMapped(const nsIAtom* aAttribute) const
{
  return false;
}

nsChangeHint
nsGenericDOMDataNode::GetAttributeChangeHint(const nsIAtom* aAttribute,
                                             int32_t aModType) const
{
  NS_NOTREACHED("Shouldn't be calling this!");
  return nsChangeHint(0);
}

size_t
nsGenericDOMDataNode::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
{
  size_t n = nsIContent::SizeOfExcludingThis(aMallocSizeOf);
  n += mText.SizeOfExcludingThis(aMallocSizeOf);
  return n;
}

{'repo_name': 'ricardoquesada/Spidermonkey', 'stars': '201', 'repo_language': 'C++', 'file_name': 'panelUI.css', 'mime_type': 'text/plain', 'hash': 8660195184492438925, 'source_dataset': 'data'}