# frozen_string_literal: true

RubyNext::Core.patch Symbol, method: :end_with?, version: "2.7" do
  <<-RUBY
def end_with?(*prefixes)
  to_s.end_with?(*prefixes)
end
  RUBY
end

{'repo_name': 'ruby-next/ruby-next', 'stars': '350', 'repo_language': 'Ruby', 'file_name': 'tally.rb', 'mime_type': 'text/x-ruby', 'hash': 2920119142845785945, 'source_dataset': 'data'}


/***********************************************************************
    PEGASUS: Peta-Scale Graph Mining System
    Authors: U Kang, Duen Horng Chau, and Christos Faloutsos

This software is licensed under 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.
-------------------------------------------------------------------------
File: PageRankNaive.java
 - PageRank using plain matrix-vector multiplication.
Version: 2.0
***********************************************************************/

package pegasus;

import java.io.*;
import java.util.*;
import java.text.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.util.*;

class MinMaxInfo
{
	public double min;
	public double max;
};

public class PagerankNaive extends Configured implements Tool
{
    protected static enum PrCounters { CONVERGE_CHECK }
	protected static double converge_threshold = 0.000001;

    //////////////////////////////////////////////////////////////////////
    // STAGE 1: Generate partial matrix-vector multiplication results.
	//          Perform hash join using Vector.rowid == Matrix.colid.
	//  - Input: edge_file, pagerank vector
	//  - Output: partial matrix-vector multiplication results.
    //////////////////////////////////////////////////////////////////////
	public static class MapStage1 extends MapReduceBase	implements Mapper<LongWritable, Text, IntWritable, Text>
    {
		int make_symmetric = 0;

		public void configure(JobConf job) {
			make_symmetric = Integer.parseInt(job.get("make_symmetric"));

			System.out.println("MapStage1 : make_symmetric = " + make_symmetric);
		}

		public void map (final LongWritable key, final Text value, final OutputCollector<IntWritable, Text> output, final Reporter reporter) throws IOException
		{
			String line_text = value.toString();
			if (line_text.startsWith("#"))				// ignore comments in edge file
				return;

			final String[] line = line_text.split("\t");
			if(line.length < 2 )
				return;

			if( line[1].charAt(0) == 'v' ) {	// vector : ROWID	VALUE('vNNNN')
				output.collect( new IntWritable(Integer.parseInt(line[0])), new Text(line[1]) );
			} else {
				// In other matrix-vector multiplication, we output (dst, src) here
				// However, In PageRank, the matrix-vector computation formula is M^T * v.
				// Therefore, we output (src,dst) here.
				int src_id = Integer.parseInt(line[0]);
				int dst_id = Integer.parseInt(line[1]);
				output.collect( new IntWritable( src_id ), new Text(line[1]) );

				if( make_symmetric == 1 )
					output.collect( new IntWritable( dst_id ), new Text(line[0]) );
			}
		}
	}

    public static class RedStage1 extends MapReduceBase	implements Reducer<IntWritable, Text, IntWritable, Text>
    {
		int number_nodes = 0;
		double mixing_c = 0;
		double random_coeff = 0;

		public void configure(JobConf job) {
			number_nodes = Integer.parseInt(job.get("number_nodes"));
			mixing_c = Double.parseDouble(job.get("mixing_c"));
			random_coeff = (1-mixing_c) / (double)number_nodes;

			System.out.println("RedStage1: number_nodes = " + number_nodes + ", mixing_c = " + mixing_c + ", random_coeff = " + random_coeff);
		}

		public void reduce (final IntWritable key, final Iterator<Text> values, final OutputCollector<IntWritable, Text> output, final Reporter reporter) throws IOException
        {
			int i;
			double cur_rank = 0;

		    ArrayList<Integer> dst_nodes_list = new ArrayList<Integer>();

			while (values.hasNext()) {
				String line_text = values.next().toString();
				final String[] line = line_text.split("\t");

				if( line.length == 1 ) {
					if(line_text.charAt(0) == 'v')	// vector : VALUE
						cur_rank = Double.parseDouble(line_text.substring(1));
					else {							// edge : ROWID
						dst_nodes_list.add( Integer.parseInt( line[0] ) );
					}
				}
			}

			// add random coeff
			output.collect(key, new Text( "s" + cur_rank ));

			int outdeg = dst_nodes_list.size();
			if( outdeg > 0 )
				cur_rank = cur_rank / (double)outdeg;

			for( i = 0; i < outdeg; i++) {
				output.collect( new IntWritable( dst_nodes_list.get(i) ), new Text( "v" + cur_rank ) );
			}
		}
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // STAGE 2: merge multiplication results.
	//  - Input: partial multiplication results
	//  - Output: combined multiplication results
    ////////////////////////////////////////////////////////////////////////////////////////////////
	public static class MapStage2 extends MapReduceBase	implements Mapper<LongWritable, Text, IntWritable, Text>
    {
		// Identity mapper
		public void map (final LongWritable key, final Text value, final OutputCollector<IntWritable, Text> output, final Reporter reporter) throws IOException
		{
			final String[] line = value.toString().split("\t");

			output.collect(new IntWritable(Integer.parseInt(line[0])), new Text(line[1]) );
		}
	}

    public static class RedStage2 extends MapReduceBase	implements Reducer<IntWritable, Text, IntWritable, Text>
    {
		int number_nodes = 0;
		double mixing_c = 0;
		double random_coeff = 0;
		double converge_threshold = 0;
		int change_reported = 0;

		public void configure(JobConf job) {
			number_nodes = Integer.parseInt(job.get("number_nodes"));
			mixing_c = Double.parseDouble(job.get("mixing_c"));
			random_coeff = (1-mixing_c) / (double)number_nodes;
			converge_threshold = Double.parseDouble(job.get("converge_threshold"));

			System.out.println("RedStage2: number_nodes = " + number_nodes + ", mixing_c = " + mixing_c + ", random_coeff = " + random_coeff + ", converge_threshold = " + converge_threshold );
		}

		public void reduce (final IntWritable key, final Iterator<Text> values, final OutputCollector<IntWritable, Text> output, final Reporter reporter) throws IOException
        {
			int i;
			double next_rank = 0;
			double previous_rank = 0;

			while (values.hasNext()) {
				String cur_value_str = values.next().toString();
				if( cur_value_str.charAt(0) == 's' )
					previous_rank = Double.parseDouble( cur_value_str.substring(1) );
				else
					next_rank += Double.parseDouble( cur_value_str.substring(1) ) ;
			}

			next_rank = next_rank * mixing_c + random_coeff;

			output.collect( key, new Text("v" + next_rank ) );

			if( change_reported == 0 ) {
				double diff = Math.abs(previous_rank-next_rank);

				if( diff > converge_threshold ) {
					reporter.incrCounter(PrCounters.CONVERGE_CHECK, 1);
					change_reported = 1;
				}
			}
		}
    }

    //////////////////////////////////////////////////////////////////////
    // STAGE 3: After finding pagerank, calculate min/max pagerank
	//  - Input: The converged PageRank vector
	//  - Output: (key 0) minimum PageRank, (key 1) maximum PageRank
    //////////////////////////////////////////////////////////////////////
	public static class MapStage3 extends MapReduceBase	implements Mapper<LongWritable, Text, IntWritable, DoubleWritable>
    {
		private final IntWritable from_node_int = new IntWritable();

		public void map (final LongWritable key, final Text value, final OutputCollector<IntWritable, DoubleWritable> output, final Reporter reporter) throws IOException
		{
			String line_text = value.toString();
			if (line_text.startsWith("#"))				// ignore comments in edge file
				return;

			final String[] line = line_text.split("\t");
			double pagerank = Double.parseDouble(line[1].substring(1));
			output.collect( new IntWritable(0) , new DoubleWritable( pagerank ) );
			output.collect( new IntWritable(1) , new DoubleWritable( pagerank ) );
		}
	}

    public static class RedStage3 extends MapReduceBase	implements Reducer<IntWritable, DoubleWritable, IntWritable, DoubleWritable>
    {
		int number_nodes = 0;
		double mixing_c = 0;
		double random_coeff = 0;

		public void configure(JobConf job) {
			number_nodes = Integer.parseInt(job.get("number_nodes"));
			mixing_c = Double.parseDouble(job.get("mixing_c"));
			random_coeff = (1-mixing_c) / (double)number_nodes;

			System.out.println("RedStage2: number_nodes = " + number_nodes + ", mixing_c = " + mixing_c + ", random_coeff = " + random_coeff );
		}

		public void reduce (final IntWritable key, final Iterator<DoubleWritable> values, final OutputCollector<IntWritable, DoubleWritable> output, final Reporter reporter) throws IOException
        {
			int i;
			double min_value = 1.0;
			double max_value = 0.0;

			int min_or_max = key.get();	// 0 : min, 1: max

			while (values.hasNext()) {
				double cur_value = values.next().get();

				if( min_or_max == 0 ) {	// find min
					if( cur_value < min_value )
						min_value = cur_value;
				} else {				// find max
					if( cur_value > max_value )
						max_value = cur_value;
				}
			}

			if( min_or_max == 0)
				output.collect( key, new DoubleWritable(min_value) );
			else
				output.collect( key, new DoubleWritable(max_value) );
		}
    }

    //////////////////////////////////////////////////////////////////////
    // STAGE 4 : Find distribution of pageranks.
	//  - Input: The converged PageRank vector
	//  - Output: The histogram of PageRank vector in 1000 bins between min_PageRank and max_PageRank
    //////////////////////////////////////////////////////////////////////
	public static class MapStage4 extends MapReduceBase implements Mapper<LongWritable, Text, IntWritable, IntWritable>
    {
		private final IntWritable from_node_int = new IntWritable();
		double min_pr = 0;
		double max_pr = 0;
		double gap_pr = 0;
		int hist_width = 1000;

		public void configure(JobConf job) {
			min_pr = Double.parseDouble(job.get("min_pr"));
			max_pr = Double.parseDouble(job.get("max_pr"));
			gap_pr = max_pr - min_pr;

			System.out.println("MapStage4: min_pr = " + min_pr + ", max_pr = " + max_pr);
		}

		public void map (final LongWritable key, final Text value, final OutputCollector<IntWritable, IntWritable> output, final Reporter reporter) throws IOException
		{
			String line_text = value.toString();
			if (line_text.startsWith("#"))				// ignore comments in edge file
				return;

			final String[] line = line_text.split("\t");
			double pagerank = Double.parseDouble(line[1].substring(1));
			int distr_index = (int)(hist_width * (pagerank - min_pr)/gap_pr) + 1;
			if(distr_index == hist_width + 1)
				distr_index = hist_width;
			output.collect( new IntWritable(distr_index) , new IntWritable(1) );
		}
	}

    public static class RedStage4 extends MapReduceBase implements Reducer<IntWritable, IntWritable, IntWritable, IntWritable>
    {
		public void reduce (final IntWritable key, final Iterator<IntWritable> values, final OutputCollector<IntWritable, IntWritable> output, final Reporter reporter) throws IOException
        {
			int sum = 0;

			while (values.hasNext()) {
				int cur_value = values.next().get();
				sum += cur_value;
			}

			output.collect( key, new IntWritable(sum) );
		}
    }

    //////////////////////////////////////////////////////////////////////
    // command line interface
    //////////////////////////////////////////////////////////////////////
    protected Path edge_path = null;
	protected Path vector_path = null;
    protected Path tempmv_path = null;
	protected Path output_path = null;
	protected String local_output_path;
	protected Path minmax_path = null;
	protected Path distr_path = null;
	protected int number_nodes = 0;
	protected int niteration = 32;
	protected double mixing_c = 0.85f;
	protected int nreducers = 1;
	protected int make_symmetric = 0;		// convert directed graph to undirected graph

    // Main entry point.
    public static void main (final String[] args) throws Exception
    {
		final int result = ToolRunner.run(new Configuration(), new PagerankNaive(), args);

		System.exit(result);
    }

    // Print the command-line usage text.
    protected static int printUsage ()
    {
		System.out.println("PagerankNaive <input_path> <output_path> <# of nodes>  <# of tasks> <max iteration> <makesym or nosym> <new or contNN>");

		ToolRunner.printGenericCommandUsage(System.out);

		return -1;
    }

	// submit the map/reduce job.
    public int run (final String[] args) throws Exception
    {
		if( args.length != 7 ) {
			return printUsage();
		}

		int i;
		edge_path = new Path(args[0]);

		output_path = new Path(args[1]+"/pr_output");
		vector_path = new Path(args[1]+"/pr_vector");
		tempmv_path = new Path(args[1]+"/pr_tmp");
		minmax_path = new Path(args[1]+"/pr_minmax");
		distr_path = new Path(args[1]+"/pr_distr");
		number_nodes = Integer.parseInt(args[2]);
		nreducers = Integer.parseInt(args[3]);
		niteration = Integer.parseInt(args[4]);

		if( args[5].compareTo("makesym") == 0 )
			make_symmetric = 1;
		else
			make_symmetric = 0;

		int cur_iteration = 1;
		if( args[6].startsWith("cont") )
			cur_iteration = Integer.parseInt(args[7].substring(4));

		local_output_path = args[2] + "_temp";

		converge_threshold = ((double)1.0/(double) number_nodes)/10;

		System.out.println("\n-----===[PEGASUS: A Peta-Scale Graph Mining System]===-----\n");
		System.out.println("[PEGASUS] Computing PageRank. Max iteration = " +niteration + ", threshold = " + converge_threshold + ", cur_iteration=" + cur_iteration + "\n");

		if( cur_iteration == 1 )
			gen_initial_vector(number_nodes, vector_path);

		final FileSystem fs = FileSystem.get(vector_path.toUri(), getConf());

		// Run pagerank until converges.
		for (i = cur_iteration; i <= niteration; i++) {
			JobClient.runJob(configStage1());
			RunningJob job = JobClient.runJob(configStage2());

			// The counter is newly created per every iteration.
			Counters c = job.getCounters();
			long changed = c.getCounter(PrCounters.CONVERGE_CHECK);
			System.out.println("Iteration = " + i + ", changed reducer = " + changed);

			if( changed == 0 ) {
				System.out.println("PageRank vector converged. Now preparing to finish...");
				fs.delete(vector_path);
				fs.delete(tempmv_path);
				fs.rename(output_path, vector_path);
				break;
			}

			// rotate directory
			fs.delete(vector_path);
			fs.delete(tempmv_path);
			fs.rename(output_path, vector_path);
		}

		if( i == niteration ) {
			System.out.println("Reached the max iteration. Now preparing to finish...");
		}

		// find min/max of pageranks
		//System.out.println("Finding minimum and maximum pageranks...");
		//JobClient.runJob(configStage3());

		//FileUtil.fullyDelete( FileSystem.getLocal(getConf()), new Path(local_output_path));
		//String new_path = local_output_path + "/" ;
		//fs.copyToLocalFile(minmax_path, new Path(new_path) ) ;

		//MinMaxInfo mmi = readMinMax( new_path );
		//System.out.println("min = " + mmi.min + ", max = " + mmi.max );

		// find distribution of pageranks
		//JobClient.runJob(configStage4(mmi.min, mmi.max));

		System.out.println("\n[PEGASUS] PageRank computed.");
		System.out.println("[PEGASUS] The final PageRanks are in the HDFS pr_vector.");
		//System.out.println("[PEGASUS] The minium and maximum PageRanks are in the HDFS pr_minmax.");
		//System.out.println("[PEGASUS] The histogram of PageRanks in 1000 bins between min_PageRank and max_PageRank are in the HDFS pr_distr.\n");

		return 0;
    }

	// generate initial pagerank vector
	public void gen_initial_vector(int number_nodes, Path vector_path) throws IOException
	{
		int i, j = 0;
		int milestone = number_nodes/10;
		String file_name = "pagerank_init_vector.temp";
		FileWriter file = new FileWriter(file_name);
		BufferedWriter out = new BufferedWriter (file);

		System.out.print("Creating initial pagerank vectors...");
		double initial_rank = 1.0 / (double)number_nodes;

		for(i=0; i < number_nodes; i++)
		{
			out.write(i + "\tv" + initial_rank +"\n");
			if(++j > milestone) {
					System.out.print(".");
					j = 0;
			}
		}
		out.close();
		System.out.println("");

		// copy it to curbm_path, and delete temporary local file.
		Path destination = new Path(vector_path.toString()+ "/" + file_name);
		final FileSystem fs = FileSystem.get(destination.toUri(), getConf());
		fs.copyFromLocalFile( true, new Path("./" + file_name), destination);
	}

	// read neighborhood number after each iteration.
	public static MinMaxInfo readMinMax(String new_path) throws Exception
	{
		MinMaxInfo info = new MinMaxInfo();
		String output_path = new_path + "/part-00000";
		String file_line = "";

		try {
			BufferedReader in = new BufferedReader(	new InputStreamReader(new FileInputStream( output_path ), "UTF8"));

			// Read first line
			file_line = in.readLine();

			// Read through file one line at time. Print line # and line
			while (file_line != null){
			    final String[] line = file_line.split("\t");

				if(line[0].startsWith("0"))
					info.min = Double.parseDouble( line[1] );
				else
					info.max = Double.parseDouble( line[1] );

				file_line = in.readLine();
			}

			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return info;//result;
	}

	// Configure pass1
    protected JobConf configStage1 () throws Exception
    {
		final JobConf conf = new JobConf(getConf(), PagerankNaive.class);
		conf.set("number_nodes", "" + number_nodes);
		conf.set("mixing_c", "" + mixing_c);
		conf.set("make_symmetric", "" + make_symmetric);
		conf.setJobName("Pagerank_Stage1");

		conf.setMapperClass(MapStage1.class);
		conf.setReducerClass(RedStage1.class);

		FileInputFormat.setInputPaths(conf, edge_path, vector_path);
		FileOutputFormat.setOutputPath(conf, tempmv_path);

		conf.setNumReduceTasks( nreducers );

		conf.setOutputKeyClass(IntWritable.class);
		conf.setOutputValueClass(Text.class);

		return conf;
    }

	// Configure pass2
    protected JobConf configStage2 () throws Exception
    {
		final JobConf conf = new JobConf(getConf(), PagerankNaive.class);
		conf.set("number_nodes", "" + number_nodes);
		conf.set("mixing_c", "" + mixing_c);
		conf.set("converge_threshold", "" + converge_threshold);
		conf.setJobName("Pagerank_Stage2");

		conf.setMapperClass(MapStage2.class);
		conf.setReducerClass(RedStage2.class);

		FileInputFormat.setInputPaths(conf, tempmv_path);
		FileOutputFormat.setOutputPath(conf, output_path);

		conf.setNumReduceTasks( nreducers );

		conf.setOutputKeyClass(IntWritable.class);
		conf.setOutputValueClass(Text.class);

		return conf;
    }

	// Configure pass3
    protected JobConf configStage3 () throws Exception
    {
		final JobConf conf = new JobConf(getConf(), PagerankNaive.class);
		conf.set("number_nodes", "" + number_nodes);
		conf.set("mixing_c", "" + mixing_c);
		conf.set("converge_threshold", "" + converge_threshold);
		conf.setJobName("Pagerank_Stage3");

		conf.setMapperClass(MapStage3.class);
		conf.setReducerClass(RedStage3.class);
		conf.setCombinerClass(RedStage3.class);

		FileInputFormat.setInputPaths(conf, vector_path);
		FileOutputFormat.setOutputPath(conf, minmax_path);

		conf.setNumReduceTasks( 1 );

		conf.setOutputKeyClass(IntWritable.class);
		conf.setOutputValueClass(DoubleWritable.class);

		return conf;
    }

	// Configure pass4
    protected JobConf configStage4 (double min_pr, double max_pr) throws Exception
    {
		final JobConf conf = new JobConf(getConf(), PagerankNaive.class);
		conf.set("min_pr", "" + min_pr);
		conf.set("max_pr", "" + max_pr);

		conf.setJobName("Pagerank_Stage4");

		conf.setMapperClass(MapStage4.class);
		conf.setReducerClass(RedStage4.class);
		conf.setCombinerClass(RedStage4.class);

		FileInputFormat.setInputPaths(conf, vector_path);
		FileOutputFormat.setOutputPath(conf, distr_path);

		conf.setNumReduceTasks( nreducers );

		conf.setOutputKeyClass(IntWritable.class);
		conf.setOutputValueClass(IntWritable.class);

		return conf;
    }

}

{'repo_name': 'Intel-bigdata/HiBench', 'stars': '1015', 'repo_language': 'Java', 'file_name': 'dfsioe.conf', 'mime_type': 'text/plain', 'hash': -5010875016936867273, 'source_dataset': 'data'}


<gpx xmlns="http://www.topografix.com/GPX/1/1"
	 xmlns:gpxdata="http://www.cluetrust.com/XML/GPXDATA/1/0"
	 creator="pytrainer http://sourceforge.net/projects/pytrainer" version="1.1">
	<metadata>
		<name>Run 2009-06-19</name>
		<link href="http://sourceforge.net/projects/pytrainer"/>
		<time>2009-06-19T10:13:04Z</time>
	</metadata>
	<trk>
		<trkseg>
			<trkpt lat="51.219983" lon="6.765224">
				<ele>52.048584</ele>
				<time>2009-06-19T10:13:04Z</time>
				<extensions>
					<gpxdata:hr>164</gpxdata:hr>
					<gpxdata:cadence>99</gpxdata:cadence>
				</extensions>
			</trkpt>
			<trkpt lat="51.220137" lon="6.765098">
				<ele>52.529175</ele>
				<time>2009-06-19T10:13:09Z</time>
				<extensions>
					<gpxdata:hr>161</gpxdata:hr>
					<gpxdata:cadence>95</gpxdata:cadence>
				</extensions>
			</trkpt>
			<trkpt lat="51.219983" lon="6.765224">
				<ele>52.048584</ele>
				<time>2009-06-19T10:13:15Z</time>
				<extensions>
					<gpxdata:hr>164</gpxdata:hr>
					<gpxdata:cadence>99</gpxdata:cadence>
				</extensions>
			</trkpt>
			<trkpt lat="51.220137" lon="6.765098">
				<ele>52.529175</ele>
				<time>2009-06-19T10:13:19Z</time>
				<extensions>
					<gpxdata:hr>161</gpxdata:hr>
					<gpxdata:cadence>96</gpxdata:cadence>
				</extensions>
			</trkpt>
		</trkseg>
	</trk>
<extensions>
	<gpxdata:lap>
		<gpxdata:index>1</gpxdata:index>
		<gpxdata:startPoint lat="51.219983" lon="6.765224"/>
		<gpxdata:endPoint lat="51.220137" lon="6.765098" />
		<gpxdata:startTime>2009-06-19T10:13:04Z</gpxdata:startTime>
		<gpxdata:elapsedTime>4.6700000</gpxdata:elapsedTime>
		<gpxdata:calories>1</gpxdata:calories>
		<gpxdata:distance>0.5881348</gpxdata:distance>
		<gpxdata:summary name="AverageHeartRateBpm" kind="avg">163</gpxdata:summary>
		<gpxdata:trigger kind="manual" />
		<gpxdata:intensity>active</gpxdata:intensity>
	</gpxdata:lap>
</extensions>
</gpx>

{'repo_name': 'jenetics/jpx', 'stars': '106', 'repo_language': 'Java', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': -8583811144214238407, 'source_dataset': 'data'}


--TEST--
Bug #60322 (ob_get_clean() now raises an E_NOTICE if no buffers exist)
--FILE--
<?php
while(ob_get_clean()) ;
var_dump(ob_get_clean());
--EXPECT--
bool(false)

{'repo_name': 'niklasvh/php.js', 'stars': '805', 'repo_language': 'PHP', 'file_name': 'locales.js', 'mime_type': 'text/plain', 'hash': -695561690206920356, 'source_dataset': 'data'}


{
  "animatedParts" : {
    "stateTypes" : {
      "body" : {
        "priority" : 0,
        "default" : "idle",
        "states" : {
          "idle" : {
            "frames" : 13,
            "cycle" : 1.5
          },
          "walk" : {
            "frames" : 5,
            "cycle" : 0.5,
            "mode" : "loop",
            "properties" : {
            "particleEmittersOff" : [ "spindust" ]
            }
          },
          "jump" : {
            "frames" : 1,
            "cycle" : 0.25,
            "mode" : "loop",
            "properties" : {
              "immediateSound" : "/sfx/npc/monsters/monster_hop.ogg",
              "immediateSoundRangeMultiplier" : 0.5
            }
          },
          "fall" : {
            "frames" : 1,
            "cycle" : 0.25,
            "mode" : "loop"
          },
          "chargewindup" : {
            "frames" : 8,
            "cycle" : 0.125,
            "mode" : "loop",
            "properties" : {
              "particleEmittersOn" : [ "spindust" ],
              "persistentSound" : "/sfx/npc/monsters/mandraflora_windup.ogg",
              "persistentSoundStopTime" : 0.15
            }
          },
          "chargewinddown" : {
            "frames" : 8,
            "cycle" : 0.6,
            "mode" : "transition",
            "transition" : "fall",
            "properties" : {
              "particleEmittersOff" : [ "spindust" ]
              // "persistentSound" : "/sfx/npc/monsters/mandraflora_winddown.ogg",
              // "persistentSoundStopTime" : 1
            }
          },
          "charge" : {
            "frames" : 8,
            "cycle" : 0.18,
            "mode" : "loop",
            "properties" : {
              "persistentSound" : "/sfx/npc/monsters/mandraflora_spinning.ogg",
              "persistentSoundStopTime" : 0.5
            }
          }
        }
      },
      "damage" : {
        "priority" : 3,
        "default" : "none",
        "states" : {
          "none" : {
            "frames" : 1
          },
          "stunned" : {
            "frames" : 1
          }
        }
      },
      "releaseParticles" : {
        "default" : "off",
        "states" : {
          "off" : {
            "frames" : 1,
            "properties" : {
              "particleEmittersOff" : [ "releaseParticles" ]
            }
          },
          "on" : {
            "frames" : 1,
            "cycle" : 0.1,
            "mode" : "transition",
            "transition" : "off",
            "properties" : {
              "particleEmittersOn" : [ "releaseParticles" ]
            }
          }
        }
      }
    },

    "parts" : {
      "body" : {
        "properties" : {
          "transformationGroups" : [ "body" ],
          "offset" : [-0.0625, 0.6875]
        },
        "partStates" : {
          "body" : {
            "idle" : {
              "properties" : {
                "image" : "<partImage>:idle.<frame>"
              }
            },
            "walk" : {
              "properties" : {
                "image" : "<partImage>:walk.<frame>"
              }
            },
            "jump" : {
              "properties" : {
                "image" : "<partImage>:walk.<frame>"
              }
            },
            "fall" : {
              "properties" : {
                "image" : "<partImage>:walk.<frame>"
              }
            },
            "chargewindup" : {
              "properties" : {
                "image" : "<partImage>:charge.<frame>"
              }
            },
            "chargewinddown" : {
              "properties" : {
                "image" : "<partImage>:charge.<frame>"
              }
            },
            "charge" : {
              "properties" : {
                "image" : "<partImage>:charge.<frame>"
              }
            }
          },
          "damage" : {
            "stunned" : {
              "properties" : {
                "image" : "<partImage>:hurt.<frame>"
              }
            }
          }
        }
      }
    }
  },

  "transformationGroups" : {
    "body" : { "interpolated" : true }
  },

  "effects" : {
    "blink" : {
      "type" : "flash",
      "time" : 0,
      "directives" : "fade=ffffff;0.5"
    }
  },

  "particleEmitters" : {
    "spindust" : {
      "emissionRate" : 15,
      "offsetRegion" : [ -0.0, -2.25, 0.0, -2.25 ],
      "particles" : [
        { "particle" : "mandrafloradust" }
      ]
    },
    "deathPoof" : {
      "particles" : [
        { "particle" : "monstersplosion" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathember" },
        { "particle" : "deathfizz1left" },
        { "particle" : "deathfizz1right" },
        { "particle" : "deathfizz2left" },
        { "particle" : "deathfizz2right" },
        { "particle" : "deathfizz3left" },
        { "particle" : "deathfizz3right" },
        { "particle" : "deathfizz4left" },
        { "particle" : "deathfizz4right" }
      ]
    },
    "captureParticles" : {
      "particles" : [
        { "particle" : "monstercapture" }
      ]
    },
    "releaseParticles" : {
      "particles" : [
        { "particle" : "monsterrelease" }
      ]
    },
    "teleportOut" : {
      "particles" : [
        { "particle" : "monstercapture" }
      ]
    },
    "teleportIn" : {
      "particles" : [
        { "particle" : "monsterrelease" }
      ]
    },
    "levelUp" : {
      "particles" : [
        { "particle" : "monsterlevelup" }
      ]
    }
  },

  "sounds" : {
    "aggroHop" : [ "/sfx/npc/monsters/monster_surprise.ogg" ],
    "fire" : [ "/sfx/npc/monsters/monster_surprise.ogg" ],
    "deathPuff" : [ "/sfx/npc/enemydeathpuff.ogg" ]
  }
}

{'repo_name': 'sayterdarkwynd/FrackinUniverse', 'stars': '315', 'repo_language': 'Lua', 'file_name': 'villager_photontop.tenant', 'mime_type': 'text/plain', 'hash': -8637541222665015662, 'source_dataset': 'data'}


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
#          \file   logging.py
#        \author   chenghuige
#          \date   2016-09-24 09:25:56.796006
#   \Description
# ==============================================================================

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# import tensorflow as tf
# flags = tf.app.flags
# FLAGS = flags.FLAGS

import sys

import logging
import logging.handlers

import gezi

_logger = logging.getLogger('melt')

_logger2 = logging.getLogger('melt2')

#_handler = logging.StreamHandler()
#_handler.setLevel(logging.INFO)
#_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
#_logger.addHandler(_handler)
#_logger.setLevel(logging.INFO)

log = _logger.log
#debug = _logger.debug
#error = _logger.error
#fatal = _logger.fatal
#info = _logger.info
#warn = _logger.warn
#warning = _logger.warning

#info2 = _logger2.info

hvd = None

def set_hvd(hvd_):
  global hvd
  hvd = hvd_

def info(*args):
  if not hvd or hvd.rank() == 0:
    _logger.info(' '.join("{}".format(a) for a in args))

def info2(*args):
  if not hvd or hvd.rank() == 0:
    _logger2.info(' '.join("{}".format(a) for a in args))

def fatal(*args):
  if not hvd or hvd.rank() == 0:
    _logger.fatal(' '.join("{}".format(a) for a in args))

def error(*args):
  if not hvd or hvd.rank() == 0:
    _logger.error(' '.join("{}".format(a) for a in args))

def debug(*args):
  if not hvd or hvd.rank() == 0:
    _logger.debug(' '.join("{}".format(a) for a in args))

def warn(*args):
  if not hvd or hvd.rank() == 0:
    _logger.warn(' '.join("{}".format(a) for a in args))

def warning(*args):
  if not hvd or hvd.rank() == 0:
    _logger.warning('WARNING: %s' % (' '.join("{}".format(a) for a in args)))

from datetime import timedelta
import time

class ElapsedFormatter():
  def __init__(self):
    self.start_time = time.time()

  def format(self, record):
    elapsed_seconds = record.created - self.start_time
    #using timedelta here for convenient default formatting
    elapsed = timedelta(seconds = elapsed_seconds)
    return "{} {} {}".format(gezi.now_time(), str(elapsed)[:-7], record.getMessage())

_logging_file = None
_logging_file2 = None

def _get_handler(file, formatter, split=True, split_bytime=False, mode = 'a', level=logging.INFO):
  #setting below will set root logger write to _logging_file
  #logging.basicConfig(filename=_logging_file, level=level, format=None)
  #logging.basicConfig(filename=_logging_file, level=level)
  #save one per 1024k/4, save at most 10G 1024
  if split:
    if not split_bytime:
      file_handler = logging.handlers.RotatingFileHandler(file, mode=mode, maxBytes=1024*1024/4, backupCount=10240*4)
    else:
      file_handler = logging.handlers.TimedRotatingFileHandler(file, when='H', interval=1, backupCount=1024)
      file_handler.suffix = "%Y%m%d-%H%M"
  else:
    file_handler = logging.FileHandler(_logging_file, mode=mode)
  file_handler.setLevel(level)
  file_handler.setFormatter(formatter)
  return file_handler

def set_dir(path, file='log.html', logtostderr=True, logtofile=True, split=True, split_bytime=False, level=logging.INFO, mode='a'):
  global _logger, _logging_file
  if _logging_file is None:
    if not path:
      path = '/tmp/'
    _logging_file = '%s/%s'%(path, file)
    _logging_file2 = '%s/log.txt'%path
    #formatter = logging.Formatter("%(asctime)s %(message)s",
    #                          "%Y-%m-%d %H:%M:%S")
    formatter = ElapsedFormatter()
    if logtofile:
      gezi.try_mkdir(path)
      file_handler = _get_handler(_logging_file, formatter, split, split_bytime, mode, level)
      file_handler2 = _get_handler(_logging_file2, formatter, split, True, mode, level)
      #file_handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
      _logger.addHandler(file_handler)
      _logger2.addHandler(file_handler2)

    if logtostderr:
      handler = logging.StreamHandler()
      handler.setLevel(logging.INFO)
      handler.setFormatter(formatter)
      #handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT, None))
      _logger.addHandler(handler)
      _logger2.addHandler(handler)

      # some how new tf cause to logg twice..
      # https://stackoverflow.com/questions/19561058/duplicate-output-in-simple-python-logging-configuration
      _logger.propagate = False
      _logger2.propagate = False

    _logger.setLevel(level)
    _logger2.setLevel(level)

def init(path, file='log.html', logtostderr=True, logtofile=True, split=True, split_bytime=False, level=logging.INFO, mode='a'):
  #logging.basicConfig(level=logging.INFO, stream=sys.stdout)
  set_dir(path=path, mode=mode, file=file, logtostderr=logtostderr, logtofile=logtofile, split=split, split_bytime=split_bytime, level=level)

def vlog(level, msg, *args, **kwargs):
  _logger.log(level, msg, *args, **kwargs)

def get_verbosity():
  """Return how much logging output will be produced."""
  return _logger.getEffectiveLevel()

def set_verbosity(verbosity):
  """Sets the threshold for what messages will be logged."""
  _logger.setLevel(verbosity)

def get_logging_file():
  return _logging_file

{'repo_name': 'chenghuige/wenzheng', 'stars': '536', 'repo_language': 'Jupyter Notebook', 'file_name': 'tokenizer.py', 'mime_type': 'text/x-python', 'hash': -4409158289453539428, 'source_dataset': 'data'}


{'repo_name': 'microsoft/CDM', 'stars': '662', 'repo_language': 'Java', 'file_name': 'InventTransOriginRAssetScrap_RU.1.0.cdm.json', 'mime_type': 'text/plain', 'hash': -6430742316546668470, 'source_dataset': 'data'}


(ns autocomplete.core
    (:require [reagent.core :as reagent]))

(defn home-render []
  [:div.ui-widget
   [:label {:for "tags"} "Programming Languages: "]
   [:input#tags]])

(def tags
  ["ActionScript"
   "AppleScript"
   "Asp"
   "BASIC"
   "C"
   "C++"
   "Clojure"
   "COBOL"
   "ColdFusion"
   "Erlang"
   "Fortran"
   "Groovy"
   "Haskell"
   "Java"
   "JavaScript"
   "Lisp"
   "Perl"
   "PHP"
   "Python"
   "Ruby"
   "Scala"
   "Scheme"])

(defn home-did-mount []
  (js/$ (fn []
          (.autocomplete (js/$ "#tags")
                         (clj->js {:source tags})))))

(defn home []
  (reagent/create-class {:reagent-render home-render
                         :component-did-mount home-did-mount}))

(defn ^:export main []
  (reagent/render [home]
                  (.getElementById js/document "app")))

{'repo_name': 'reagent-project/reagent-cookbook', 'stars': '750', 'repo_language': 'Clojure', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': -1238142465868878102, 'source_dataset': 'data'}


/*
 * Anchore Engine API Server
 *
 * This is the Anchore Engine API. Provides the primary external API for users of the service.
 *
 * API version: 0.1.12
 * Contact: nurmi@anchore.com
 */

// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.

package anchore
// AnchoreErrorCode A description of an anchore error code (name, description)
type AnchoreErrorCode struct {
	// Error code name
	Name string `json:"name,omitempty"`
	// Description of the error code
	Description string `json:"description,omitempty"`
}

{'repo_name': 'banzaicloud/pipeline', 'stars': '1326', 'repo_language': 'Go', 'file_name': 'config_test.go', 'mime_type': 'text/plain', 'hash': 8047653452834930376, 'source_dataset': 'data'}


#include <iostream>

struct MyClass1
{
public:
  int GetId() const {return 1;}
};

struct MyClass2
{
public:
  int GetId() const {return 2;}
};

template <typename T>
void MyFunction(const T& object)
{
  std::cout << object.GetId() << std::endl;
}

int main(int argc, char *argv[])
{
  MyClass1 myClass1;
  MyFunction(myClass1);

  MyClass2 myClass2;
  MyFunction(myClass2);

  return 0;
}

{'repo_name': 'daviddoria/Examples', 'stars': '178', 'repo_language': 'C++', 'file_name': 'Flicker.sh', 'mime_type': 'text/x-shellscript', 'hash': -5374582156079208106, 'source_dataset': 'data'}


{'repo_name': 'QuarkChain/pyquarkchain', 'stars': '190', 'repo_language': 'Python', 'file_name': 'test_qkcpow.py', 'mime_type': 'text/x-python', 'hash': -1420895221239774893, 'source_dataset': 'data'}


#!/usr/bin/ruby

hostname = `"/Library/Application Support/VMware Tools/vmware-tools-daemon" --cmd "info-get guestinfo.hostname"`

hostname = hostname.chomp

puts "Nice to meet you, my VM name is '#{hostname}'."

puts "\n"

puts '- Setting local hostname...'

hostnamecmd = "/usr/sbin/scutil --set HostName #{hostname}"
computernamecmd = "/usr/sbin/scutil --set ComputerName #{hostname}"
localhostnamecmd = "/usr/sbin/scutil --set LocalHostName #{hostname}"
Kernel.system(hostnamecmd)
Kernel.system(computernamecmd)
Kernel.system(localhostnamecmd)

puts '- Re-obtaining DHCP lease...'

Kernel.system('/usr/sbin/ipconfig set en0 none')
Kernel.system('/usr/sbin/ipconfig set en0 dhcp')

puts '- Cleaning up...'

Kernel.system('rm /Library/LaunchDaemons/local.localhost.startup.plist')
Kernel.system('rm /etc/rc.local')

puts "\n"

puts 'Done!'

{'repo_name': 'puppetlabs/puppetlabs-packer', 'stars': '106', 'repo_language': 'PowerShell', 'file_name': 'dummy-test.rb', 'mime_type': 'text/plain', 'hash': 4066900608821573173, 'source_dataset': 'data'}


mysql -Be 'CREATE DATABASE somedb COLLATE utf8_bin CHARSET UTF-8'

{'repo_name': 'Fizzadar/pyinfra', 'stars': '877', 'repo_language': 'Python', 'file_name': '__init__.py', 'mime_type': 'text/x-python', 'hash': 389060158733095701, 'source_dataset': 'data'}


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

#include "sc.hrc"	// -> SC_DLG_ATTR

#define TP_NUMBER		1
#define TP_FONT			2
#define TP_ALIGNMENT	3
#define TP_BORDER		4
#define TP_BACKGROUND	5
#define TP_PROTECTION	6
#define TP_FONTEFF		7
#define TP_ASIAN		8

//================================================
// Zellschutz-TabPage:

#define BTN_PROTECTED			1
#define BTN_HIDE_FORMULAR		2
#define BTN_HIDE_ALL			3
#define FT_HINT                 4
#define FL_PROTECTION           5
#define BTN_HIDE_PRINT          6
#define FT_HINT2                7
#define FL_PRINT                8

{'repo_name': 'apache/openoffice', 'stars': '410', 'repo_language': 'C++', 'file_name': 'ascfldlg.hrc', 'mime_type': 'text/plain', 'hash': -7663243872127651004, 'source_dataset': 'data'}


# Security configuration for openapi-security in light-rest-4j. It is a specific config
# for OpenAPI framework security. It is introduced to support multiple frameworks in the
# same server instance. If this file cannot be found, the generic security.yml will be
# loaded for backward compatibility.
---
# Enable JWT verification flag.
enableVerifyJwt: ${openapi-security.enableVerifyJwt:false}

# Extract JWT scope token from the X-Scope-Token header and validate the JWT token
enableExtractScopeToken: ${openapi-security.enableExtractScopeToken:true}

# Enable JWT scope verification. Only valid when enableVerifyJwt is true.
enableVerifyScope: ${openapi-security.enableVerifyScope:true}

# Enable JWT scope verification.
# Only valid when (enableVerifyJwt is true) AND (enableVerifyJWTScopeToken is true)
enableVerifyJWTScopeToken: ${openapi-security.enableVerifyJWTScopeToken:true}

# User for test only. should be always be false on official environment.
enableMockJwt: ${openapi-security.enableMockJwt:false}

# JWT signature public certificates. kid and certificate path mappings.
jwt:
  certificate:
    '100': primary.crt
    '101': secondary.crt
  clockSkewInSeconds: 60
  # Key distribution server standard: JsonWebKeySet for other OAuth 2.0 provider| X509Certificate for light-oauth2
  keyResolver: X509Certificate

# Enable or disable JWT token logging
logJwtToken: ${openapi-security.logJwtToken:true}

# Enable or disable client_id, user_id and scope logging.
logClientUserScope: ${openapi-security.logClientUserScope:false}

# Enable JWT token cache to speed up verification. This will only verify expired time
# and skip the signature verification as it takes more CPU power and long time.
enableJwtCache: ${openapi-security.enableJwtCache:true}

# If you are using light-oauth2, then you don't need to have oauth subfolder for public
# key certificate to verify JWT token, the key will be retrieved from key endpoint once
# the first token is arrived. Default to false for dev environment without oauth2 server
# or official environment that use other OAuth 2.0 providers.
bootstrapFromKeyService: ${openapi-security.bootstrapFromKeyService:false}

{'repo_name': 'networknt/light-example-4j', 'stars': '131', 'repo_language': 'Java', 'file_name': 'logback.xml', 'mime_type': 'text/xml', 'hash': 4622510062110414662, 'source_dataset': 'data'}


// Copyright © 2017 Dmitry Sikorsky. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using ExtCore.Data.Abstractions;
using ExtCore.Events;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Platformus.Barebone;
using Platformus.Designers.Backend.ViewModels.Styles;
using Platformus.Designers.Events;

namespace Platformus.Designers.Backend.Controllers
{
  [Area("Backend")]
  [Authorize(Policy = Policies.HasBrowseStylesPermission)]
  public class StylesController : Platformus.Barebone.Backend.Controllers.ControllerBase
  {
    public StylesController(IStorage storage)
      : base(storage)
    {
    }

    public ActionResult Index(string orderBy = "filename", string direction = "asc", int skip = 0, int take = 10, string filter = null)
    {
      return this.View(new IndexViewModelFactory(this).Create(orderBy, direction, skip, take, filter));
    }

    [HttpGet]
    [ImportModelStateFromTempData]
    public IActionResult CreateOrEdit(string id)
    {
      return this.View(new CreateOrEditViewModelFactory(this).Create(id));
    }

    [HttpPost]
    [ExportModelStateToTempData]
    public IActionResult CreateOrEdit(CreateOrEditViewModel createOrEdit)
    {
      if (this.ModelState.IsValid)
      {
        if (!string.IsNullOrEmpty(createOrEdit.Id))
          System.IO.File.Delete(PathManager.GetStylePath(this, createOrEdit.Id));

        System.IO.File.WriteAllText(PathManager.GetStylePath(this, createOrEdit.Filename), createOrEdit.Content);

        if (string.IsNullOrEmpty(createOrEdit.Id))
          Event<IStyleCreatedEventHandler, IRequestHandler, string>.Broadcast(this, createOrEdit.Filename);

        else Event<IStyleEditedEventHandler, IRequestHandler, string>.Broadcast(this, createOrEdit.Filename);

        return this.RedirectToAction("Index");
      }

      return this.CreateRedirectToSelfResult();
    }

    public ActionResult Delete(string id)
    {
      System.IO.File.Delete(PathManager.GetStylePath(this, id));
      Event<IStyleDeletedEventHandler, IRequestHandler, string>.Broadcast(this, id);
      return this.RedirectToAction("Index");
    }
  }
}

{'repo_name': 'Platformus/Platformus', 'stars': '405', 'repo_language': 'C#', 'file_name': 'Metadata.uk.resx', 'mime_type': 'text/xml', 'hash': 1975144943290860048, 'source_dataset': 'data'}


# AngularCliSample2

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 6.0.3.

## Development server

Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

## Code scaffolding

Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.

## Build

Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build.

## Running unit tests

Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).

## Running end-to-end tests

Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).

## Further help

To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

{'repo_name': 'cloudinary/cloudinary_angular', 'stars': '305', 'repo_language': 'TypeScript', 'file_name': 'photo-upload-jquery.component.ts', 'mime_type': 'text/x-java', 'hash': -2102994010030585986, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2016 Hammock and its contributors
  ~
  ~ 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.
  -->

<persistence
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        version="2.1"
        xmlns="http://xmlns.jcp.org/xml/ns/persistence"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="MyPU" transaction-type="RESOURCE_LOCAL">
        <class>ws.ament.hammock.jpa.openjpa.Employee</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:./target/default"/>
        </properties>
    </persistence-unit>
</persistence>

{'repo_name': 'hammock-project/hammock', 'stars': '103', 'repo_language': 'Java', 'file_name': 'pom.xml', 'mime_type': 'text/xml', 'hash': 4300490703420297685, 'source_dataset': 'data'}


using Akka.Actor;
using Neo.Cryptography;
using Neo.IO.Caching;
using Neo.Ledger;
using Neo.Network.P2P.Capabilities;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.Plugins;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;

namespace Neo.Network.P2P
{
    partial class RemoteNode
    {
        private class Timer { }
        private class PendingKnownHashesCollection : KeyedCollection<UInt256, (UInt256, DateTime)>
        {
            protected override UInt256 GetKeyForItem((UInt256, DateTime) item)
            {
                return item.Item1;
            }
        }

        private readonly PendingKnownHashesCollection pendingKnownHashes = new PendingKnownHashesCollection();
        private readonly HashSetCache<UInt256> knownHashes = new HashSetCache<UInt256>(Blockchain.Singleton.MemPool.Capacity * 2 / 5);
        private readonly HashSetCache<UInt256> sentHashes = new HashSetCache<UInt256>(Blockchain.Singleton.MemPool.Capacity * 2 / 5);
        private bool verack = false;
        private BloomFilter bloom_filter;

        private static readonly TimeSpan TimerInterval = TimeSpan.FromSeconds(30);
        private static readonly TimeSpan PendingTimeout = TimeSpan.FromMinutes(1);

        private readonly ICancelable timer = Context.System.Scheduler.ScheduleTellRepeatedlyCancelable(TimerInterval, TimerInterval, Context.Self, new Timer(), ActorRefs.NoSender);

        private void OnMessage(Message msg)
        {
            foreach (IP2PPlugin plugin in Plugin.P2PPlugins)
                if (!plugin.OnP2PMessage(msg))
                    return;
            if (Version == null)
            {
                if (msg.Command != MessageCommand.Version)
                    throw new ProtocolViolationException();
                OnVersionMessageReceived((VersionPayload)msg.Payload);
                return;
            }
            if (!verack)
            {
                if (msg.Command != MessageCommand.Verack)
                    throw new ProtocolViolationException();
                OnVerackMessageReceived();
                return;
            }
            switch (msg.Command)
            {
                case MessageCommand.Addr:
                    OnAddrMessageReceived((AddrPayload)msg.Payload);
                    break;
                case MessageCommand.Block:
                    OnInventoryReceived((Block)msg.Payload);
                    break;
                case MessageCommand.Consensus:
                    OnInventoryReceived((ConsensusPayload)msg.Payload);
                    break;
                case MessageCommand.FilterAdd:
                    OnFilterAddMessageReceived((FilterAddPayload)msg.Payload);
                    break;
                case MessageCommand.FilterClear:
                    OnFilterClearMessageReceived();
                    break;
                case MessageCommand.FilterLoad:
                    OnFilterLoadMessageReceived((FilterLoadPayload)msg.Payload);
                    break;
                case MessageCommand.GetAddr:
                    OnGetAddrMessageReceived();
                    break;
                case MessageCommand.GetBlocks:
                    OnGetBlocksMessageReceived((GetBlocksPayload)msg.Payload);
                    break;
                case MessageCommand.GetBlockByIndex:
                    OnGetBlockByIndexMessageReceived((GetBlockByIndexPayload)msg.Payload);
                    break;
                case MessageCommand.GetData:
                    OnGetDataMessageReceived((InvPayload)msg.Payload);
                    break;
                case MessageCommand.GetHeaders:
                    OnGetHeadersMessageReceived((GetBlockByIndexPayload)msg.Payload);
                    break;
                case MessageCommand.Inv:
                    OnInvMessageReceived((InvPayload)msg.Payload);
                    break;
                case MessageCommand.Mempool:
                    OnMemPoolMessageReceived();
                    break;
                case MessageCommand.Ping:
                    OnPingMessageReceived((PingPayload)msg.Payload);
                    break;
                case MessageCommand.Pong:
                    OnPongMessageReceived((PingPayload)msg.Payload);
                    break;
                case MessageCommand.Transaction:
                    if (msg.Payload.Size <= Transaction.MaxTransactionSize)
                        OnInventoryReceived((Transaction)msg.Payload);
                    break;
                case MessageCommand.Verack:
                case MessageCommand.Version:
                    throw new ProtocolViolationException();
                case MessageCommand.Alert:
                case MessageCommand.Headers:
                case MessageCommand.MerkleBlock:
                case MessageCommand.NotFound:
                case MessageCommand.Reject:
                default: break;
            }
        }

        private void OnAddrMessageReceived(AddrPayload payload)
        {
            system.LocalNode.Tell(new Peer.Peers
            {
                EndPoints = payload.AddressList.Select(p => p.EndPoint).Where(p => p.Port > 0)
            });
        }

        private void OnFilterAddMessageReceived(FilterAddPayload payload)
        {
            bloom_filter?.Add(payload.Data);
        }

        private void OnFilterClearMessageReceived()
        {
            bloom_filter = null;
        }

        private void OnFilterLoadMessageReceived(FilterLoadPayload payload)
        {
            bloom_filter = new BloomFilter(payload.Filter.Length * 8, payload.K, payload.Tweak, payload.Filter);
        }

        /// <summary>
        /// Will be triggered when a MessageCommand.GetAddr message is received.
        /// Randomly select nodes from the local RemoteNodes and tells to RemoteNode actors a MessageCommand.Addr message.
        /// The message contains a list of networkAddresses from those selected random peers.
        /// </summary>
        private void OnGetAddrMessageReceived()
        {
            Random rand = new Random();
            IEnumerable<RemoteNode> peers = LocalNode.Singleton.RemoteNodes.Values
                .Where(p => p.ListenerTcpPort > 0)
                .GroupBy(p => p.Remote.Address, (k, g) => g.First())
                .OrderBy(p => rand.Next())
                .Take(AddrPayload.MaxCountToSend);
            NetworkAddressWithTime[] networkAddresses = peers.Select(p => NetworkAddressWithTime.Create(p.Listener.Address, p.Version.Timestamp, p.Version.Capabilities)).ToArray();
            if (networkAddresses.Length == 0) return;
            EnqueueMessage(Message.Create(MessageCommand.Addr, AddrPayload.Create(networkAddresses)));
        }

        /// <summary>
        /// Will be triggered when a MessageCommand.GetBlocks message is received.
        /// Tell the specified number of blocks' hashes starting with the requested HashStart until payload.Count or MaxHashesCount
        /// Responses are sent to RemoteNode actor as MessageCommand.Inv Message.
        /// </summary>
        /// <param name="payload">A GetBlocksPayload including start block Hash and number of blocks requested.</param>
        private void OnGetBlocksMessageReceived(GetBlocksPayload payload)
        {
            UInt256 hash = payload.HashStart;
            // The default value of payload.Count is -1
            int count = payload.Count < 0 || payload.Count > InvPayload.MaxHashesCount ? InvPayload.MaxHashesCount : payload.Count;
            TrimmedBlock state = Blockchain.Singleton.View.Blocks.TryGet(hash);
            if (state == null) return;
            List<UInt256> hashes = new List<UInt256>();
            for (uint i = 1; i <= count; i++)
            {
                uint index = state.Index + i;
                if (index > Blockchain.Singleton.Height)
                    break;
                hash = Blockchain.Singleton.GetBlockHash(index);
                if (hash == null) break;
                hashes.Add(hash);
            }
            if (hashes.Count == 0) return;
            EnqueueMessage(Message.Create(MessageCommand.Inv, InvPayload.Create(InventoryType.Block, hashes.ToArray())));
        }

        private void OnGetBlockByIndexMessageReceived(GetBlockByIndexPayload payload)
        {
            uint count = payload.Count == -1 ? InvPayload.MaxHashesCount : Math.Min((uint)payload.Count, InvPayload.MaxHashesCount);
            for (uint i = payload.IndexStart, max = payload.IndexStart + count; i < max; i++)
            {
                Block block = Blockchain.Singleton.GetBlock(i);
                if (block == null)
                    break;

                if (bloom_filter == null)
                {
                    EnqueueMessage(Message.Create(MessageCommand.Block, block));
                }
                else
                {
                    BitArray flags = new BitArray(block.Transactions.Select(p => bloom_filter.Test(p)).ToArray());
                    EnqueueMessage(Message.Create(MessageCommand.MerkleBlock, MerkleBlockPayload.Create(block, flags)));
                }
            }
        }

        /// <summary>
        /// Will be triggered when a MessageCommand.GetData message is received.
        /// The payload includes an array of hash values.
        /// For different payload.Type (Tx, Block, Consensus), get the corresponding (Txs, Blocks, Consensus) and tell them to RemoteNode actor.
        /// </summary>
        /// <param name="payload">The payload containing the requested information.</param>
        private void OnGetDataMessageReceived(InvPayload payload)
        {
            var notFound = new List<UInt256>();
            foreach (UInt256 hash in payload.Hashes.Where(p => sentHashes.Add(p)))
            {
                switch (payload.Type)
                {
                    case InventoryType.TX:
                        Transaction tx = Blockchain.Singleton.GetTransaction(hash);
                        if (tx != null)
                            EnqueueMessage(Message.Create(MessageCommand.Transaction, tx));
                        else
                            notFound.Add(hash);
                        break;
                    case InventoryType.Block:
                        Block block = Blockchain.Singleton.GetBlock(hash);
                        if (block != null)
                        {
                            if (bloom_filter == null)
                            {
                                EnqueueMessage(Message.Create(MessageCommand.Block, block));
                            }
                            else
                            {
                                BitArray flags = new BitArray(block.Transactions.Select(p => bloom_filter.Test(p)).ToArray());
                                EnqueueMessage(Message.Create(MessageCommand.MerkleBlock, MerkleBlockPayload.Create(block, flags)));
                            }
                        }
                        else
                        {
                            notFound.Add(hash);
                        }
                        break;
                    default:
                        if (Blockchain.Singleton.RelayCache.TryGet(hash, out IInventory inventory))
                            EnqueueMessage(Message.Create((MessageCommand)payload.Type, inventory));
                        break;
                }
            }

            if (notFound.Count > 0)
            {
                foreach (InvPayload entry in InvPayload.CreateGroup(payload.Type, notFound.ToArray()))
                    EnqueueMessage(Message.Create(MessageCommand.NotFound, entry));
            }
        }

        /// <summary>
        /// Will be triggered when a MessageCommand.GetHeaders message is received.
        /// Tell the specified number of blocks' headers starting with the requested IndexStart to RemoteNode actor.
        /// A limit set by HeadersPayload.MaxHeadersCount is also applied to the number of requested Headers, namely payload.Count.
        /// </summary>
        /// <param name="payload">A GetBlocksPayload including start block index and number of blocks' headers requested.</param>
        private void OnGetHeadersMessageReceived(GetBlockByIndexPayload payload)
        {
            uint index = payload.IndexStart;
            uint count = payload.Count == -1 ? HeadersPayload.MaxHeadersCount : (uint)payload.Count;
            if (index > Blockchain.Singleton.HeaderHeight)
                return;
            List<Header> headers = new List<Header>();
            for (uint i = 0; i < count; i++)
            {
                var header = Blockchain.Singleton.GetHeader(index + i);
                if (header == null) break;
                headers.Add(header);
            }
            if (headers.Count == 0) return;
            EnqueueMessage(Message.Create(MessageCommand.Headers, HeadersPayload.Create(headers.ToArray())));
        }

        private void OnInventoryReceived(IInventory inventory)
        {
            pendingKnownHashes.Remove(inventory.Hash);
            switch (inventory)
            {
                case Transaction transaction:
                    system.Consensus?.Tell(transaction);
                    break;
                case Block block:
                    if (block.Index > Blockchain.Singleton.Height + InvPayload.MaxHashesCount) return;
                    UpdateLastBlockIndex(block.Index, false);
                    break;
            }
            knownHashes.Add(inventory.Hash);
            system.TaskManager.Tell(inventory);
            system.Blockchain.Tell(inventory);
        }

        private void OnInvMessageReceived(InvPayload payload)
        {
            UInt256[] hashes = payload.Hashes.Where(p => !pendingKnownHashes.Contains(p) && !knownHashes.Contains(p) && !sentHashes.Contains(p)).ToArray();
            if (hashes.Length == 0) return;
            switch (payload.Type)
            {
                case InventoryType.Block:
                    using (SnapshotView snapshot = Blockchain.Singleton.GetSnapshot())
                        hashes = hashes.Where(p => !snapshot.ContainsBlock(p)).ToArray();
                    break;
                case InventoryType.TX:
                    using (SnapshotView snapshot = Blockchain.Singleton.GetSnapshot())
                        hashes = hashes.Where(p => !snapshot.ContainsTransaction(p)).ToArray();
                    break;
            }
            if (hashes.Length == 0) return;
            foreach (UInt256 hash in hashes)
                pendingKnownHashes.Add((hash, TimeProvider.Current.UtcNow));
            system.TaskManager.Tell(new TaskManager.NewTasks { Payload = InvPayload.Create(payload.Type, hashes) });
        }

        private void OnMemPoolMessageReceived()
        {
            foreach (InvPayload payload in InvPayload.CreateGroup(InventoryType.TX, Blockchain.Singleton.MemPool.GetVerifiedTransactions().Select(p => p.Hash).ToArray()))
                EnqueueMessage(Message.Create(MessageCommand.Inv, payload));
        }

        private void OnPingMessageReceived(PingPayload payload)
        {
            UpdateLastBlockIndex(payload.LastBlockIndex, true);
            EnqueueMessage(Message.Create(MessageCommand.Pong, PingPayload.Create(Blockchain.Singleton.Height, payload.Nonce)));
        }

        private void OnPongMessageReceived(PingPayload payload)
        {
            UpdateLastBlockIndex(payload.LastBlockIndex, true);
        }

        private void OnVerackMessageReceived()
        {
            verack = true;
            system.TaskManager.Tell(new TaskManager.Register { Version = Version });
            CheckMessageQueue();
        }

        private void OnVersionMessageReceived(VersionPayload payload)
        {
            Version = payload;
            foreach (NodeCapability capability in payload.Capabilities)
            {
                switch (capability)
                {
                    case FullNodeCapability fullNodeCapability:
                        IsFullNode = true;
                        LastBlockIndex = fullNodeCapability.StartHeight;
                        break;
                    case ServerCapability serverCapability:
                        if (serverCapability.Type == NodeCapabilityType.TcpServer)
                            ListenerTcpPort = serverCapability.Port;
                        break;
                }
            }
            if (!LocalNode.Singleton.AllowNewConnection(Self, this))
            {
                Disconnect(true);
                return;
            }
            SendMessage(Message.Create(MessageCommand.Verack));
        }

        private void RefreshPendingKnownHashes()
        {
            while (pendingKnownHashes.Count > 0)
            {
                var (_, time) = pendingKnownHashes[0];
                if (TimeProvider.Current.UtcNow - time <= PendingTimeout)
                    break;
                pendingKnownHashes.RemoveAt(0);
            }
        }

        private void UpdateLastBlockIndex(uint lastBlockIndex, bool requestTasks)
        {
            if (lastBlockIndex > LastBlockIndex)
            {
                LastBlockIndex = lastBlockIndex;
                system.TaskManager.Tell(new TaskManager.Update { LastBlockIndex = LastBlockIndex, RequestTasks = requestTasks });
            }
        }
    }
}

{'repo_name': 'neo-project/neo', 'stars': '2992', 'repo_language': 'C#', 'file_name': 'UT_ReflectionCache.cs', 'mime_type': 'text/plain', 'hash': 833022143093077378, 'source_dataset': 'data'}


// Testcase for value-initialization in new-expressions.
// { dg-do run }

#include <stdlib.h>
#include <string.h>

// Make sure that we return memory that isn't already set to 0.
void *operator new(size_t s)
{
  void *p = malloc (s);
  memset (p, 42, s);
  return p;
}

struct A { A() {} ~A() {} };
struct B { A a; int i; };

int main()
{
  B *p = new B();
  if (p->i != 0)
    abort();

  p = new B[2]();
  if (p[0].i != 0 || p[1].i != 0)
    abort();

  B(*p2)[2] = new B[2][2]();
  if (p2[0][0].i != 0 || p2[0][1].i != 0)
    abort();
}

{'repo_name': 'kframework/c-semantics', 'stars': '211', 'repo_language': 'C', 'file_name': 'ClangKast.cc', 'mime_type': 'text/x-c++', 'hash': -143568316907518379, 'source_dataset': 'data'}