text:
<?php
if(file_exists(__DIR__ . '/install.lock')){
    header('location:/');
}

$basePath = substr(__DIR__,0,-6);
@rmdir(__DIR__ . '/temp');

$lists[__DIR__]['read'] = is_readable(__DIR__);
$lists[__DIR__]['write'] = is_writable(__DIR__);
$lists[__DIR__]['executable'] = @mkdir (__DIR__ . '/temp');
@rmdir(__DIR__ . '/temp');

$storagePath = $basePath . 'storage';
@rmdir ($storagePath . '/temp');

$lists[$storagePath]['read'] = is_readable($storagePath);
$lists[$storagePath]['write'] = is_writable($storagePath);
$lists[$storagePath]['executable'] = @mkdir($storagePath . '/temp');

@rmdir ($storagePath . '/temp');

$vendorPath = $basePath .'vendor';
@rmdir($vendorPath.'/temp');

$lists[$vendorPath]['read'] = is_readable($vendorPath);
$lists[$vendorPath]['write'] = is_writable($vendorPath);
$lists[$vendorPath]['executable'] = @mkdir($vendorPath.'/temp');

@rmdir($vendorPath.'/temp');

$cachePath = $basePath . 'bootstrap'. DIRECTORY_SEPARATOR. 'cache' ;
@rmdir($cachePath . '/temp');

$lists[$cachePath]['read'] = is_readable($cachePath);
$lists[$cachePath]['write'] = is_writable($cachePath);
$lists[$cachePath]['executable'] = @mkdir ($cachePath . '/temp');

@rmdir($cachePath . '/temp');

$uploadPath = __DIR__ . DIRECTORY_SEPARATOR .'uploads';
@rmdir($uploadPath . '/temp');

$lists[$uploadPath]['read'] = is_readable($uploadPath);
$lists[$uploadPath]['write'] = is_writable($uploadPath);
$lists[$uploadPath]['executable'] = @mkdir ($uploadPath . '/temp');
@rmdir($uploadPath . '/temp');

$extends['fileinfo'] = extension_loaded('fileinfo');
$extends['gd'] = extension_loaded('gd');
$extends['iconv'] = extension_loaded('iconv');
$extends['json'] = extension_loaded('json');
$extends['mbstring'] = extension_loaded('mbstring');
$extends['pdo'] = extension_loaded('pdo');
$extends['pdo_mysql'] = extension_loaded('pdo_mysql');
$extends['openssl'] = extension_loaded('openssl');
$extends['tokenizer'] = extension_loaded('tokenizer');
$extends['ctype'] = extension_loaded('ctype');
$extends['curl'] = extension_loaded('curl');

if(!file_exists($basePath . '.env') && file_exists($basePath.'.env.example')) {
    $env = file_get_contents($basePath.'.env.example');

    $env = str_replace('APP_DEBUG=true', 'APP_DEBUG=false', $env);

    if(function_exists('openssl_random_pseudo_bytes')) {
        $secure = true;
        $app_key = 'base64:' . base64_encode(openssl_random_pseudo_bytes(32,$secure));

        $env = str_replace('APP_KEY=', 'APP_KEY=' . $app_key, $env);
    }
    file_put_contents($basePath.'.env', $env);
}
?>
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>SmartWiki安装</title>
    <link href="static/bootstrap/css/bootstrap.min.css" rel="stylesheet">

SmartWiki安装

        <button type="button" class="close" data-dismiss="alert">×Close</button>

    <form method="post" action="{{route('install.index')}}" class="form-horizontal" role="form">

PHP版本 PHP版本必须大于等于5.6

当前PHP版本	<?php echo PHP_VERSION;?>

目录权限检测

                目录	读	写	执行

            <?php foreach ($lists as $path=>$item):?>

                <?php echo $path;?>
                <?php echo $item['read']?'[√]' : '[×]' ;?>
                <?php echo $item['write']?'[√]' : '[×]'; ?>
                <?php echo $item['executable']?'[√]' : '[×]'; ?>

            <?php endforeach;?>

PHP扩展检测

扩展名	是否安装

                <?php foreach ($extends as $name=>$isLoad):?>

                    <?php echo $name;?>
                    <?php echo $isLoad?'[√]' : '[×]' ;?>

                <?php endforeach;?>

                下一步

    </form>


text:
{HEADER}

{CATEGORY} Attendance

    {DATE_RANGE}

{CATEGORY_ATTENDANCES}

redpajama_set_name: RedPajamaGithub


text:
<?php
$this->pageTitle=t('Update Villa owner Info');
$this->titleImage='images/pencil2.png';
$this->widget('cmswidgets.villaowner.VillaownerUpdateWidget',array());
?>


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/fsnotify/fsnotify"
	"github.com/pierods/smac"
)

var (
	autoComplete smac.AutoComplete
	home         []byte
)

func handler(rw http.ResponseWriter, r *http.Request) {

	path := r.URL.Path

	if strings.HasPrefix(path, "/complete") {
		splitPath := strings.Split(path, "/")
		stem := splitPath[2]

		completions, err := autoComplete.Complete(stem)
		if err != nil {
			rw.Write([]byte(""))
			return
		}

		rw.Header().Set("Content-Type", "application/json")
		rw.WriteHeader(200)
		json.NewEncoder(rw).Encode(&completions)
		return
	}

	if strings.HasPrefix(path, "/accept") {
		splitPath := strings.Split(path, "/")
		acceptedWord := splitPath[2]

		err := autoComplete.Accept(acceptedWord)
		if err != nil {
			err = autoComplete.Learn(acceptedWord)
			if err != nil {
				autoComplete.Accept(acceptedWord)
			}
		}
		rw.WriteHeader(200)
		return
	}

	rw.Header().Set("Content/Type", "text/html")
	rw.WriteHeader(200)
	rw.Write(home)
}

func main() {

	goPath := os.Getenv("GOPATH")

	homeFile := goPath + "/src/github.com/pierods/smac/demo/demo.html"
	f, fErr := os.Open(homeFile)
	if fErr != nil {
		fmt.Println(fErr)
		os.Exit(-1)
	}
	home, fErr = ioutil.ReadAll(f)

	if fErr != nil {
		fmt.Println(fErr)
		os.Exit(-1)
	}

	f.Close()

	wordFile := goPath + "/src/github.com/pierods/smac/demo/allwords.txt"

	var err error

	autoCompleteL, err := smac.NewAutoCompleteLinoF(wordFile, 2, 0, 0)

	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
	autoComplete = &autoCompleteL

	watcher := watch(homeFile)
	defer watcher.Close()
	http.HandleFunc("/", handler)
	fmt.Println("Listener : Started : Listening on port 30000")
	http.ListenAndServe(":30000", nil)
}

func watch(fileName string) *fsnotify.Watcher {

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					fmt.Println("re-reading file:", event.Name)
					f, fErr := os.Open(fileName)
					if fErr != nil {
						fmt.Println(fErr)
						os.Exit(-1)
					}
					home, fErr = ioutil.ReadAll(f)
					if fErr != nil {
						fmt.Println(fErr)
						os.Exit(-1)
					}
					f.Close()
				}
			case err := <-watcher.Errors:
				fmt.Println("error:", err)
			}
		}
	}()

	err = watcher.Add(fileName)
	if err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
	return watcher
}


text:
package com.rcextract.minecord.utils;

import java.util.Collection;
import java.util.HashSet;
import java.util.function.Predicate;

public class EnhancedSet<T> extends HashSet<T> {

	private static final long serialVersionUID = -4004081408851334978L;

	public EnhancedSet() {
		super();
	}

	public EnhancedSet(Collection<T> collection) {
		super(collection);
	}

	/**
	 * Returns the unique value when the size of this set is 1, otherwise null.
	 * @return The unique value when the size of this set is 1, otherwise null.
	 */
	public T get() {
		if (super.size() == 1) return super.iterator().next();
		return null;
	}

	/**
	 * Returns all the elements which match the requirements of the filter.
	 * @param filter The filter.
	 * @return All the elements which match the requirements of the filter.
	 */
	public EnhancedSet<T> getIf(Predicate<? super T> filter) {
		EnhancedSet<T> set = new EnhancedSet<T>();
		super.forEach(t -> { if (filter.test(t)) set.add(t); });
		return set;
	}

	public boolean containsIf(Predicate<? super T> filter) {
		for (T t : this) if (filter.test(t)) return true;
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public EnhancedSet<T> clone() {
		return (EnhancedSet<T>) super.clone();
	}

}


text:
from __future__ import division, unicode_literals

"""
This module implements input and output processing from PWSCF.
"""

__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Virtual Lab"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__date__ = "3/27/15"

import six

from monty.re import regrep
from collections import defaultdict

class PWInput(object):
    """
    Base input file class. Right now, only supports no symmetry and is
    very basic.
    """

    def __init__(self, structure, pseudo, control=None, system=None,
                 electrons=None, ions=None, cell=None, kpoints_mode="automatic",
                 kpoints_grid=(1, 1, 1),kpoints_shift=(0, 0, 0)):
        """
        Initializes a PWSCF input file.

        Args:
            structure (Structure): Input structure
            pseudo (dict): A dict of the pseudopotentials to use.
            control (dict): Control parameters. Refer to official PWSCF doc
                on supported parameters. Default to {"calculation": "scf"}
            system (dict): System parameters. Refer to official PWSCF doc
                on supported parameters. Default to None, which means {}.
            electrons (dict): Electron parameters. Refer to official PWSCF doc
                on supported parameters. Default to None, which means {}.
            ions (dict): Ions parameters. Refer to official PWSCF doc
                on supported parameters. Default to None, which means {}.
            cell (dict): Cell parameters. Refer to official PWSCF doc
                on supported parameters. Default to None, which means {}.
            kpoints_mode (str): Kpoints generation mode. Default to automatic.
            kpoints_grid (sequence): The kpoint grid. Default to (1, 1, 1).
            kpoints_shift (sequence): The shift for the kpoints. Defaults to
                (0, 0, 0).
        """
        self.structure = structure
        sections = {}
        sections["control"] = control or {"calculation": "scf"}
        sections["system"] = system or {}
        sections["electrons"] = electrons or {}
        sections["ions"] = ions or {}
        sections["cell"] = cell or {}
        for species in self.structure.composition.keys():
            if species.symbol not in pseudo:
                raise PWInputError("Missing %s in pseudo specification!")
        self.pseudo = pseudo
        self.sections = sections
        self.kpoints_mode = kpoints_mode
        self.kpoints_grid = kpoints_grid
        self.kpoints_shift = kpoints_shift

    def __str__(self):
        out = []
        def to_str(v):
            if isinstance(v, six.string_types):
                return "'%s'" % v
            return v
        for k1 in ["control", "system", "electrons", "ions", "cell"]:
            v1 = self.sections[k1]
            out.append("&%s" % k1.upper())
            sub = []
            for k2 in sorted(v1.keys()):
                sub.append("  %s = %s" % (k2, to_str(v1[k2])))
            if k1 == "system":
                sub.append("  ibrav = 0")
                sub.append("  nat = %d" % len(self.structure))
                sub.append("  ntyp = %d" % len(self.structure.composition))
            sub.append("/")
            out.append(",\n".join(sub))

        out.append("ATOMIC_SPECIES")
        for k, v in self.structure.composition.items():
            out.append("  %s %.4f %s" % (k.symbol, k.atomic_mass,
                                         self.pseudo[k.symbol]))
        out.append("ATOMIC_POSITIONS crystal")
        for site in self.structure:
            out.append("  %s %.6f %.6f %.6f" % (site.specie.symbol, site.a,
                                                site.b, site.c))
        out.append("K_POINTS %s" % self.kpoints_mode)
        kpt_str = ["%s" % i for i in self.kpoints_grid]
        kpt_str.extend(["%s" % i for i in self.kpoints_shift])
        out.append("  %s" % " ".join(kpt_str))
        out.append("CELL_PARAMETERS angstrom")
        for vec in self.structure.lattice.matrix:
            out.append("  %f %f %f" % (vec[0], vec[1], vec[2]))
        return "\n".join(out)

    def write_file(self, filename):
        """
        Write the PWSCF input file.

        Args:
            filename (str): The string filename to output to.
        """
        with open(filename, "w") as f:
            f.write(self.__str__())

class PWInputError(BaseException):
    pass

class PWOutput(object):

    patterns = {
        "energies": "total energy\s+=\s+([\d\.\-]+)\sRy",
        "ecut": "kinetic\-energy cutoff\s+=\s+([\d\.\-]+)\s+Ry",
        "lattice_type": "bravais\-lattice index\s+=\s+(\d+)",
        "celldm1": "celldm\(1\)=\s+([\d\.]+)\s",
        "celldm2": "celldm\(2\)=\s+([\d\.]+)\s",
        "celldm3": "celldm\(3\)=\s+([\d\.]+)\s",
        "celldm4": "celldm\(4\)=\s+([\d\.]+)\s",
        "celldm5": "celldm\(5\)=\s+([\d\.]+)\s",
        "celldm6": "celldm\(6\)=\s+([\d\.]+)\s",
        "nkpts": "number of k points=\s+([\d]+)"
    }

    def __init__(self, filename):
        self.filename = filename
        self.data = defaultdict(list)
        self.read_pattern(PWOutput.patterns)
        for k, v in self.data.items():
            if k == "energies":
                self.data[k] = [float(i[0][0]) for i in v]
            elif k in ["lattice_type", "nkpts"]:
                self.data[k] = int(v[0][0][0])
            else:
                self.data[k] = float(v[0][0][0])

    def read_pattern(self, patterns, reverse=False,
                     terminate_on_match=False, postprocess=str):
        """
        General pattern reading. Uses monty's regrep method. Takes the same
        arguments.

        Args:
            patterns (dict): A dict of patterns, e.g.,
                {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"}.
            reverse (bool): Read files in reverse. Defaults to false. Useful for
                large files, esp OUTCARs, especially when used with
                terminate_on_match.
            terminate_on_match (bool): Whether to terminate when there is at
                least one match in each key in pattern.
            postprocess (callable): A post processing function to convert all
                matches. Defaults to str, i.e., no change.

        Renders accessible:
            Any attribute in patterns. For example,
            {"energy": "energy\(sigma->0\)\s+=\s+([\d\-\.]+)"} will set the
            value of self.data["energy"] = [[-1234], [-3453], ...], to the
            results from regex and postprocess. Note that the returned
            values are lists of lists, because you can grep multiple
            items on one line.
        """
        matches = regrep(self.filename, patterns, reverse=reverse,
                         terminate_on_match=terminate_on_match,
                         postprocess=postprocess)
        self.data.update(matches)

    def get_celldm(self, i):
        return self.data["celldm%d" % i]

    @property
    def final_energy(self):
        return self.data["energies"][-1]

    @property
    def lattice_type(self):
        return self.data["lattice_type"]

if __name__ == "__main__":
    o = PWOutput("../../test_files/Si.pwscf.out")
    print(o.data)
    print(o.final_energy)


text:
'use strict';

module.exports = function (router) {
  router.get('/', function (req, res) {
    res.render('guide');
  });
};


text:
// ***********************************************************************
// Copyright (c) 2006 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using NUnit.Framework.Interfaces;

namespace NUnit.Framework.Assertions
{
    [TestFixture]
    public class AssertZeroTests
    {
        private readonly int i1 = 0;
        private readonly int i2 = 1234;
        private readonly uint u1 = 0;
        private readonly uint u2 = 12345879;
        private readonly long l1 = 0;
        private readonly long l2 = 12345879;
        private readonly ulong ul1 = 0;
        private readonly ulong ul2 = 12345879;
        private readonly float f1 = 0F;
        private readonly float f2 = 8.543F;
        private readonly decimal de1 = 0M;
        private readonly decimal de2 = 83.4M;
        private readonly double d1 = 0.0;
        private readonly double d2 = 8.0;

        [Test]
        public void ZeroIsZero()
        {
            Assert.Zero(i1);
            Assert.Zero(u1);
            Assert.Zero(l1);
            Assert.Zero(ul1);
            Assert.Zero(f1);
            Assert.Zero(de1);
            Assert.Zero(d1);
        }

        [Test]
        public void AssertZeroFailsWhenNumberIsNotAZero()
        {
            Assert.Throws<AssertionException>(() => Assert.Zero(i2));
            Assert.Throws<AssertionException>(() => Assert.Zero(u2));
            Assert.Throws<AssertionException>(() => Assert.Zero(l2));
            Assert.Throws<AssertionException>(() => Assert.Zero(ul2));
            Assert.Throws<AssertionException>(() => Assert.Zero(f2));
            Assert.Throws<AssertionException>(() => Assert.Zero(de2));
            Assert.Throws<AssertionException>(() => Assert.Zero(d2));
        }

        [Test]
        public void NotZeroIsNotZero()
        {
            Assert.NotZero(i2);
            Assert.NotZero(u2);
            Assert.NotZero(l2);
            Assert.NotZero(ul2);
            Assert.NotZero(f2);
            Assert.NotZero(de2);
            Assert.NotZero(d2);
        }

        [Test]
        public void AssertNotZeroFailsWhenNumberIsZero()
        {
            Assert.Throws<AssertionException>(() => Assert.NotZero(i1));
            Assert.Throws<AssertionException>(() => Assert.NotZero(u1));
            Assert.Throws<AssertionException>(() => Assert.NotZero(l1));
            Assert.Throws<AssertionException>(() => Assert.NotZero(ul1));
            Assert.Throws<AssertionException>(() => Assert.NotZero(f1));
            Assert.Throws<AssertionException>(() => Assert.NotZero(de1));
            Assert.Throws<AssertionException>(() => Assert.NotZero(d1));
        }

        [Test]
        public void ZeroWithMessagesOverload()
        {
            Assert.That(
                () => Assert.Zero(1, "MESSAGE"),
                Throws.TypeOf<AssertionException>().With.Message.Contains("MESSAGE"));
        }

        [Test]
        public void ZeroWithMessageOverloadPasses()
        {
            Assert.Zero(0, "Message");
        }

        [Test]
        public void ExpectedFailureMessageExists()
        {
            var expectedMessage =
                "  Expected: 0" + Environment.NewLine +
                "  But was:  1234" + Environment.NewLine;
            var ex = Assert.Throws<AssertionException>(() => Assert.Zero(i2));
            Assert.That(ex.Message, Is.EqualTo(expectedMessage));
        }
    }
}


text:
package com.github.peejweej.sample;

import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by Fechner on 12/31/14.
 */
public class FileUtil {

    private static final String TAG = "FileLoader";

    //region Out Methods
    /**
     *
     * @param fileSequence
     * @param fileName
     * @param context
     */
    protected static void saveFileToApplicationFiles(Context context, CharSequence fileSequence, String fileName){

        Log.i(TAG, "Attempting to save file named:" + fileName);

        try {
            File file = new File(context.getFilesDir(), fileName);

            if (!file.exists()) {
                boolean success = file.createNewFile();
            }
            String fileString = fileSequence.toString();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileString);
            bw.close();
//            FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
//            outputStream.write(fileString.getBytes());
//            outputStream.close();
        }
        catch (FileNotFoundException e){
            Log.e(TAG, "saveFileToApplicationFiles FileNotFoundException: " + e.toString());
        }
        catch (IOException e){
            Log.e(TAG, "saveFileToApplicationFiles IOException: " + e.toString());
        }

        Log.i(TAG, "File saving was successful.");
    }

    public static void saveFileToSdCard(Context context, byte[] bytes, String fileName){
        String fileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
                + context.getString(R.string.app_name);
        saveFile(bytes, fileDir, fileName);
    }

    public static void saveFileToApplicationFiles(Context context, byte[] bytes, String fileName){
        String fileDir = context.getFilesDir().getAbsolutePath() + "/"
                + context.getString(R.string.app_name);
        saveFile(bytes, fileDir, fileName);
    }

    public static Uri saveFile(byte[] bytes, String dirName, String fileName){

        try{
            File dir = new File(dirName);
            dir.mkdirs();
            File file = new File(dirName, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes);
            fos.close();
            Log.i(TAG, "USFM File Saved");
            return Uri.fromFile(file);
        }
        catch (IOException e){
            e.printStackTrace();
            Log.e(TAG, "Error when saving file");
            return null;
        }
    }

    public static void saveFile(CharSequence fileSequence, String dirName, String fileName){

        Log.i(TAG, "Attempting to save file named:" + fileName);

        try {
            File file = new File(dirName, fileName);

            if (!file.exists()) {
                file.createNewFile();
            }
            String fileString = fileSequence.toString();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileString);
            bw.close();
        }
        catch (FileNotFoundException e){
            Log.e(TAG, "saveFileToApplicationFiles FileNotFoundException: " + e.toString());
        }
        catch (IOException e){
            Log.e(TAG, "saveFileToApplicationFiles IOException: " + e.toString());
        }

        Log.i(TAG, "File saving was successful.");
    }

    /**
     *
     * @param fileSequence
     * @param fileName
     * @param context
     */
    public static void saveFileToSDCard(Context context, CharSequence fileSequence, String fileName){

        Log.i(TAG, "Attempting to save file named:" + fileName);

        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name), fileName);

            if (!file.exists()) {
                boolean madeDirs = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name)).mkdirs();
                boolean madeFile = file.createNewFile();
            }
            String fileString = fileSequence.toString();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileString);
            bw.close();

//            FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
//            outputStream.write(fileString.getBytes());
//            outputStream.close();
        }
        catch (FileNotFoundException e){
            Log.e(TAG, "saveFileToApplicationFiles FileNotFoundException: " + e.toString());
        }
        catch (IOException e){
            Log.e(TAG, "saveFileToApplicationFiles IOException: " + e.toString());
        }

        Log.i(TAG, "File saving was successful.");
    }

    public static Uri createTemporaryFile(Context context, byte[] bytes, String fileName){

        clearTemporaryFiles(context);
        String directory = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/" + context.getString(R.string.app_name) + "/temp";

        return saveFile(bytes, directory, fileName);
    }

    public static Uri createTemporaryFile(Context context, CharSequence fileSequence, String fileName){

        clearTemporaryFiles(context);
//        Log.i(TAG, "Attempting to save temporary file named:" + fileName);

        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/temp", fileName);

            if (!file.exists()) {
                boolean madeDirs = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/temp").mkdirs();
                boolean madeFile = file.createNewFile();
            }
            String fileString = fileSequence.toString();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileString);
            bw.close();
//            Log.i(TAG, "createTemporaryFile saving was successful.");
            return Uri.fromFile(file);

//            FileOutputStream outputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
//            outputStream.write(fileString.getBytes());
//            outputStream.close();
        }
        catch (FileNotFoundException e){
            Log.e(TAG, "createTemporaryFile FileNotFoundException: " + e.toString());
        }
        catch (IOException e){
            Log.e(TAG, "createTemporaryFile IOException: " + e.toString());
        }
        Log.i(TAG, "createTemporaryFile saving was unsuccessful.");
        return null;
    }

    public static void clearTemporaryFiles(Context context){

        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/temp");
        if(file.exists()){
            final File to = new File(file.getAbsolutePath());
            boolean success = file.renameTo(to);
            success = file.delete();
        }
    }

    //endregion

    //region In Method

    /**
     *
     * @param context
     * @param fileName
     * @return
     */
    protected static String getJSONStringFromApplicationFiles(Context context, String fileName){

        if(context == null || fileName == null){
            return null;
        }
        try{

            InputStream fileStream = context.openFileInput(fileName);

            String resultString =  getStringFromInputStream(fileStream, fileName).toString();
            return resultString;
        }
        catch (IOException e){
            Log.e(TAG, "initializeKeyboards IOException: " + e.toString());
            return null;
        }
    }

    /**
     *
     * @param context
     * @param fileName
     * @return
     */
    protected static String getJSONStringFromAssets(Context context, String fileName){

        try{
            InputStream fileStream = context.getAssets().open(fileName);

            String resultString = getStringFromInputStream(fileStream, fileName).toString();
            return resultString;
        }
        catch (IOException e){
            Log.e(TAG, "initializeKeyboards IOException: " + e.toString());
            return null;
        }
    }

    public static String getStringFromFile(File file){

        try{
            FileInputStream fileStream = new FileInputStream(file);

            String resultString = getStringFromInputStream(fileStream, file.getName()).toString();
            return resultString;
        }
        catch (IOException e){
            Log.e(TAG, "initializeKeyboards IOException: " + e.toString());
            return null;
        }
    }

    /**
     *
     * @param fileStream
     * @param fileName
     * @return The String from the Stream or null if there's an error.
     */
    private static CharSequence getStringFromInputStream(InputStream fileStream, String fileName){

        String resultString = "";

        try{

            BufferedReader in = new BufferedReader(new InputStreamReader(fileStream, "utf-8"));
            String str;

            while ((str = in.readLine()) != null) {
                resultString += str;
            }

            in.close();
        }
        catch (FileNotFoundException e){
            Log.e(TAG, "getStringFromInputStream file name: " + fileName + " FileNotFoundException: " + e.toString());
            return null;
        }
        catch (IOException e){
            Log.e(TAG, "getStringFromInputStream file name: " + fileName + " IOException: " + e.toString());
            return null;
        }

        return resultString;
    }

    protected static void deleteFile(Context context, String fileName){

        context.deleteFile(fileName);
    }

    //endregion
}


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.mobility.jsr172">
    <module_version install_time="1360799327123" last="true" origin="installer" specification_version="1.21.1">
        <file crc="1219309950" name="config/Modules/org-netbeans-modules-mobility-jsr172.xml"/>
        <file crc="1882889784" name="modules/locale/org-netbeans-modules-mobility-jsr172_ja.jar"/>
        <file crc="605279931" name="modules/locale/org-netbeans-modules-mobility-jsr172_pt_BR.jar"/>
        <file crc="1559556969" name="modules/locale/org-netbeans-modules-mobility-jsr172_ru.jar"/>
        <file crc="1283845363" name="modules/locale/org-netbeans-modules-mobility-jsr172_zh_CN.jar"/>
        <file crc="1069943824" name="modules/org-netbeans-modules-mobility-jsr172.jar"/>
    </module_version>
</module>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2014-2017 Rudy De Busscher

    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.

-->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
        <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
        <param-value>true</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>


text:
package io.material.catalog.imageview;

import io.material.catalog.R;

import androidx.fragment.app.Fragment;
import dagger.Provides;
import dagger.android.ContributesAndroidInjector;
import dagger.multibindings.IntoSet;
import io.material.catalog.application.scope.ActivityScope;
import io.material.catalog.application.scope.FragmentScope;
import io.material.catalog.feature.Demo;
import io.material.catalog.feature.DemoLandingFragment;
import io.material.catalog.feature.FeatureDemo;

/** A fragment that displays radio button demos for the Catalog app. */
public class ShapeableImageViewFragment extends DemoLandingFragment {

  @Override
  public int getTitleResId() {
    return R.string.cat_imageview_title;
  }

  @Override
  public int getDescriptionResId() {
    return R.string.cat_imageview_description;
  }

  @Override
  public Demo getMainDemo() {
    return new Demo() {
      @Override
      public Fragment createFragment() {
        return new ShapeableImageViewMainDemoFragment();
      }
    };
  }

  /** The Dagger module for {@link ShapeableImageViewFragment} dependencies. */
  @dagger.Module
  public abstract static class Module {

    @FragmentScope
    @ContributesAndroidInjector
    abstract ShapeableImageViewFragment contributeInjector();

    @Provides
    @IntoSet
    @ActivityScope
    static FeatureDemo provideFeatureDemo() {
      return new FeatureDemo(R.string.cat_imageview_title, R.drawable.ic_placeholder) {
        @Override
        public Fragment createFragment() {
          return new ShapeableImageViewFragment();
        }
      };
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="options">Optionen</string>

    <string name="filt_lang">Karten Sprachen</string>
    <string name="filt_lang_desc">Wähle die Sprache, in der die jeweilige Erweiterung angezeigt werden soll.</string>
    <string name="system_default">Standard</string>

    <string name="sort_card">Kartensortierung</string>
    <string name="sort_card_desc">Wie sollen die Karten sortiert werden.</string>
    <string name="drag_handle_desc">Zieh mich!</string>
    <string name="sort_card_end">Alles unterhalb dieser Option wird ignoriert.</string>
    <string-array name="sort_card_names">
        <item>Erweiterung</item>
        <item>Kartenname</item>
        <item>Veröffentlichungsdatum</item>
        <item>Kosten</item>
        <item>Karten-Typ</item>
        <item>Sprache</item>
        <item>Promokarten zuerst</item>
    </string-array>

</resources>


text:
package com.cerner.bunsen.definitions;

import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.RuntimeCompositeDatatypeDefinition;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseExtension;

/**
 * Converter implementation for extension leaf primitives.
 *
 * @param <T> the type of the schema produced by the converter.
 */
public class LeafExtensionConverter<T> extends HapiConverter<T> {

  class LeafExensionFieldSetter implements HapiFieldSetter, HapiObjectConverter {

    private final HapiObjectConverter valuetoHapiConverter;

    private final BaseRuntimeElementCompositeDefinition elementDefinition;

    LeafExensionFieldSetter(BaseRuntimeElementCompositeDefinition elementDefinition,
        HapiObjectConverter valuetoHapiConverter) {

      this.elementDefinition = elementDefinition;
      this.valuetoHapiConverter = valuetoHapiConverter;
    }

    @Override
    public void setField(IBase parentObject,
        BaseRuntimeChildDefinition fieldToSet,
        Object sparkObject) {

      IBase hapiObject = valuetoHapiConverter.toHapi(sparkObject);

      IBaseExtension extension = (IBaseExtension) elementDefinition.newInstance(extensionUrl);

      extension.setValue((IBaseDatatype) hapiObject);

      fieldToSet.getMutator().addValue(parentObject, extension);
    }

    /**
     * Converts an object from a different data model to a HAPI object.
     *
     * @param input the object to convert
     * @return the HAPI equivalent.
     */
    @Override
    public IBase toHapi(Object input) {

      IBase hapiObject = valuetoHapiConverter.toHapi(input);

      IBaseExtension extension = (IBaseExtension) elementDefinition.newInstance(extensionUrl);

      extension.setValue((IBaseDatatype) hapiObject);

      return extension;
    }
  }

  private final String extensionUrl;

  private final HapiConverter<T> valueConverter;

  /**
   * Constructs a converter for the leaf extension.
   *
   * @param extensionUrl the URL of the extension
   * @param valueConverter the converter for the extension's value.
   */
  public LeafExtensionConverter(String extensionUrl, HapiConverter valueConverter) {
    this.extensionUrl = extensionUrl;
    this.valueConverter = valueConverter;
  }

  @Override
  public Object fromHapi(Object input) {

    IBaseExtension extension = (IBaseExtension) input;

    return valueConverter.fromHapi(extension.getValue());
  }

  @Override
  public T getDataType() {
    return valueConverter.getDataType();
  }

  @Override
  public String extensionUrl() {
    return extensionUrl;
  }

  @Override
  public HapiFieldSetter toHapiConverter(BaseRuntimeElementDefinition... elementDefinitions) {

    // Get the structure definition of the value.
    String fieldName = "value" + valueConverter.getElementType();

    RuntimeCompositeDatatypeDefinition definition =
        (RuntimeCompositeDatatypeDefinition) elementDefinitions[0];

    BaseRuntimeElementDefinition valueDefinition = definition.getChildByName(fieldName)
        .getChildByName(fieldName);

    HapiObjectConverter sparkToHapi = (HapiObjectConverter)
        valueConverter.toHapiConverter(valueDefinition);

    return new LeafExensionFieldSetter(definition,  sparkToHapi);
  }
}


text:
import squawk
from datetime import datetime
from squawk.models import TransmissionLog

class DummyGateway(object):
    """ Dummy gateway for testing. """
    def __init__(self):
        self.LAST_MESSAGE = ""
        self.LAST_NOTIFICATION_ID = ""
        self.GATEWAY_MID = '1234A'

    def send(self, txrecords):
        """ Dummy gateway will raise Exception if message is "FAIL MESSAGE" or
return quietly otherwise.
"""
        # txrecords is a list of TransmissionLog IDs
        txrecords = TransmissionLog.objects.filter(pk__in=txrecords)
        message = txrecords[0].message
        notification_id = txrecords[0].notification_id
        self.LAST_MESSAGE = message
        self.LAST_NOTIFICATION_ID = notification_id

        # allows for testing of failed gateway send
        send_ok = False if message == 'FAIL MESSAGE' else True

        for tx in txrecords:
            tx.enqueued = False
            tx.send_ok = send_ok
            tx.gateway_response = self.GATEWAY_MID
            tx.save()

        if not send_ok:
            raise squawk.GatewayFailError("Send failed", notification_id = notification_id)

    def status_callback(self, callback_data):
        """ demo callback handler that is based on Clickatell.
"""
        gateway_id = callback_data.get('apiMsgId')
        status = callback_data.get('status')
        timestamp = callback_data.get('timestamp')
        try:
            charge = callback_data.get('charge', None)
            charge = float(charge) if charge else None
        except ValueError:
            ## @todo - log this!
            charge = None

        status_text = {'001' : 'Message unknown',
                       '002' : 'Message queued',
                       '003' : 'Delivered to gateway',
                       '004' : 'Received by recipient',  ## END OF STORY :)
                       '005' : 'Error with message',
                       '006' : 'User cancelled message delivery',
                       '007' : 'Error delivering message',
                       '008' : 'Message received by gateway',
                       '009' : 'Routing error',
                       '010' : 'Message expired',
                       '011' : 'Message queued',
                       '012' : 'Out of credit',
                       }.get(status, "STATUS UNKNOWN: %s"%status)

        try:
            al = TransmissionLog.objects.get(gateway_response = gateway_id)
            al.gateway_status = status_text
            al.charge = charge
            if status == '004':
                al.delivery_confirmed = True
            al.status_timestamp = datetime.fromtimestamp(float(timestamp))
            al.save()
        except TransmissionLog.DoesNotExist:
            ## @todo - log this!!
            pass


text:
<div class="row" id="trace-container">

  {% include 'trace/time-labels.html' %}

</div>

{% include 'trace/script.html' %}


text:
// <copyright file="FillRegionProcessor.cs" company="James Jackson-South">
// Copyright (c) James Jackson-South and contributors.
// Licensed under the Apache License, Version 2.0.
// </copyright>

namespace ImageSharp.Drawing.Processors
{
    using System;
    using System.Buffers;
    using System.Runtime.CompilerServices;
    using Drawing;

    using ImageSharp.Memory;
    using ImageSharp.PixelFormats;
    using ImageSharp.Processing;
    using SixLabors.Primitives;

    /// <summary>
    /// Usinf a brsuh and a shape fills shape with contents of brush the
    /// </summary>
    /// <typeparam name="TPixel">The type of the color.</typeparam>
    /// <seealso cref="ImageSharp.Processing.ImageProcessor{TPixel}" />
    internal class FillRegionProcessor<TPixel> : ImageProcessor<TPixel>
        where TPixel : struct, IPixel<TPixel>
    {
        private const float AntialiasFactor = 1f;
        private const int DrawPadding = 1;

        /// <summary>
        /// Initializes a new instance of the <see cref="FillRegionProcessor{TPixel}" /> class.
        /// </summary>
        /// <param name="brush">The details how to fill the region of interest.</param>
        /// <param name="region">The region of interest to be filled.</param>
        /// <param name="options">The configuration options.</param>
        public FillRegionProcessor(IBrush<TPixel> brush, Region region, GraphicsOptions options)
        {
            this.Region = region;
            this.Brush = brush;
            this.Options = options;
        }

        /// <summary>
        /// Gets the brush.
        /// </summary>
        public IBrush<TPixel> Brush { get; }

        /// <summary>
        /// Gets the region that this processor applies to.
        /// </summary>
        public Region Region { get; }

        /// <summary>
        /// Gets the options.
        /// </summary>
        /// <value>
        /// The options.
        /// </value>
        public GraphicsOptions Options { get; }

        /// <inheritdoc/>
        protected override void OnApply(ImageBase<TPixel> source, Rectangle sourceRectangle)
        {
            Region region = this.Region;
            Rectangle rect = region.Bounds;

            // Align start/end positions.
            int minX = Math.Max(0, rect.Left);
            int maxX = Math.Min(source.Width, rect.Right);
            int minY = Math.Max(0, rect.Top);
            int maxY = Math.Min(source.Height, rect.Bottom);
            if (minX >= maxX)
            {
                return; // no effect inside image;
            }

            if (minY >= maxY)
            {
                return; // no effect inside image;
            }

            ArrayPool<float> arrayPool = ArrayPool<float>.Shared;

            int maxIntersections = region.MaxIntersections;
            float subpixelCount = 4;
            if (this.Options.Antialias)
            {
                subpixelCount = this.Options.AntialiasSubpixelDepth;
                if (subpixelCount < 4)
                {
                    subpixelCount = 4;
                }
            }

            using (BrushApplicator<TPixel> applicator = this.Brush.CreateApplicator(source, rect, this.Options))
            {
                float[] buffer = arrayPool.Rent(maxIntersections);
                Span<float> bufferSpan = buffer.AsSpan().Slice(0, maxIntersections);
                int scanlineWidth = maxX - minX;
                using (var scanline = new Buffer<float>(scanlineWidth))
                {
                    try
                    {
                        bool scanlineDirty = true;
                        for (int y = minY; y < maxY; y++)
                        {
                            if (scanlineDirty)
                            {
                                // clear the buffer
                                for (int x = 0; x < scanlineWidth; x++)
                                {
                                    scanline[x] = 0;
                                }

                                scanlineDirty = false;
                            }

                            float subpixelFraction = 1f / subpixelCount;
                            float subpixelFractionPoint = subpixelFraction / subpixelCount;
                            for (float subPixel = (float)y; subPixel < y + 1; subPixel += subpixelFraction)
                            {
                                int pointsFound = region.Scan(subPixel, bufferSpan);
                                if (pointsFound == 0)
                                {
                                    // nothing on this line skip
                                    continue;
                                }

                                QuickSort(bufferSpan.Slice(0, pointsFound));

                                for (int point = 0; point < pointsFound; point += 2)
                                {
                                    // points will be paired up
                                    float scanStart = buffer[point] - minX;
                                    float scanEnd = buffer[point + 1] - minX;
                                    int startX = (int)MathF.Floor(scanStart);
                                    int endX = (int)MathF.Floor(scanEnd);

                                    if (startX >= 0 && startX < scanline.Length)
                                    {
                                        for (float x = scanStart; x < startX + 1; x += subpixelFraction)
                                        {
                                            scanline[startX] += subpixelFractionPoint;
                                            scanlineDirty = true;
                                        }
                                    }

                                    if (endX >= 0 && endX < scanline.Length)
                                    {
                                        for (float x = endX; x < scanEnd; x += subpixelFraction)
                                        {
                                            scanline[endX] += subpixelFractionPoint;
                                            scanlineDirty = true;
                                        }
                                    }

                                    int nextX = startX + 1;
                                    endX = Math.Min(endX, scanline.Length); // reduce to end to the right edge
                                    nextX = Math.Max(nextX, 0);
                                    for (int x = nextX; x < endX; x++)
                                    {
                                        scanline[x] += subpixelFraction;
                                        scanlineDirty = true;
                                    }
                                }
                            }

                            if (scanlineDirty)
                            {
                                if (!this.Options.Antialias)
                                {
                                    for (int x = 0; x < scanlineWidth; x++)
                                    {
                                        if (scanline[x] > 0.5)
                                        {
                                            scanline[x] = 1;
                                        }
                                        else
                                        {
                                            scanline[x] = 0;
                                        }
                                    }
                                }

                                applicator.Apply(scanline, minX, y);
                            }
                        }
                    }
                    finally
                    {
                        arrayPool.Return(buffer);
                    }
                }
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void Swap(Span<float> data, int left, int right)
        {
            float tmp = data[left];
            data[left] = data[right];
            data[right] = tmp;
        }

        private static void QuickSort(Span<float> data)
        {
            int hi = Math.Min(data.Length - 1, data.Length - 1);
            QuickSort(data, 0, hi);
        }

        private static void QuickSort(Span<float> data, int lo, int hi)
        {
            if (lo < hi)
            {
                int p = Partition(data, lo, hi);
                QuickSort(data, lo, p);
                QuickSort(data, p + 1, hi);
            }
        }

        private static int Partition(Span<float> data, int lo, int hi)
        {
            float pivot = data[lo];
            int i = lo - 1;
            int j = hi + 1;
            while (true)
            {
                do
                {
                    i = i + 1;
                }
                while (data[i] < pivot && i < hi);

                do
                {
                    j = j - 1;
                }
                while (data[j] > pivot && j > lo);

                if (i >= j)
                {
                    return j;
                }

                Swap(data, i, j);
            }
        }
    }
}


text:
package br.exemplolista;

import java.util.Iterator;

public interface MinhaLista<T> {

	public void adicionar(T item);

	public T getItemNoIndice(int index);

	public T removeItemDoIndice(int index);

	public void insereItemNoIndice(int index, T valor);

	public void mostrarTodosValores();

	public Iterator<T> iterator();

}


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Page\Shop\Order;

use FriendsOfBehat\PageObjectExtension\Page\SymfonyPageInterface;

interface ShowPageInterface extends SymfonyPageInterface
{
    public function hasPayAction(): bool;

    public function pay(): void;

    public function choosePaymentMethod(string $paymentMethodName): void;

    public function getNotifications(): array;

    public function getAmountOfItems(): int;
}


text:
Log Analytics enables you to edit and run log queries on data collected by your resources and analyze their results.

## What does this pack do?

You can use Log Analytics queries to:
- Retrieve records that match particular criteria
- Identify trends
- Analyze patterns
- Provide various insights into your data

To access Azure Log Analytics, you need Cortex XSOAR authorization. For details, see https://xsoar.pan.dev/docs/reference/integrations/azure-log-analytics.

The **Azure Log Analytics - Query From Saved Search** playbook enables you to execute a query from a saved search in Azure Log Analytics.


text:
package com.mq.aliyun.example.producers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.mq.producer.ProducerSerialize;

/**
 * Created by wangziqing on 17/7/25.
 */
public class MyProducerSerialize implements ProducerSerialize {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public byte[] objToBytes(Object object) {
        //do some thine
        try {
            return mapper.writeValueAsBytes(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();

            throw new RuntimeException("序列化失败");
        }

    }
}


text:
                        {{ partial "socialbtns.html" . }}
                    Privacy policy

                    © {{ .Site.Params.copyrightyear }} {{ .Site.Params.author }}

    {{ if .IsPage }} {{ if ( eq .Type "post" ) }}{{ end }}{{ end }}
    {{ if .IsNode }} {{ partial "JS-cardmedia.html" . }} {{ partial "JS-fabbutton.html" . }}{{end}}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace FSWatcher {
    public partial class Form1 : Form {
        private const string m_Dir = @"C:\Temp";
        private FileSystemWatcher m_Watcher;

        public delegate void InvokeDelegate();

        public Form1() {
            InitializeComponent();
            m_Watcher = new FileSystemWatcher(m_Dir);
            m_Watcher.Changed += new FileSystemEventHandler(OnChange);
            m_Watcher.Created += new FileSystemEventHandler(OnChange);
            m_Watcher.Deleted += new FileSystemEventHandler(OnChange);
            m_Watcher.Renamed += new RenamedEventHandler(OnRename);
            //m_Watcher.Renamed += new FileSystemEventHandler(OnChange);
            m_Watcher.EnableRaisingEvents = true;
        }

        void OnRename(object sender, RenamedEventArgs e) {
            Console.WriteLine("{0} was renamed to {1}", e.OldName, e.Name);
        }

        void OnChange(object sender, FileSystemEventArgs e) {
            /*
             * This naive code will blow up because the FSW will be invoking this
             * code from another thread, which means we can't update the UI.
            string[] files = Directory.GetFiles(m_Dir);
            lstFiles.BeginUpdate();
            lstFiles.Items.Clear();
            foreach (string file in files)
                lstFiles.Items.Add(file);
            lstFiles.EndUpdate();
             */

            // This will run it on the GUI's thread.
            if (InvokeRequired) {
                BeginInvoke(new InvokeDelegate(OnChangeInThread));
            }
        }

        private void OnChangeInThread() {
            string[] files = Directory.GetFiles(m_Dir);
            lstFiles.BeginUpdate();
            lstFiles.Items.Clear();
            foreach (string file in files)
                lstFiles.Items.Add(file);
            lstFiles.EndUpdate();
        }
    }
}


text:
package org.apache.spark.sql.hive;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.QueryTest$;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.hive.test.TestHive$;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.apache.spark.sql.SaveMode;
import org.apache.spark.sql.catalyst.TableIdentifier;
import org.apache.spark.util.Utils;

public class JavaMetastoreDataSourcesSuite {
  private transient JavaSparkContext sc;
  private transient SQLContext sqlContext;

  File path;
  Path hiveManagedPath;
  FileSystem fs;
  Dataset<Row> df;

  private static void checkAnswer(Dataset<Row> actual, List<Row> expected) {
    String errorMessage = QueryTest$.MODULE$.checkAnswer(actual, expected);
    if (errorMessage != null) {
      Assert.fail(errorMessage);
    }
  }

  @Before
  public void setUp() throws IOException {
    sqlContext = TestHive$.MODULE$;
    sc = new JavaSparkContext(sqlContext.sparkContext());

    path =
      Utils.createTempDir(System.getProperty("java.io.tmpdir"), "datasource").getCanonicalFile();
    if (path.exists()) {
      path.delete();
    }
    HiveSessionCatalog catalog = (HiveSessionCatalog) sqlContext.sessionState().catalog();
    hiveManagedPath = new Path(
      catalog.hiveDefaultTableFilePath(new TableIdentifier("javaSavedTable")));
    fs = hiveManagedPath.getFileSystem(sc.hadoopConfiguration());
    fs.delete(hiveManagedPath, true);

    List<String> jsonObjects = new ArrayList<>(10);
    for (int i = 0; i < 10; i++) {
      jsonObjects.add("{\"a\":" + i + ", \"b\":\"str" + i + "\"}");
    }
    Dataset<String> ds = sqlContext.createDataset(jsonObjects, Encoders.STRING());
    df = sqlContext.read().json(ds);
    df.createOrReplaceTempView("jsonTable");
  }

  @After
  public void tearDown() throws IOException {
    // Clean up tables.
    if (sqlContext != null) {
      sqlContext.sql("DROP TABLE IF EXISTS javaSavedTable");
      sqlContext.sql("DROP TABLE IF EXISTS externalTable");
    }
  }

  @Test
  public void saveExternalTableAndQueryIt() {
    Map<String, String> options = new HashMap<>();
    options.put("path", path.toString());
    df.write()
      .format("org.apache.spark.sql.json")
      .mode(SaveMode.Append)
      .options(options)
      .saveAsTable("javaSavedTable");

    checkAnswer(
      sqlContext.sql("SELECT * FROM javaSavedTable"),
      df.collectAsList());

    Dataset<Row> loadedDF =
      sqlContext.createExternalTable("externalTable", "org.apache.spark.sql.json", options);

    checkAnswer(loadedDF, df.collectAsList());
    checkAnswer(
      sqlContext.sql("SELECT * FROM externalTable"),
      df.collectAsList());
  }

  @Test
  public void saveExternalTableWithSchemaAndQueryIt() {
    Map<String, String> options = new HashMap<>();
    options.put("path", path.toString());
    df.write()
      .format("org.apache.spark.sql.json")
      .mode(SaveMode.Append)
      .options(options)
      .saveAsTable("javaSavedTable");

    checkAnswer(
      sqlContext.sql("SELECT * FROM javaSavedTable"),
      df.collectAsList());

    List<StructField> fields = new ArrayList<>();
    fields.add(DataTypes.createStructField("b", DataTypes.StringType, true));
    StructType schema = DataTypes.createStructType(fields);
    Dataset<Row> loadedDF =
      sqlContext.createExternalTable("externalTable", "org.apache.spark.sql.json", schema, options);

    checkAnswer(
      loadedDF,
      sqlContext.sql("SELECT b FROM javaSavedTable").collectAsList());
    checkAnswer(
      sqlContext.sql("SELECT * FROM externalTable"),
      sqlContext.sql("SELECT b FROM javaSavedTable").collectAsList());
  }

  @Test
  public void saveTableAndQueryIt() {
    Map<String, String> options = new HashMap<>();
    df.write()
      .format("org.apache.spark.sql.json")
      .mode(SaveMode.Append)
      .options(options)
      .saveAsTable("javaSavedTable");

    checkAnswer(
      sqlContext.sql("SELECT * FROM javaSavedTable"),
      df.collectAsList());
  }
}


text:
__version__ = '1.0.0'

from .algorithms.ICA import ICA
from .algorithms.PCA import PCA
from .algorithms.NMF import NMF
from .algorithms.SVD import SVD


text:
@interface PodsDummy_Pods_LPaimiOSUtils_Tests_Nimble : NSObject
@end
@implementation PodsDummy_Pods_LPaimiOSUtils_Tests_Nimble
@end


text:
'use strict';

ApplicationConfiguration.registerModule('project', ['core']);


text:
<!doctype html>

    <meta charset="utf-8">
    <title>IcoMoon Demo</title>
    <meta name="description" content="An Icon Font Generated By IcoMoon.io">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="demo-files/demo.css">
    <link rel="stylesheet" href="style.css">

Font Name: icomoon (Glyphs: 11)

Grid Size: Unknown

                 icon-api

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e600" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-btc-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e601" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-coin

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e602" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-docs

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e603" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-double-arrow-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e604" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-github

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e605" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-keyring-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e606" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-lab-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e607" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-public-key-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e608" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-qr-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e609" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

                 icon-bitauth-solid

            <fieldset class="fs0 size1of1 clearfix hidden-false">
                <input type="text" readonly value="e900" class="unit size1of2" />
                <input type="text" maxlength="1" readonly value="" class="unitRight size1of2 talign-right" />
            </fieldset>

                liga:
                <input type="text" readonly value="" class="liga unitRight" />

Font Test Drive

            Font Size: <input id="fontSize" type="number" class="textbox0 mbm"
            min="8" value="48" />
            px

        <input id="testText" type="text" class="phl size1of1 mvl"
        placeholder="Type some text to test..." value=""/>

Generated by IcoMoon


text:
package cn.howardliu.gear.spring.boot.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration;
import org.springframework.boot.info.BuildProperties;
import org.springframework.boot.info.GitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <br>created at 2019/11/26
 *
 * @author liuxh
 * @since 1.0.0
 */
@Configuration
@AutoConfigureAfter(ProjectInfoAutoConfiguration.class)
@ConditionalOnClass({
        MeterRegistry.class,
        MeterRegistryCustomizer.class
})
@ConditionalOnProperty({
        "spring.cloud.client.ip-address"
})
public class MicrometerAutoConfiguration {
    @Bean
    @ConditionalOnBean({
            BuildProperties.class,
            GitProperties.class
    })
    public MeterRegistryCustomizer<MeterRegistry> registerCommonTagsWithGitInfoAndBuildInfo(@Value("${spring.application.name:wm-app-v1}") String applicationName,
                                                                                @Value("${spring.cloud.client.ip-address}") String ipAddress,
                                                                                @Value("${server.port}") String serverPort,
                                                                                BuildProperties buildProperties,
                                                                                GitProperties gitProperties) {
        return registry -> registry.config()
                .commonTags(
                        "application", applicationName,
                        "instance", ipAddress + ":" + serverPort,
                        "build.group", buildProperties.getGroup(),
                        "build.artifact", buildProperties.getArtifact(),
                        "git.branch", gitProperties.getBranch(),
                        "git.commit.id", gitProperties.getCommitId()
                );
    }

    @Bean
    @ConditionalOnBean(BuildProperties.class)
    @ConditionalOnMissingBean(GitProperties.class)
    public MeterRegistryCustomizer<MeterRegistry> registerCommonTagsWithBuildInfo(@Value("${spring.application.name:wm-app-v1}") String applicationName,
                                                                                @Value("${spring.cloud.client.ip-address}") String ipAddress,
                                                                                @Value("${server.port}") String serverPort,
                                                                                BuildProperties buildProperties) {
        return registry -> registry.config()
                .commonTags(
                        "application", applicationName,
                        "instance", ipAddress + ":" + serverPort,
                        "build.group", buildProperties.getGroup(),
                        "build.artifact", buildProperties.getArtifact()
                );
    }

    @Bean
    @ConditionalOnBean(GitProperties.class)
    @ConditionalOnMissingBean(BuildProperties.class)
    public MeterRegistryCustomizer<MeterRegistry> registerCommonTagsWithGitInfo(@Value("${spring.application.name:wm-app-v1}") String applicationName,
                                                                                @Value("${spring.cloud.client.ip-address}") String ipAddress,
                                                                                @Value("${server.port}") String serverPort,
                                                                                GitProperties gitProperties) {
        return registry -> registry.config()
                .commonTags(
                        "application", applicationName,
                        "instance", ipAddress + ":" + serverPort,
                        "git.branch", gitProperties.getBranch(),
                        "git.commit.id", gitProperties.getCommitId()
                );
    }

    @Bean
    @ConditionalOnMissingBean({
            BuildProperties.class,
            GitProperties.class
    })
    public MeterRegistryCustomizer<MeterRegistry> registerCommonTags(@Value("${spring.application.name:wm-app-v1}") String applicationName,
                                                                     @Value("${spring.cloud.client.ip-address}") String ipAddress,
                                                                     @Value("${server.port}") String serverPort) {
        return registry -> registry.config()
                .commonTags(
                        "application", applicationName,
                        "instance", ipAddress + ":" + serverPort
                );
    }
}


text:
package org.springframework.security.provisioning;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.fest.assertions.Assertions.assertThat;

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

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.PopulatedDatabase;
import org.springframework.security.TestDataSource;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Tests for {@link JdbcUserDetailsManager}
 *
 * @author Luke Taylor
 */
public class JdbcUserDetailsManagerTests {
	private static final String SELECT_JOE_SQL = "select * from users where username = 'joe'";
	private static final String SELECT_JOE_AUTHORITIES_SQL = "select * from authorities where username = 'joe'";

	private static final UserDetails joe = new User("joe", "password", true, true, true,
			true, AuthorityUtils.createAuthorityList("A", "C", "B"));

	private static TestDataSource dataSource;
	private JdbcUserDetailsManager manager;
	private MockUserCache cache;
	private JdbcTemplate template;

	@BeforeClass
	public static void createDataSource() {
		dataSource = new TestDataSource("jdbcusermgrtest");
	}

	@AfterClass
	public static void clearDataSource() throws Exception {
		dataSource.destroy();
		dataSource = null;
	}

	@Before
	public void initializeManagerAndCreateTables() {
		manager = new JdbcUserDetailsManager();
		cache = new MockUserCache();
		manager.setUserCache(cache);
		manager.setDataSource(dataSource);
		manager.setCreateUserSql(JdbcUserDetailsManager.DEF_CREATE_USER_SQL);
		manager.setUpdateUserSql(JdbcUserDetailsManager.DEF_UPDATE_USER_SQL);
		manager.setUserExistsSql(JdbcUserDetailsManager.DEF_USER_EXISTS_SQL);
		manager.setCreateAuthoritySql(JdbcUserDetailsManager.DEF_INSERT_AUTHORITY_SQL);
		manager.setDeleteUserAuthoritiesSql(JdbcUserDetailsManager.DEF_DELETE_USER_AUTHORITIES_SQL);
		manager.setDeleteUserSql(JdbcUserDetailsManager.DEF_DELETE_USER_SQL);
		manager.setChangePasswordSql(JdbcUserDetailsManager.DEF_CHANGE_PASSWORD_SQL);
		manager.initDao();
		template = manager.getJdbcTemplate();

		template.execute("create table users(username varchar(20) not null primary key,"
				+ "password varchar(20) not null, enabled boolean not null)");
		template.execute("create table authorities (username varchar(20) not null, authority varchar(20) not null, "
				+ "constraint fk_authorities_users foreign key(username) references users(username))");
		PopulatedDatabase.createGroupTables(template);
		PopulatedDatabase.insertGroupData(template);
	}

	@After
	public void dropTablesAndClearContext() {
		template.execute("drop table authorities");
		template.execute("drop table users");
		template.execute("drop table group_authorities");
		template.execute("drop table group_members");
		template.execute("drop table groups");
		SecurityContextHolder.clearContext();
	}

	@Test
	public void createUserInsertsCorrectData() {
		manager.createUser(joe);

		UserDetails joe2 = manager.loadUserByUsername("joe");

		assertEquals(joe, joe2);
	}

	@Test
	public void deleteUserRemovesUserDataAndAuthoritiesAndClearsCache() {
		insertJoe();
		manager.deleteUser("joe");

		assertEquals(0, template.queryForList(SELECT_JOE_SQL).size());
		assertEquals(0, template.queryForList(SELECT_JOE_AUTHORITIES_SQL).size());
		assertFalse(cache.getUserMap().containsKey("joe"));
	}

	@Test
	public void updateUserChangesDataCorrectlyAndClearsCache() {
		insertJoe();
		User newJoe = new User("joe", "newpassword", false, true, true, true,
				AuthorityUtils.createAuthorityList(new String[] { "D", "F", "E" }));

		manager.updateUser(newJoe);

		UserDetails joe = manager.loadUserByUsername("joe");

		assertEquals(newJoe, joe);
		assertFalse(cache.getUserMap().containsKey("joe"));
	}

	@Test
	public void userExistsReturnsFalseForNonExistentUsername() {
		assertFalse(manager.userExists("joe"));
	}

	@Test
	public void userExistsReturnsTrueForExistingUsername() {
		insertJoe();
		assertTrue(manager.userExists("joe"));
		assertTrue(cache.getUserMap().containsKey("joe"));
	}

	@Test(expected = AccessDeniedException.class)
	public void changePasswordFailsForUnauthenticatedUser() {
		manager.changePassword("password", "newPassword");
	}

	@Test
	public void changePasswordSucceedsWithAuthenticatedUserAndNoAuthenticationManagerSet() {
		insertJoe();
		authenticateJoe();
		manager.changePassword("wrongpassword", "newPassword");
		UserDetails newJoe = manager.loadUserByUsername("joe");

		assertEquals("newPassword", newJoe.getPassword());
		assertFalse(cache.getUserMap().containsKey("joe"));
	}

	@Test
	public void changePasswordSucceedsWithIfReAuthenticationSucceeds() {
		insertJoe();
		Authentication currentAuth = authenticateJoe();
		AuthenticationManager am = mock(AuthenticationManager.class);
		when(am.authenticate(currentAuth)).thenReturn(currentAuth);

		manager.setAuthenticationManager(am);
		manager.changePassword("password", "newPassword");
		UserDetails newJoe = manager.loadUserByUsername("joe");

		assertEquals("newPassword", newJoe.getPassword());
		// The password in the context should also be altered
		Authentication newAuth = SecurityContextHolder.getContext().getAuthentication();
		assertEquals("joe", newAuth.getName());
		assertEquals(currentAuth.getDetails(), newAuth.getDetails());
		assertThat(newAuth.getCredentials()).isNull();
		assertFalse(cache.getUserMap().containsKey("joe"));
	}

	@Test
	public void changePasswordFailsIfReAuthenticationFails() {
		insertJoe();
		authenticateJoe();
		AuthenticationManager am = mock(AuthenticationManager.class);
		when(am.authenticate(any(Authentication.class))).thenThrow(
				new BadCredentialsException(""));

		manager.setAuthenticationManager(am);

		try {
			manager.changePassword("password", "newPassword");
			fail("Expected BadCredentialsException");
		}
		catch (BadCredentialsException expected) {
		}

		// Check password hasn't changed.
		UserDetails newJoe = manager.loadUserByUsername("joe");
		assertEquals("password", newJoe.getPassword());
		assertEquals("password", SecurityContextHolder.getContext().getAuthentication()
				.getCredentials());
		assertTrue(cache.getUserMap().containsKey("joe"));
	}

	@Test
	public void findAllGroupsReturnsExpectedGroupNames() {
		List<String> groups = manager.findAllGroups();
		assertEquals(4, groups.size());

		Collections.sort(groups);
		assertEquals("GROUP_0", groups.get(0));
		assertEquals("GROUP_1", groups.get(1));
		assertEquals("GROUP_2", groups.get(2));
		assertEquals("GROUP_3", groups.get(3));
	}

	@Test
	public void findGroupMembersReturnsCorrectData() {
		List<String> groupMembers = manager.findUsersInGroup("GROUP_0");
		assertEquals(1, groupMembers.size());
		assertEquals("jerry", groupMembers.get(0));
		groupMembers = manager.findUsersInGroup("GROUP_1");
		assertEquals(2, groupMembers.size());
	}

	@Test
	@SuppressWarnings("unchecked")
	public void createGroupInsertsCorrectData() {
		manager.createGroup("TEST_GROUP",
				AuthorityUtils.createAuthorityList("ROLE_X", "ROLE_Y"));

		List roles = template
				.queryForList("select ga.authority from groups g, group_authorities ga "
						+ "where ga.group_id = g.id " + "and g.group_name = 'TEST_GROUP'");

		assertEquals(2, roles.size());
	}

	@Test
	public void deleteGroupRemovesData() throws Exception {
		manager.deleteGroup("GROUP_0");
		manager.deleteGroup("GROUP_1");
		manager.deleteGroup("GROUP_2");
		manager.deleteGroup("GROUP_3");

		assertEquals(0, template.queryForList("select * from group_authorities").size());
		assertEquals(0, template.queryForList("select * from group_members").size());
		assertEquals(0, template.queryForList("select id from groups").size());
	}

	@Test
	public void renameGroupIsSuccessful() throws Exception {
		manager.renameGroup("GROUP_0", "GROUP_X");

		assertEquals(
				0,
				(int) template.queryForObject("select id from groups where group_name = 'GROUP_X'",
						Integer.class));
	}

	@Test
	public void addingGroupUserSetsCorrectData() throws Exception {
		manager.addUserToGroup("tom", "GROUP_0");

		assertEquals(
				2,
				template.queryForList(
						"select username from group_members where group_id = 0").size());
	}

	@Test
	public void removeUserFromGroupDeletesGroupMemberRow() throws Exception {
		manager.removeUserFromGroup("jerry", "GROUP_1");

		assertEquals(
				1,
				template.queryForList(
						"select group_id from group_members where username = 'jerry'")
						.size());
	}

	@Test
	public void findGroupAuthoritiesReturnsCorrectAuthorities() throws Exception {
		assertEquals(AuthorityUtils.createAuthorityList("ROLE_A"),
				manager.findGroupAuthorities("GROUP_0"));
	}

	@Test
	public void addGroupAuthorityInsertsCorrectGroupAuthorityRow() throws Exception {
		GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_X");
		manager.addGroupAuthority("GROUP_0", auth);

		template.queryForObject(
				"select authority from group_authorities where authority = 'ROLE_X' and group_id = 0",
				String.class);
	}

	@Test
	public void deleteGroupAuthorityRemovesCorrectRows() throws Exception {
		GrantedAuthority auth = new SimpleGrantedAuthority("ROLE_A");
		manager.removeGroupAuthority("GROUP_0", auth);
		assertEquals(
				0,
				template.queryForList(
						"select authority from group_authorities where group_id = 0")
						.size());

		manager.removeGroupAuthority("GROUP_2", auth);
		assertEquals(
				2,
				template.queryForList(
						"select authority from group_authorities where group_id = 2")
						.size());
	}

	// SEC-1156
	@Test
	public void createUserDoesNotSaveAuthoritiesIfEnableAuthoritiesIsFalse()
			throws Exception {
		manager.setEnableAuthorities(false);
		manager.createUser(joe);
		assertEquals(0, template.queryForList(SELECT_JOE_AUTHORITIES_SQL).size());
	}

	// SEC-1156
	@Test
	public void updateUserDoesNotSaveAuthoritiesIfEnableAuthoritiesIsFalse()
			throws Exception {
		manager.setEnableAuthorities(false);
		insertJoe();
		template.execute("delete from authorities where username='joe'");
		manager.updateUser(joe);
		assertEquals(0, template.queryForList(SELECT_JOE_AUTHORITIES_SQL).size());
	}

	// SEC-2166
	@Test
	public void createNewAuthenticationUsesNullPasswordToKeepPassordsSave() {
		insertJoe();
		UsernamePasswordAuthenticationToken currentAuth = new UsernamePasswordAuthenticationToken(
				"joe", null, AuthorityUtils.createAuthorityList("ROLE_USER"));
		Authentication updatedAuth = manager.createNewAuthentication(currentAuth, "new");
		assertThat(updatedAuth.getCredentials()).isNull();
	}

	private Authentication authenticateJoe() {
		UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
				"joe", "password", joe.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(auth);

		return auth;
	}

	private void insertJoe() {
		template.execute("insert into users (username, password, enabled) values ('joe','password','true')");
		template.execute("insert into authorities (username, authority) values ('joe','A')");
		template.execute("insert into authorities (username, authority) values ('joe','B')");
		template.execute("insert into authorities (username, authority) values ('joe','C')");
		cache.putUserInCache(joe);
	}

	private class MockUserCache implements UserCache {
		private Map<String, UserDetails> cache = new HashMap<String, UserDetails>();

		public UserDetails getUserFromCache(String username) {
			return (User) cache.get(username);
		}

		public void putUserInCache(UserDetails user) {
			cache.put(user.getUsername(), user);
		}

		public void removeUserFromCache(String username) {
			cache.remove(username);
		}

		Map<String, UserDetails> getUserMap() {
			return cache;
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="zend.config.adapters.ini"><info><title>Zend_Config_Ini</title></info>

    <para>
        <classname>Zend_Config_Ini</classname> permet aux développeurs de stocker des données de
        configuration dans le format familier d'un fichier <acronym>INI</acronym> et de les lire
        dans l'application en employant une syntaxe de propriétés d'objet imbriquées. Le format
        <acronym>INI</acronym> est spécialisé pour fournir à la fois la capacité d'avoir une
        hiérarchie des données de configuration et permettre l'héritage entre les sections de
        données de configuration. La hiérarchie des données de configuration est supportée grâce
        au fractionnement des clés à l'aide de points (<emphasis>.</emphasis>). Une section peut
        être étendue ou héritée d'une autre section en suivant le nom de section avec le caractère
        de deux points (<emphasis>:</emphasis>) et le nom de la section de laquelle des données
        doivent être héritées.
    </para>

    <note><info><title>Analyse d'un fichier INI</title></info>

        <para>
            <classname>Zend_Config_Ini</classname> utilise la fonction
            <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://fr.php.net/parse_ini_file"><methodname>parse_ini_file()</methodname></link>
            de <acronym>PHP</acronym>. Veuillez prendre connaissance de la documentation pour
            appréhender ses comportements spécifiques, qui se propagent à
            <classname>Zend_Config_Ini</classname>, tel que la façon dont les valeurs
            spéciales : <constant>TRUE</constant>, <constant>FALSE</constant>,
            "yes", "no" et <constant>NULL</constant> sont manipulées.
        </para>
    </note>

    <note><info><title>Séparateur de clé</title></info>

        <para>
            Par défaut, le séparateur de clé est le caractère point (<emphasis>.</emphasis>),
            cependant cela peut être changé en changeant la clé <property>nestSeparator</property>
            de <varname>$options</varname>
            en construisant l'objet
            <classname>Zend_Config_Ini</classname>. Par exemple :
        </para>

        <programlisting language="php"><![CDATA[
$options['nestSeparator'] = ':';
$options = new Zend_Config_Ini('/chemin/vers/config.ini',
                               'test',
                               $options);
]]></programlisting>
    </note>

    <example xml:id="zend.config.adapters.ini.example.using"><info><title>Utiliser Zend_Config_Ini</title></info>

        <para>
            Cet exemple illustre une utilisation de base de <classname>Zend_Config_Ini</classname>
            pour le chargement des données de configuration à partir d'un fichier
            <acronym>INI</acronym>. Dans cet
            exemple il y a des données de configuration pour un environnement de production et pour
            un environnement de test. Puisque les données de configuration de l'environnement de
            test sont très semblables à celles de la production, la section de test hérite de la
            section de production. Dans ce cas, la décision est arbitraire et pourrait avoir été
            écrite réciproquement, avec la section de production héritant de la section de test,
            bien que ceci ne doit pas être le cas pour des situations plus complexes. Supposons,
            que les données suivantes de configuration sont contenues dans
            <filename>/chemin/vers/config.ini</filename> :
        </para>

        <programlisting language="ini"><![CDATA[
; Données de configuration du site de production
[production]
webhost                  = www.example.com
database.adapter         = pdo_mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; Données de configuration du site de test héritant du site
; de production et surchargeant les clés nécessaires
[test : production]
database.params.host     = dev.example.com
database.params.username = devuser
database.params.password = devsecret
]]></programlisting>

        <para>
            Ensuite, supposons que le développeur ait besoin des données de configuration de
            test issues du fichier <acronym>INI</acronym>. Il est facile de charger ces données
            en indiquant le fichier <acronym>INI</acronym> et la section de test :
        </para>

        <programlisting language="php"><![CDATA[
$config = new Zend_Config_Ini('/chemin/vers/config.ini', 'test');

echo $config->database->params->host;   // affiche "dev.example.com"
echo $config->database->params->dbname; // affiche "dbname"
]]></programlisting>
    </example>

    <note>
        <table xml:id="zend.config.adapters.ini.table"><info><title>Paramètres du constructeur de Zend_Config_Ini</title></info>

            <tgroup cols="2">
                <thead>
                    <row>
                        <entry>Paramètres</entry>
                        <entry>Notes</entry>
                    </row>
                </thead>
                <tbody>
                    <row>
                        <entry><varname>$filename</varname></entry>
                        <entry>Le fichier <acronym>INI</acronym> à charger.</entry>
                    </row>
                    <row>
                        <entry><varname>$section</varname></entry>
                        <entry>
                            La [section] dans le fichier <acronym>INI</acronym> qui doit être
                            chargé. L'affectation de <constant>NULL</constant> à ce paramètre
                            chargera toutes les sections. Alternativement, un tableau de noms
                            de section peut être fourni pour charger des sections multiples.
                        </entry>
                    </row>
                    <row>
                        <entry>
                            <varname>$options</varname> (par défault <constant>FALSE</constant>)
                        </entry>
                        <entry>
                            Tableau d'options. Les clés suivantes sont supportées :
                            <itemizedlist>
                                <listitem>
                                    <para>
                                        <emphasis><property>allowModifications</property></emphasis> :
                                        Mettre à <constant>TRUE</constant> pour permettre la
                                        modification en mémoire des données de configuration
                                        chargées. Par défaut à <constant>FALSE</constant>.
                                    </para>
                                </listitem>
                                <listitem>
                                    <para>
                                        <emphasis><property>nestSeparator</property></emphasis> :
                                        Caractère à utiliser en tant que séparateur d'imbrication.
                                        Par défaut ".".
                                    </para>
                                </listitem>
                            </itemizedlist>
                        </entry>
                    </row>
                </tbody>
            </tgroup>
        </table>
    </note>
</section>


text:
/**
 * This package contains several convenient implementations of the {@link org.easybatch.core.api.Record} interface.
 */
package org.easybatch.core.record;


text:
main :: IO ()
main = putStrLn "Not yet"


text:
namespace {
const int kMinPort = 1024;
const int kMaxPort = 65535;
}  // namespace

namespace common {

MainRunner::MainRunner() {
}

MainRunner::~MainRunner() {
}

bool MainRunner::InitFromManifest(const std::string& input_file,
                                  std::string* error) {
  BuildConfig config;
  ninja_main_.reset(new ninja::NinjaMain(config));
  return ninja_main_->InitFromManifest(input_file, error, true);
}

void MainRunner::CreateThreads() {
  main_thread_.reset(
      new NinjaThreadImpl(NinjaThread::MAIN, base::MessageLoop::current()));
  rpc_thread_.reset(new NinjaThreadImpl(NinjaThread::RPC));
  file_thread_.reset(new NinjaThreadImpl(NinjaThread::FILE));
}

void MainRunner::Run() {
  base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
  rpc_thread_->StartWithOptions(options);
  file_thread_->Start();
  base::RunLoop run_loop;
  run_loop.Run();
}

void MainRunner::Shutdown() {
  file_thread_.reset();
  rpc_thread_.reset();
  NinjaThread::ShutdownThreadPool();
}

// static
MainRunner* MainRunner::Create() {
  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();

  uint32 port = rpc::kDefaultPort;
  if (command_line->HasSwitch(switches::kPort)) {
    std::string port_str = command_line->GetSwitchValueASCII(switches::kPort);
    DCHECK(!port_str.empty());
    base::StringToUint(port_str, &port);
    CHECK(port >= kMinPort && port <= kMaxPort)
        << "Port should be in range [" << kMinPort << ", " << kMaxPort << "].";
  }

  // Setup whether we are running as master or slave.
  if (command_line->HasSwitch(switches::kMaster)) {
    LOG(INFO) << "Running as slave.";
    std::string master = command_line->GetSwitchValueASCII(switches::kMaster);
    DCHECK(!master.empty());
    return new slave::SlaveMainRunner(master, port);
  } else {
    LOG(INFO) << "Running as master.";
    std::string bind_ip = rpc::kDefaultBindIP;
    if (command_line->HasSwitch(switches::kBindIP)) {
      bind_ip = command_line->GetSwitchValueASCII(switches::kBindIP);
      DCHECK(!bind_ip.empty());
    }
    return new master::MasterMainRunner(bind_ip, port);
  }
}

ninja::NinjaMain* MainRunner::ninja_main() {
  return ninja_main_.get();
}

}  // namespace common


text:
<?php

namespace Greg;

class ProductIdentifier
{
    /**
     * @var string
     */
    private $organization;

    /**
     * @var string
     */
    private $product;

    /**
     * ISO 639-1 language code in lower-case format.
     *
     * @var string
     */
    private $language;

    /**
     * @param string $organization
     * @param string $product
     * @param string $language
     */
    public function __construct($organization, $product, $language)
    {
        if (2 !== strlen($language)) {
            throw new \InvalidArgumentException('Language code must conform to the ISO 639-1 standard.');
        }

        $this->organization = $organization;
        $this->product = $product;
        $this->language = strtolower($language);
    }

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

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

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


text:
// Require dependencies
import trim from 'lodash/trim';

/**
 * @type {RegExp} - Kebab RegEx
 */
const KEBAB_REGEX = /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g;

/**
 * String to-kebab-case
 *
 * @param {string} str - string
 * @return {string} - kebab-case string
 */
export default function toKebabCase(str) {
    return trim(str.replace(KEBAB_REGEX, match => `-${match.toLowerCase()}`), '-');
}


text:
<template>
  <textarea rows='1' class="tree-title" id="title" value.bind="title" keydown.delegate="onTitleKeyDown($event)" keyup.delegate="onTitleKeyUp($event)"></textarea>
  <div keydown.delegate="onKeyDown($event)">
    <div repeat.for="child of node.children">
      <compose
        model.bind="{'node_id':child, 'parentVM':$parent}"
        view-model="tree-node">
      </compose>
    </div>
  </div>
</template>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.billing.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.billing.fluent.models.InvoiceSectionWithCreateSubPermissionInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** The list of invoice section properties with create subscription permission. */
@Fluent
public final class InvoiceSectionListWithCreateSubPermissionResult {
    @JsonIgnore
    private final ClientLogger logger = new ClientLogger(InvoiceSectionListWithCreateSubPermissionResult.class);

    /*
     * The list of invoice section properties with create subscription
     * permission.
     */
    @JsonProperty(value = "value")
    private List<InvoiceSectionWithCreateSubPermissionInner> value;

    /*
     * The link (url) to the next page of results.
     */
    @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY)
    private String nextLink;

    /**
     * Get the value property: The list of invoice section properties with create subscription permission.
     *
     * @return the value value.
     */
    public List<InvoiceSectionWithCreateSubPermissionInner> value() {
        return this.value;
    }

    /**
     * Set the value property: The list of invoice section properties with create subscription permission.
     *
     * @param value the value value to set.
     * @return the InvoiceSectionListWithCreateSubPermissionResult object itself.
     */
    public InvoiceSectionListWithCreateSubPermissionResult withValue(
        List<InvoiceSectionWithCreateSubPermissionInner> value) {
        this.value = value;
        return this;
    }

    /**
     * Get the nextLink property: The link (url) to the next page of results.
     *
     * @return the nextLink value.
     */
    public String nextLink() {
        return this.nextLink;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (value() != null) {
            value().forEach(e -> e.validate());
        }
    }
}


text:
        {{ profileInfo.name }}
        {{ profileInfo.email }}