text:
/***************************************************************************

    Space Firebird hardware

****************************************************************************/

#include "emu.h"
#include "cpu/mcs48/mcs48.h"
#include "sound/dac.h"
#include "sound/samples.h"
#include "includes/spacefb.h"

READ8_HANDLER( spacefb_audio_p2_r )
{
	spacefb_state *state = space->machine().driver_data<spacefb_state>();
	return (state->m_sound_latch & 0x18) << 1;
}

READ8_HANDLER( spacefb_audio_t0_r )
{
	spacefb_state *state = space->machine().driver_data<spacefb_state>();
	return state->m_sound_latch & 0x20;
}

READ8_HANDLER( spacefb_audio_t1_r )
{
	spacefb_state *state = space->machine().driver_data<spacefb_state>();
	return state->m_sound_latch & 0x04;
}

WRITE8_HANDLER( spacefb_port_1_w )
{
	spacefb_state *state = space->machine().driver_data<spacefb_state>();
	device_t *samples = space->machine().device("samples");

	cputag_set_input_line(space->machine(), "audiocpu", 0, (data & 0x02) ? CLEAR_LINE : ASSERT_LINE);

	/* enemy killed */
	if (!(data & 0x01) && (state->m_sound_latch & 0x01))  sample_start(samples, 0,0,0);

	/* ship fire */
	if (!(data & 0x40) && (state->m_sound_latch & 0x40))  sample_start(samples, 1,1,0);

	/*
     *  Explosion Noise
     *
     *  Actual sample has a bit of attack at the start, but these doesn't seem to be an easy way
     *  to play the attack part, then loop the middle bit until the sample is turned off
     *  Fortunately it seems like the recorded sample of the spaceship death is the longest the sample plays for.
     *  We loop it just in case it runs out
     */
	if ((data & 0x80) != (state->m_sound_latch & 0x80))
	{
		if (data & 0x80)
			/* play decaying noise */
			sample_start(samples, 2,3,0);
		else
			/* start looping noise */
			sample_start(samples, 2,2,1);
	}

	state->m_sound_latch = data;
}

static const char *const spacefb_sample_names[] =
{
	"*spacefb",
	"ekilled.wav",
	"shipfire.wav",
	"explode1.wav",
	"explode2.wav",
	0
};

static const samples_interface spacefb_samples_interface =
{
	3,
	spacefb_sample_names
};

MACHINE_CONFIG_FRAGMENT( spacefb_audio )
	MCFG_SPEAKER_STANDARD_MONO("mono")

	MCFG_SOUND_ADD("dac", DAC, 0)
	MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.50)

	MCFG_SOUND_ADD("samples", SAMPLES, 0)
	MCFG_SOUND_CONFIG(spacefb_samples_interface)
	MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
MACHINE_CONFIG_END


text:
package org.kevoree.modeling.ast.impl;

import org.kevoree.modeling.ast.KDependency;

public class Dependency implements KDependency {

    private final String query;

    public Dependency(String query) {
        this.query = query;
    }

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

redpajama_set_name: RedPajamaGithub


text:
package com.not2excel.api.util;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Richmond Steele
 * @since 12/16/13
 * All rights Reserved
 * Please read included LICENSE file
 */
public class Colorizer
{
    private static final int                    MAX_SIZE         = 1000;
    private static final Map<String, String>    colorizedStrings = new ConcurrentHashMap<String, String>();
    private static final Map<String, ChatColor> customColors     = new ConcurrentHashMap<String, ChatColor>();

    static
    {
        addColor("purple", ChatColor.LIGHT_PURPLE);
        addColor("cyan", ChatColor.AQUA);
        addColor("dark_cyan", ChatColor.DARK_AQUA);
    }

    /**
     * Converts simple colors into ChatColor values
     * eg. <blue>test => §9test (actually its technically ChatColor.BLUE, not §9. despite them being the same)
     *
     * @param string
     *         input string
     * @return string with proper ChatColor inputted
     */
    public static String formatColors(String string)
    {
        synchronized (colorizedStrings)
        {
            if (colorizedStrings.containsKey(string))
            {
                return colorizedStrings.get(string);
            }
            else
            {
                Pattern p = Pattern.compile("<([a-zA-Z_]*)>");
                Matcher m = p.matcher(string);
                String colorized = string;
                while (m.find())
                {
                    colorized = colorized.replaceFirst(p.pattern(), convertToColorCode(m.group(1)));
                }
                colorizedStrings.put(string, colorized);
                if(colorizedStrings.size() > MAX_SIZE)
                {
                    reduceSize();
                }
                return colorized;
            }
        }
    }

    /**
     * Formats string and colorizes it
     *
     * @param string
     *         String containing colors and %s %d etc.
     * @param objects
     *         Objects to be formatted into the string
     * @return formatted and colorized String
     */
    public static String formatString(String string, Object... objects)
    {
        string = String.format(string, objects);
        return formatColors(string);
    }

    public static void send(CommandSender sender, String string, Object... objects)
    {
        sender.sendMessage(formatString(string, objects));
    }

    public static void addColor(String s, ChatColor color)
    {
        synchronized (customColors)
        {
            if(!customColors.containsKey(s.toUpperCase()))
            {
                customColors.put(s.toUpperCase(), color);
            }
        }
    }

    public static void removeColor(String s)
    {
        synchronized (customColors)
        {
            if(customColors.containsKey(s.toUpperCase()))
            {
                customColors.remove(s.toUpperCase());
            }
        }
    }

    /**
     * Wrapper for ChatColor.valueOf()
     *
     * @param s
     *         string to get color of
     * @return ChatColor char
     */
    private static String convertToColorCode(String s)
    {
        synchronized (customColors)
        {
            if(customColors.containsKey(s.toUpperCase()))
            {
                return customColors.get(s.toUpperCase()).toString();
            }
        }
        try
        {
            return ChatColor.valueOf(s.toUpperCase()).toString();
        }
        catch(Exception e)
        {
            return "<" + s + ">";
        }
    }

    private static void reduceSize()
    {
        synchronized (colorizedStrings)
        {
            Iterator<String> iterator = colorizedStrings.values().iterator();
            for(int i = colorizedStrings.size() / 10; i >= 0; --i)
            {
                if(!iterator.hasNext())
                {
                    break;
                }
                iterator.next();
                iterator.remove();
            }
        }
    }
}


text:
function P = ccemsi_p(ccemsi_file);
%  P = ccemsi_p(ccemsi_file)
%   Parameter initialisation of model ccemsi
%   P   Parameter list
%
% Stimela, 2004

% © Kim van Schagen,

%Check if given file exists
ccemsi_fileEcht = chckFile(ccemsi_file);
if ~ccemsi_fileEcht
    error(['Cannot find parameterfile ''' ccemsi_file ''' .']);
else
  %Get Parameter data (evaluate entries, and limits) and return real data
  P = st_getPdata(ccemsi_fileEcht, 'ccemsi');
end

%%% MODEL-SPECIFIC => %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Fill parameter list with precalculated parameters
% eg. P.CalData = P.Ex1*P.Ex2;

%%% <= MODEL-SPECIFIC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


text:
  /*--------------------------------------:noTabs=true:tabSize=2:indentSize=2:--
    --  COMPATABILITY FILE
    --  htmlarea.js is now XinhaCore.js
    --
    --  $HeadURL: http://svn.xinha.python-hosting.com/trunk/htmlarea.js $
    --  $LastChangedDate: 2007-01-15 15:28:57 +0100 (Mo, 15 Jan 2007) $
    --  $LastChangedRevision: 659 $
    --  $LastChangedBy: gogo $
    --------------------------------------------------------------------------*/

if ( typeof _editor_url == "string" )
{
  // Leave exactly one backslash at the end of _editor_url
  _editor_url = _editor_url.replace(/\x2f*$/, '/');
}
else
{
  alert("WARNING: _editor_url is not set!  You should set this variable to the editor files path; it should preferably be an absolute path, like in '/htmlarea/', but it can be relative if you prefer.  Further we will try to load the editor files correctly but we'll probably fail.");
  _editor_url = '';
}

document.write('<script type="text/javascript" src="'+_editor_url+'XinhaCore.js"></script>');


text:
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
//   contributors may be used to endorse or promote products derived from this
//   software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//

using System;
using JetBrains.Annotations;

namespace NLog.Config
{
    /// <summary>
    /// Failed to resolve the interface of service type
    /// </summary>
    public sealed class NLogDependencyResolveException : Exception
    {
        /// <summary>
        /// Typed we tried to resolve
        /// </summary>
        [NotNull] public Type ServiceType { get; }

        /// <inheritdoc/>
        public NLogDependencyResolveException(string message, [NotNull] Type serviceType) : base(CreateFullMessage(serviceType, message))
        {
            ServiceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
        }

        /// <inheritdoc/>
        public NLogDependencyResolveException(string message, Exception innerException, [NotNull] Type serviceType) : base(CreateFullMessage(serviceType, message), innerException)
        {
            ServiceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
        }

        private static string CreateFullMessage(Type typeToResolve, string message) => $"Cannot resolve the type: '{typeToResolve.Name}'. {message}".Trim();
    }
}


text:
import shapefile, sys
import Image, ImageDraw
import argparse

def longest_len(list):
  return len(max(list, key=len))
def clear_file():
  with open(args['output'] + '.txt', 'w') as text_file:
      text_file.write('')
def print_or_fout(str):
  if args['output'] != False:
    with open(args['output'] + '.txt', 'a') as text_file:
      text_file.write(str)
  else:
    sys.stdout.write(str)
def show_attribute_columns(r,tab_lens=False):
  fields=[y[0] for y in r.fields if y[0] !='DeletionFlag']
  if (tab_lens == False):
    tab_lens = [len(x)+2 for x in fields]
  for i, f in enumerate(fields):
    print_or_fout ((f+"\t").expandtabs(tab_lens[i]))
  print_or_fout("\n")
def show_attribute_table(r):

  recs = r.records()
  recs.append([y[0] for y in r.fields if y[0] !='DeletionFlag'])
  tab_lens = [longest_len(y)+2 for y in [list(x) for x in zip(*recs)]]
  show_attribute_columns(r,tab_lens)
  for rec in r.records():
    for i, item in enumerate(rec):
      print_or_fout((item+"\t").expandtabs(tab_lens[i]))
    print_or_fout("\n")

def process(r):

  iwidth = args['width']
  # end if

  filter_idxs = []
  groupby_idxs = []
  if len(args['filter']):
    filter_keys = [x[0] for x in args['filter'] if x[0][0] != '[']
    groupby_keys = [x[0][1:-1] for x in args['filter'] if x[0][0] == '[']
    vals = [x[1] for x in args['filter'] if x[0][0] != '[' ]
    fields=[y[0] for y in r.fields]
    filter_idxs =[fields.index(x)-1 for x in filter_keys if x in fields]
    groupby_idxs =[fields.index(x)-1 for x in groupby_keys if x in fields]
    if len(groupby_idxs) >0: #group by active
      group_bys = list(set([x[y] for x in r.records() for y in groupby_idxs if x[y].replace(' ','') != ''])) #unique values in group by clause
    else:
      group_bys = ['']
  else:
    group_bys = ['']
    # end if
  # end if

  for group_by in group_bys:
    feature_counter = 0
    if group_by != '':
      sys.stdout.write ("group by "+group_by +'.....')
    xys=[]
    boxes = []
    for sr in r.shapeRecords():
      if len(filter_idxs)>0:
        n = len([i for i,x in enumerate(filter_idxs) if sr.record[x]==vals[i]])
        if n ==0:
          continue
        # end if
      # end if
      if group_by != '':
        n = len([i for i,x in enumerate(groupby_idxs) if sr.record[x]==group_by])
        if n ==0:
          continue
        # end if
      # end if
      feature_counter = feature_counter + 1
      shape=sr.shape
      boxes.append(shape.bbox)
      xy = []
      for x,y in shape.points:
        xy.append((x,y))
      xys.append(xy)

    print "features: "+str(feature_counter)
    nbbox = boxes[0]

    for bbox in boxes:
      if bbox[2] > nbbox[2]:
      # end if

        nbbox[2] = bbox[2]
      # end if

      if bbox[3] > nbbox[3]:
      # end if

        nbbox[3] = bbox[3]
      # end if

      if bbox[0] < nbbox[0]:
      # end if

        nbbox[0] = bbox[0]
      # end if

      if bbox[1] < nbbox[1]:
      # end if

        nbbox[1] = bbox[1]
      # end if
    # end for

    bbox=nbbox
    xdist = bbox[2] - bbox[0]
    ydist = bbox[3] - bbox[1]
    ratio=xdist/ydist
    iheight = int(iwidth/ratio)
    xratio = iwidth/xdist
    yratio = iheight/ydist

    img = Image.new("RGB", (iwidth, iheight), "white")
    img2 = Image.new("RGB", (iwidth, iheight), "white")
    transparent_area = (0,0,iwidth,iheight)

    mask=Image.new('L', (iwidth, iheight), color=255)
    draw=ImageDraw.Draw(mask)
    draw.rectangle(transparent_area, fill=0)
    img.putalpha(mask)
    img2.putalpha(mask)

    draw = ImageDraw.Draw(img)
    draw2 = ImageDraw.Draw(img2)

    for pts in xys:
      pixels2 = []
      for x,y in pts:
        px = int(iwidth - ((bbox[2] - x) * xratio))
        py = int((bbox[3] - y) * yratio)
        pixels2.append((px,py))
      draw.polygon(pixels2, outline=args['stroke'], fill=args['fill'])
      if args['outline'] != False:
        draw2.polygon(pixels2, outline=args['outline'])

    img.save(args['output']+"_"+group_by+"_polygon.png")
    if args['outline'] != False:
      img2.save(args['output']+"_"+group_by+"_lines.png")
    # end if

parser = argparse.ArgumentParser(description="Produce .png image from shapefile. Optionally filter by attribute value(s).")

parser.add_argument('input' ,help='input filename (without .shp)')
parser.add_argument('-o','--output', default=False, required=False, help='output filename (without .png)')
parser.add_argument('-w', '--width', type=int, default=4333)
parser.add_argument('--fill', type=str, default='rgb(255, 255, 255)', help="polygon fill color. defaults to \"rgb(255, 255, 255)\"")
parser.add_argument('--stroke', type=str, default='rgb(255, 255, 255)', help="polygon stroke color. defaults to \"rgb(255, 255, 255)\"")
parser.add_argument('--outline', type=str, nargs="?", default=False, help="show outline. takes optional color parameter. defaults to \"rgb(0, 0, 0)\"")
parser.add_argument('-f',  '--filter', nargs='*', action='append', default=[], help='include features matched by this key-value pair')
parser.add_argument('--fields', default=False, action='store_true', help = 'output the attribute fields')
parser.add_argument('--table', default=False, action='store_true', help = 'output the attribute table')

args = vars(parser.parse_args())
if args['outline'] == False:
  args['outline'] = 'rgb(0, 0, 0)'

myshp = open(args['input']+".shp", "rb")
mydbf = open(args['input']+".dbf", "rb")
r = shapefile.Reader(shp=myshp, shx=None, dbf=mydbf)

if args['fields'] or args['table']:
  if args['output']:
    clear_file()
  if args['table']==False:
      tab_len = longest_len(fields=[y[0] for y in r.fields if y[0] !='DeletionFlag'])
  else:
      tab_len = longest_len([x for rec in r.records() for x in rec])
  if args['fields']:
    show_attribute_columns(r)
  if args['table']:
    show_attribute_table(r)
else:
  if args['output'] == False:
    parser.error('argument -o/--output is required')
  else:
    process(r)


text:
package com.whenling.module.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class SnServiceImpl implements SnService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public long nextValue(String type) {
		return stringRedisTemplate.execute((RedisCallback<Long>) action -> {
			byte[] typeKey = type.getBytes();
			return action.incr(typeKey);
		});
	}

}


text:
class AddUserIdToWardrobeItems < ActiveRecord::Migration[5.0]
  def change
    add_column :wardrobe_items, :user_id, :integer
  end
end


text:
using UnityEngine;

namespace DalLib.Math
{

    [System.Serializable]
    public class Vector2Int
    {

        [SerializeField]
        public int x;
        [SerializeField]
        public int y;

        /// <summary>
        /// Shorthand for writing Vector2Int(0,-1).
        /// </summary>
        public static Vector2Int down = new Vector2Int(0, -1);

        public static Vector2Int left = new Vector2Int(-1, 0);

        public static Vector2Int one = new Vector2Int(1, 1);

        public static Vector2Int right = new Vector2Int(1, 0);

        public static Vector2Int up = new Vector2Int(0, 1);

        public static Vector2Int zero = new Vector2Int(0, 0);

        public Vector2Int(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public Vector2 ToVector2()
        {
            return new Vector2(x, y);
        }

        public override string ToString()
        {
            return string.Format("({0}, {1})", x, y);
        }

        public bool Equals(Vector2Int other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return other.x == x && other.y == y;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            return obj.GetType() == typeof(Vector2Int) && Equals((Vector2Int)obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                return (x * 397) ^ y;
            }
        }

        public static bool operator ==(Vector2Int l, Vector2Int r)
        {
            return Equals(l, r);
        }

        public static bool operator !=(Vector2Int l, Vector2Int r)
        {
            return !Equals(l, r);
        }

        public static Vector2Int operator +(Vector2Int l, Vector2Int r)
        {
            return new Vector2Int(l.x + r.x, l.y + r.y);
        }

        public static Vector2Int operator -(Vector2Int l, Vector2Int r)
        {
            return new Vector2Int(l.x - r.x, l.y - r.y);
        }

        static public explicit operator Vector2(Vector2Int v2)
        {
            return new Vector2(v2.x, v2.y);
        }

        static public explicit operator Vector3(Vector2Int v2)
        {
            return new Vector3(v2.x, v2.y, 0f);
        }

        public float magnitude(Vector2Int v2)
        {
            return Mathf.Sqrt((v2.x * v2.x) + (v2.y * v2.y));
        }

        public int sqrMagnitude(Vector2Int v2)
        {
            return ((v2.x * v2.x) + (v2.y * v2.y));
        }
    }
}


text:
package org.kaazing.gateway.management.jmx;

import java.util.List;
import javax.management.ObjectName;
import org.kaazing.gateway.management.config.ClusterConfigurationBean;

public class ClusterConfigurationMXBeanImpl implements ClusterConfigurationMXBean {

    private final ObjectName name;
    private final ClusterConfigurationBean clusterConfigBean;

    public ClusterConfigurationMXBeanImpl(ObjectName name, ClusterConfigurationBean clusterConfigBean) {
        this.name = name;
        this.clusterConfigBean = clusterConfigBean;
    }

    @Override
    public String getName() {
        return clusterConfigBean.getName();
    }

    @Override
    public String getAccepts() {
        return stringifyList(clusterConfigBean.getAccepts());
    }

    @Override
    public String getConnects() {
        return stringifyList(clusterConfigBean.getConnects());
    }

    @Override
    public String getConnectOptions() {
        return clusterConfigBean.getConnectOptions();
    }

    public String stringifyList(List<String> values) {
        StringBuffer sb = new StringBuffer();
        if (values != null) {
            boolean first = true;
            for (String str : values) {
                if (!first) {
                    sb.append('\n');
                }
                sb.append(str);
                first = false;
            }
        }
        return sb.toString();
    }
}


text: synclient TouchpadOff=$(synclient -l | grep -c 'TouchpadOff.*=.*0')


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Storage;
using System.IO;
using System.Text.RegularExpressions;

namespace Lumia.Imaging.Extras.Tests
{
	public class KnownImage
	{
		public KnownImage(string path, Size size, ImageFormat imageFormat = ImageFormat.Jpeg)
		{
			Path = path;
			Size = size;
			ImageFormat = imageFormat;

			var regex = new Regex(@"(?<name>\w+)\.\w+?$", RegexOptions.IgnoreCase);
			var matches = regex.Matches(Path);
			Name = matches[0].Groups["name"].Value;
		}

		public Task<StorageFile> GetFileAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Package.Current.InstalledLocation.GetFileAsync(Path).AsTask(cancellationToken);
		}

		public async Task<StorageFileImageSource> GetImageSourceAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return new StorageFileImageSource(await GetFileAsync(cancellationToken).ConfigureAwait(false));
		}

		public async Task<StreamImageSource> GetStreamImageSourceAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			var storageFile = await GetFileAsync(cancellationToken).ConfigureAwait(false);
			var stream = await storageFile.OpenStreamForReadAsync().ConfigureAwait(false);
			return new StreamImageSource(stream);
		}

		public string Path { get; private set; }
		public Size Size { get; private set; }
		public ImageFormat ImageFormat { get; private set; }
		public string Name { get; private set; }
	}
}