text:
package com.juma.cannontoolbox;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.juma.cannontoolbox.R;
import com.juma.sdk.JumaDevice;
import com.juma.sdk.JumaDeviceCallback;
import com.juma.sdk.ScanHelper;
import com.juma.sdk.ScanHelper.ScanCallback;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class BarometerActivity extends Activity {

	private Spinner sp;
	private TableRow tb;
	private TextView tp,tc,tm;
	DecimalFormat df;
	private boolean back = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_barometer);
		df   = new DecimalFormat("######0.00");
		sp = (Spinner)findViewById(R.id.spinner1);
		tb = (TableRow)findViewById(R.id.tableRow1);
		tp = (TextView)findViewById(R.id.tp);
		tc = (TextView)findViewById(R.id.tc);
		tm = (TextView)findViewById(R.id.tm);
		tb.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onStop();
			}
		});
		setSpinner();

	}
	 @Override
	    protected void onStop() {
	        super.onStop();
	        back = true;
			// TODO Auto-generated method stub
			if(myDevice != null && myDevice.isConnected()){
				myDevice.send((byte)0x01, CannonToolboxActivity.hexToByte("00"));
				myDevice.disconnect();
			}
			if(scanner.isScanning()){
				scanner.stopScan();
			}
			finish();
	     }

	 private ScanHelper scanner;
		private JumaDevice myDevice;
		private boolean redata = true;
		private List<JumaDevice> deviceList = new ArrayList<JumaDevice>();
		private List<UUID> uuidList = new ArrayList<UUID>();
		private List<String> NameList = new ArrayList<String>();
		private ArrayAdapter<String> apName;
		private JumaDeviceCallback callback = new JumaDeviceCallback() {
			@Override
			public void onConnectionStateChange(int status,
					int newState) {
				// TODO Auto-generated method stub
				super.onConnectionStateChange(status, newState);
				if(newState == JumaDevice.STATE_CONNECTED && status == JumaDevice.SUCCESS){
					myDevice.send((byte)0x01, CannonToolboxActivity.hexToByte("02"));
					runOnUiThread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
						}});

				}else if (newState == JumaDevice.STATE_DISCONNECTED){
					myDevice = null;
					runOnUiThread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
							uuidList.clear();
							deviceList.clear();
							NameList.clear();
							apName.clear();
							apName.add("Choose Device");
							sp.setAdapter(apName);
							if(!back){
							scanner.startScan(null);
							}else{
								finish();
							}
						}});
				}
				}
			private int x = 0,y = 0;
			double t = 0,p = 0,h = 0;
			@Override
			public void onReceive(byte type, byte[] message) {
				// TODO Auto-generated method stub
				super.onReceive(type, message);
				if(redata){
					redata = false;
						x = 0;
						x |= message[0];
						x <<= 8;
						x |= (message[1]&0x00FF);
						x <<= 8;
						x |= (message[2]&0x0000FF);
						y = 0;
						y |= message[3];
						y <<= 8;
						y |= (message[4]&0x00FF);
						t = (double)y/100;
						p = (double)x/100;
						h = 18400*(1+t/273)*Math.log10(1027/p);

						runOnUiThread(new Runnable(){

							@Override
							public void run() {
								// TODO Auto-generated method stub
								tp.setText(p+"hPa");
								tc.setText(t+"¡æ");
								tm.setText(df.format(h)+"m");
								redata = true;
							}});
				}

			}

		};
		private ScanCallback scancallback = new ScanCallback() {

			@Override
			public void onScanStateChange(int status) {
				// TODO Auto-generated method stub
				if(status == ScanHelper.STATE_STOP_SCAN && !back){
					myDevice.connect(callback);
				}

			}

			@Override
			public void onDiscover(JumaDevice device, int arg1) {
				// TODO Auto-generated method stub
				if(!uuidList.contains(device.getUuid())){
					uuidList.add(device.getUuid());
					deviceList.add(device);
					NameList.add(device.getName());
					runOnUiThread(new Runnable(){

						@Override
						public void run() {
							// TODO Auto-generated method stub
							  apName.clear();
							  apName.add("Choose Device");
							  apName.addAll(NameList);
							  sp.setAdapter(apName);
						}

					});
				}
			}
		};

		@SuppressLint("HandlerLeak")
		public void setSpinner(){
			apName = new ArrayAdapter<String>(this,R.layout.message);
			apName.add("Choose Device");
			sp.setAdapter(apName);
			scanner = new ScanHelper(this, scancallback);
			sp.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {
					if(myDevice != null && myDevice.isConnected()){
						myDevice.send((byte)0x01, CannonToolboxActivity.hexToByte("00"));
						myDevice.disconnect();
					}else if(!apName.getItem(position).equals("Choose Device")){
					myDevice = deviceList.get(position-1);
					myDevice.connect(callback);
					}else{
						myDevice = null;
						}
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {

				}});
			scanner.startScan(null);
		}

		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// Inflate the menu; this adds items to the action bar if it is present.
			getMenuInflater().inflate(R.menu.magnetometer, menu);
			return true;
		}

	}


text:
package org.socraticgrid.hl7.services.orders.functional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.socraticgrid.hl7.services.orders.model.entity.Quantity;

public class TestHibernate {
	public static void main(String[] args) {
		// creating configuration object
		Configuration cfg=new Configuration();
		cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
		//creating session factory object
		SessionFactory factory=cfg.buildSessionFactory();
		//creating session object
		Session session=factory.openSession();
		//creating transaction object
		Transaction t=session.beginTransaction();
		Quantity quantity = new Quantity();
		quantity.setCode("KG");
		quantity.setUnits("KG");
		quantity.setValue("500");
		session.persist(quantity);
		t.commit();
		session.close();
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';

import { isNil } from '@llecoop/helpers';
import { select, Store } from '@ngrx/store';

import { Observable } from 'rxjs';
import { filter, first, map } from 'rxjs/operators';
import * as fromRoot from '../../store';

@Injectable()
export class IsAuthGuard implements CanActivate, CanActivateChild {
  constructor(
    private store: Store<fromRoot.RootState>,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return this.store.pipe(
      select(fromRoot.getIsAuthenticated),
      filter(auth => !isNil(auth)),
      first(),
      map(auth => {
        if (auth) {
          this.router.navigate([ '/' ]);
          return false;
        }
        return true;
      })
    );
  }

  canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    return this.canActivate(route, state);
  }
}


text:
using System;
using System.Globalization;
using System.IO;

namespace Syndll2.Data
{
    public class TechnicianModeSettings
    {
        private readonly byte _terminalId;
        private readonly SerialPortModes _serialPort0Mode;
        private readonly SerialPortModes _serialPort1Mode;
        private readonly SerialPortModes _serialPort2Mode;
        private readonly int _serialPort0BaudRate;
        private readonly int _serialPort1BaudRate;
        private readonly int _serialPort2BaudRate;
        private readonly bool _hasModem;
        private readonly byte _modemRingsToAnswer;
        private readonly NetworkCardTypes _networkCardType;

        public byte TerminalId
        {
            get { return _terminalId; }
        }

        public SerialPortModes SerialPort0Mode
        {
            get { return _serialPort0Mode; }
        }

        public SerialPortModes SerialPort1Mode
        {
            get { return _serialPort1Mode; }
        }

        public SerialPortModes SerialPort2Mode
        {
            get { return _serialPort2Mode; }
        }

        public int SerialPort0BaudRate
        {
            get { return _serialPort0BaudRate; }
        }

        public int SerialPort1BaudRate
        {
            get { return _serialPort1BaudRate; }
        }

        public int SerialPort2BaudRate
        {
            get { return _serialPort2BaudRate; }
        }

        public bool HasModem
        {
            get { return _hasModem; }
        }

        public byte ModemRingsToAnswer
        {
            get { return _modemRingsToAnswer; }
        }

        public NetworkCardTypes NetworkCardType
        {
            get { return _networkCardType; }
        }

        public override string ToString()
        {
            return string.Format("HPS{0:D2}{1}{2}{3}{4}{5}{6}{7}{8}",
                                 _terminalId,
                                 (byte)_serialPort0Mode,
                                 (byte)_serialPort1Mode,
                                 (byte)_serialPort2Mode,
                                 BaudRates.IndexOf(_serialPort0BaudRate),
                                 BaudRates.IndexOf(_serialPort1BaudRate),
                                 BaudRates.IndexOf(_serialPort2BaudRate),
                                 _hasModem ? _modemRingsToAnswer.ToString(CultureInfo.InvariantCulture) : "N",
                                 (char)_networkCardType
                );
        }

        public TechnicianModeSettings(byte terminalId = 0,
                                      SerialPortModes serialPort0Mode = SerialPortModes.Host,
                                      SerialPortModes serialPort1Mode = SerialPortModes.FingerprintUnit,
                                      SerialPortModes serialPort2Mode = SerialPortModes.Printer,
                                      int serialPort0BaudRate = 19200,
                                      int serialPort1BaudRate = 57600,
                                      int serialPort2BaudRate = 19200,
                                      bool hasModem = false,
                                      byte modemRingsToAnswer = 0,
                                      NetworkCardTypes networkCardType = NetworkCardTypes.F_Ethernet100Mbps)
        {
            if (terminalId > 31)
                throw new ArgumentException("Invalid Terminal ID.  Terminal ID should be 0 to 31.", "terminalId");
            _terminalId = terminalId;

            if (serialPort0Mode  != SerialPortModes.Host)
                throw new ArgumentException("Invalid mode for serial port 0.", "serialPort0Mode");
            _serialPort0Mode = serialPort0Mode;

            if (serialPort1Mode != SerialPortModes.FingerprintUnit && serialPort1Mode != SerialPortModes.CardReader)
                throw new ArgumentException("Invalid mode for serial port 1.", "serialPort1Mode");
            _serialPort1Mode = serialPort1Mode;

            if (serialPort2Mode != SerialPortModes.Printer && serialPort2Mode != SerialPortModes.CardReader)
                throw new ArgumentException("Invalid mode for serial port 2.", "serialPort2Mode");
            _serialPort2Mode = serialPort2Mode;

            if (!BaudRates.IsValid(serialPort0BaudRate))
                throw new ArgumentException("Invalid baud rate for serial port 0.", "serialPort0BaudRate");
            _serialPort0BaudRate = serialPort0BaudRate;

            if (!BaudRates.IsValid(serialPort1BaudRate))
                throw new ArgumentException("Invalid baud rate for serial port 1.", "serialPort1BaudRate");
            _serialPort1BaudRate = serialPort1BaudRate;

            if (!BaudRates.IsValid(serialPort2BaudRate))
                throw new ArgumentException("Invalid baud rate for serial port 2.", "serialPort2BaudRate");
            _serialPort2BaudRate = serialPort2BaudRate;

            _hasModem = hasModem;
            if (hasModem)
            {
                if (modemRingsToAnswer > 9)
                    throw new ArgumentException("Modem rings to answer must be 0 through 9", "modemRingsToAnswer");
                _modemRingsToAnswer = modemRingsToAnswer;
            }

            if (!Enum.IsDefined(typeof (NetworkCardTypes), networkCardType))
                throw new ArgumentException("Invalid network card type.", "networkCardType");
            _networkCardType = networkCardType;
        }

        // Sample Raw Data  C = command, T = terminal id, CCCC = CRC code
        // Only the Data field should be passed in.
        // S0HPG00012464NF0<:3>
        // CT01234567890123CCCC
        //   0         1

        // Data Field Breakdown
        // HPG 00 0 1 2 4 6 4 N F 0

        internal static TechnicianModeSettings Parse(string data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            const int expectedLength = 14;
            if (data.Length != expectedLength)
                throw new ArgumentException(
                    string.Format(
                        "Technician mode settings data should be exactly {0} characters, and you passed {1} characters.  " +
                        "Do not pass the command, terminal id, or CRC here.", expectedLength, data.Length),
                    "data");

            return new TechnicianModeSettings(data);
        }

        private TechnicianModeSettings(string data)
        {
            var subcode = data.Substring(0, 3);
            if (subcode != "HPG")
                throw new InvalidDataException(
                    string.Format("Expected sub-code of \"{0}\" but got \"{1}\".", "HPG", subcode));

            if (!byte.TryParse(data.Substring(3, 2), NumberStyles.None, CultureInfo.InvariantCulture, out _terminalId))
                throw new InvalidDataException("Couldn't parse terminal id from technician mode settings data.");

            byte b;
            if (!byte.TryParse(data.Substring(5, 1), NumberStyles.None, CultureInfo.InvariantCulture, out b))
                throw new InvalidDataException("Couldn't parse serial port 0 mode from technician mode settings data.");
            _serialPort0Mode = (SerialPortModes)b;

            if (!byte.TryParse(data.Substring(6, 1), NumberStyles.None, CultureInfo.InvariantCulture, out b))
                throw new InvalidDataException("Couldn't parse serial port 1 mode from technician mode settings data.");
            _serialPort1Mode = (SerialPortModes)b;

            if (!byte.TryParse(data.Substring(7, 1), NumberStyles.None, CultureInfo.InvariantCulture, out b))
                throw new InvalidDataException("Couldn't parse serial port 2 mode from technician mode settings data.");
            _serialPort2Mode = (SerialPortModes)b;

            if (!byte.TryParse(data.Substring(8, 1), NumberStyles.None, CultureInfo.InvariantCulture, out b))
                throw new InvalidDataException("Couldn't parse serial port 0 baud rate from technician mode settings data.");
            _serialPort0BaudRate = BaudRates.Get(b);

            if (!byte.TryParse(data.Substring(9, 1), NumberStyles.None, CultureInfo.InvariantCulture, out b))
                throw new InvalidDataException("Couldn't parse serial port 1 baud rate from technician mode settings data.");
            _serialPort1BaudRate = BaudRates.Get(b);

            if (!byte.TryParse(data.Substring(10, 1), NumberStyles.None, CultureInfo.InvariantCulture, out b))
                throw new InvalidDataException("Couldn't parse serial port 2 baud rate from technician mode settings data.");
            _serialPort2BaudRate = BaudRates.Get(b);

            _hasModem = data[11] != 'N';
            if (_hasModem)
            {
                if (!byte.TryParse(data.Substring(11, 1), NumberStyles.None, CultureInfo.InvariantCulture, out _modemRingsToAnswer))
                    throw new InvalidDataException("Couldn't parse modem rings to answer from technician mode settings data.");
            }

            _networkCardType = (NetworkCardTypes)data[12];
        }
    }
}


text:
define mw_prefix='{$wgDBprefix}';

ALTER TABLE &mw_prefix.page ADD page_links_updated TIMESTAMP(6) WITH TIME ZONE;


text:
package org.openkilda.tools.maxinet;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "name",
    "pos",
    "type"
    })
public class Host implements Node {

	@JsonProperty("name")
	private String name;

	@JsonProperty("pos")
	private String pos;

	@JsonProperty("type")
	private NodeType type;

	public Host() {
		this.type = NodeType.HOST;
	}

	public Host(String name) {
		this(name, null);
	}

	public Host(String name, String pos) {
		super();
		this.name = name;
		this.pos = pos;
		this.type = NodeType.HOST;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPos() {
		return pos;
	}

	public void setPos(String pos) {
		this.pos = pos;
	}

	public void setType(NodeType type) {
		this.type = type;
	}

	@Override
	public NodeType getType() {
		return type;
	}

}


text:
__author__ = 'Sergey'

def comment_add(request,
                product_url,
                id,
                comment_id,
                template_name=u'show_comment_add.jinja2.html', ):
    from applications.comment.models import Comment
    error_message = None
    comment = None
    sessionid = request.COOKIES.get(u'sessionid', None, )
    if request.method == 'POST':
        POST_NAME = request.POST.get(u'POST_NAME', None, )
        if POST_NAME == 'comment_add':
            try:
                product_id = int(id, )
            except ValueError:
                error_message = u'Некорректно значение id продукта.'
            else:
                from applications.product.models import Product
                try:
                    product = Product.objects.get(pk=product_id, url=product_url, )
                except Product.DoesNotExist:
                    error_message = u'Отсутсвует Продукт с такими данными.'
                else:
                    commenter_name = request.POST.get(u'commenter_name', None, )
                    if not commenter_name:
                        error_message = u'Отсутсвует имя комментирующего.'
                    else:
                        comment = request.POST.get(u'comment', None, )
                        if not comment:
                            error_message = u'Отсутсвует комментарий'
                        else:
                            require_a_response = request.POST.get(u'require_a_response', None, )
                            if require_a_response:
                                email = request.POST.get(u'response', None, )
                            else:
                                email = None
                            if request.user.is_authenticated() and request.user.is_active:
                                user_id_ = request.session.get(u'_auth_user_id', None, )
                                from django.contrib.auth.models import User
                                user_obj = User.objects.get(pk=user_id_, )
                            else:
                                user_obj = None
                            rating = request.POST.get(u'rating', None, )
                            if rating == u'':
                                rating = None
                            else:
                                try:
                                    rating = int(rating, )
                                except ValueError:
                                    rating = None
                                    email = u'Неправильный рэйтинг товара.'
                            if comment_id:
                                try:
                                    comment_id = int(comment_id, )
                                except ValueError:
                                    comment_id = None
                                else:
                                    from applications.comment.models import Comment
                                    try:
                                        comment_id = Comment.objects.get(pk=comment_id, )
                                    except Comment.DoesNotExist:
                                        comment_id = None

                            comment = Comment.objects.create(comment_parent=comment_id,
                                                             content_type=product.content_type,
                                                             object_id=product.pk,
                                                             user=user_obj,
                                                             sessionid=sessionid,
                                                             name=commenter_name,
                                                             comment=comment,
                                                             require_a_response=require_a_response,
                                                             email=email,
                                                             rating=rating, )

    if isinstance(comment, Comment, ) and not error_message:
        """ Если комментарий добавлен в базу
        Говорим спасибо за оставленный комментарий или вопрос.
        Комментарий к товару появится на сайте после прохождения модерации Администрацией сайта """
        from django.shortcuts import redirect
        return redirect(to='comment_add_successfully', product_url=product_url, id=id, )

    from applications.utils.captcha.views import Captcha
    keys = Captcha(request, )
    from django.shortcuts import render_to_response
    from django.template import RequestContext
    response = render_to_response(template_name=template_name,
                                  dictionary={'error_message': error_message,
                                              'keys': keys, },
                                  context_instance=RequestContext(request, ),
                                  content_type='text/html', )
    return response

def comment_add_successfully(request,
                             product_url,
                             id,
                             template_name=u'show_comment_add_successfully.jinja2.html', ):
    from django.shortcuts import render_to_response
    from django.template import RequestContext
    response = render_to_response(template_name=template_name,
                                  # dictionary={'error_message': error_message, },
                                  #             # 'orders': orders, },  # 'html_text': html_text, },
                                  context_instance=RequestContext(request, ),
                                  content_type='text/html', )
    return response

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def order_edit_product_add(request,
               id,
               template_name=u'order/order_edit_product_add.jinja2.html', ):
    from django.shortcuts import redirect
    if id:
        try:
            order_id = int(id, )
        except ValueError:
            error_message = u'Некорректно введен номер заказа.'
            return redirect(to='order_search', )
        else:
            from applications.cart.models import Order
            try:
                order = Order.objects.get(pk=id, )
            except Order.DoesNotExist:
                error_message = u'В базе отсутсвует заказ с таким номером.'
                return redirect(to='order_search', )
    else:
        error_message = u'Отсутсвует номер заказа.'
        return redirect(to='order_search', )

#    from applications.static.models import Static
#    try:
#        page = Static.objects.get(url=static_page_url, )
#    except Static.DoesNotExist:
#        from django.http import Http404
#        raise Http404
#    import markdown
#    if page:
#        html_text = markdown.markdown(page.text, )
#    else:
#        html_text = None
    from django.shortcuts import render_to_response
    from django.template import RequestContext
    response = render_to_response(template_name=template_name,
                                  dictionary={'order_id': order_id,
                                              'order': order, },
                                  context_instance=RequestContext(request, ),
                                  content_type='text/html', )
    # from datetime import datetime
    # from applications.utils.datetime2rfc import datetime2rfc
    # response['Last-Modified'] = datetime2rfc(page.updated_at, )
    return response

@staff_member_required
def order_edit(request,
               id,
               template_name=u'order/order_edit.jinja2.html', ):
    from django.shortcuts import redirect
    if id:
        try:
            order_id = int(id, )
        except ValueError:
            error_message = u'Некорректно введен номер заказа.'
            return redirect(to='order_search', )
        else:
            from applications.cart.models import Order
            try:
                order = Order.objects.get(pk=id, )
            except Order.DoesNotExist:
                error_message = u'В базе отсутсвует заказ с таким номером.'
                return redirect(to='order_search', )
    else:
        error_message = u'Отсутсвует номер заказа.'
        return redirect(to='order_search', )

#    from applications.static.models import Static
#    try:
#        page = Static.objects.get(url=static_page_url, )
#    except Static.DoesNotExist:
#        from django.http import Http404
#        raise Http404
#    import markdown
#    if page:
#        html_text = markdown.markdown(page.text, )
#    else:
#        html_text = None
    from django.shortcuts import render_to_response
    from django.template import RequestContext
    response = render_to_response(template_name=template_name,
                                  dictionary={'order_id': order_id,
                                              'order': order, },
                                  context_instance=RequestContext(request, ),
                                  content_type='text/html', )
    # from datetime import datetime
    # from applications.utils.datetime2rfc import datetime2rfc
    # response['Last-Modified'] = datetime2rfc(page.updated_at, )
    return response


text:
"""Run a code linter and post the results as GitHub comments.

This script allows you to easily trigger a workflow on GitHub using an access
token. It uses the GitHub REST API documented here:
https://docs.github.com/en/rest/reference/actions#create-a-workflow-dispatch-event

Usage:
python lint_commenter.py -t github_token -p pr_number
       [-r git_repo_url] [-C curl_command] [-l lint_command]

If -r is unspecified, uses the current repo.
"""

import argparse
from html import escape
import json
import os
import re
import subprocess
import time
from unidiff import PatchSet
import urllib.parse

# Put any lint warnings you want to fully ignore into this list.
# (Include a short explanation of why.)
IGNORE_LINT_WARNINGS = [
  'build/include_subdir',   # doesn't know about our include paths
  'build/c++11',            # ignore "unapproved c++11 header" warning
  'readability/casting',    # allow non-C++ casts in rare occasions
  'runtime/references',     # allow non-const references
  'whitespace/indent',      # we rely on our code formatter for this...
  'whitespace/line_length'  # ...and for this
]
# Exclude files within the following paths (specified as regexes).
EXCLUDE_PATH_REGEX = [
  # These files are copied from an external repo and are outside our control.
  r'^analytics/ios_headers/',
  r'^ios_pod/swift_headers/'
]
# The linter gives every error a confidence score.
# 1 = It's most likely not really an issue.
# 5 = It's definitely an issue.
# Set this to 1 to show all warnings, or higher to show fewer warnings.
MINIMUM_CONFIDENCE = 1
LABEL_TO_SKIP_LINT = 'no-lint'
CPPLINT_FILTER = '-'+',-'.join(IGNORE_LINT_WARNINGS)
LINT_COMMENT_HEADER = '⚠ Lint warning: `'
LINT_COMMENT_FOOTER = '`'
HIDDEN_COMMENT_TAG = '<hidden value="cpplint-file-comment"></hidden>'

def main():
  # This script performs a number of steps:
  #
  # 1. Get the PR's diff to find the list of affected files and lines in the PR.
  #
  # 2. Run lint on all files in the PR. For each lint warning, check if it falls
  #    within the range of lines affected by the diff. Omit that warning if it
  #    doesn't fall in the affected lines.
  #
  # 3. Delete any prior lint warning comments posted by previous runs.
  #
  # 4. Post any lint warnings that fall within the range of the PR's diff.

  args = parse_cmdline_args()
  if args.repo is None:
      args.repo=subprocess.check_output(['git', 'config', '--get', 'remote.origin.url']).decode('utf-8').rstrip('\n').lower()
      if args.verbose:
        print('autodetected repo: %s' % args.repo)
  if not args.repo.startswith('https://github.com/'):
      print('Error, only https://github.com/ repositories are allowed.')
      exit(2)
  (repo_owner, repo_name) = re.match(r'https://github\.com/([^/]+)/([^/.]+)', args.repo).groups()

  # Get the head commit for the pull request.
  # GET /repos/{owner}/{repo}/pulls/{pull_number}
  request_url = 'https://api.github.com/repos/%s/%s/pulls/%s' % (repo_owner, repo_name, args.pr_number)
  header = 'Accept: application/vnd.github.VERSION.json'
  pr_data = json.loads(subprocess.check_output(
      [args.curl,
       '-s', '-X', 'GET',
       '-H', 'Accept: application/vnd.github.v3+json',
       '-H', 'Authorization: token %s' % args.token,
       request_url
      ] + ([] if not args.verbose else ['-v'])).decode('utf-8').rstrip('\n'))

  commit_sha = pr_data['head']['sha']
  if args.verbose:
    print('Commit sha:', commit_sha)

  skip_lint = False
  if 'labels' in pr_data:
    for label in pr_data['labels']:
      if label['name'] == LABEL_TO_SKIP_LINT:
        skip_lint = True
        break
  if skip_lint:
    print('PR #%s has "%s" label, skipping lint checks' % (args.pr_number, LABEL_TO_SKIP_LINT))
    exit(0)

  # Get the diff for the pull request.
  # GET /repos/{owner}/{repo}/pulls/{pull_number}
  request_url = 'https://api.github.com/repos/%s/%s/pulls/%s' % (repo_owner, repo_name, args.pr_number)
  header = 'Accept: application/vnd.github.VERSION.diff'

  if args.verbose:
    print('request_url: %s' % request_url)

  pr_diff = subprocess.check_output(
      [args.curl,
       '-s', '-o', '-', '-w', '\nHTTP status %{http_code}\n',
       '-X', 'GET',
       '-H', header,
       '-H', 'Authorization: token %s' % args.token,
       request_url
      ] + ([] if not args.verbose else ['-v'])).decode('utf-8')
  # Parse the diff to determine the whether each source line is touched.
  # Only lint lines that refer to parts of files that are diffed will be shown.
  # Information on what this means here:
  # https://docs.github.com/en/rest/reference/pulls#create-a-review-comment-for-a-pull-request
  valid_lines = {}
  file_list = []
  pr_patch = PatchSet(pr_diff)
  for pr_patch_file in pr_patch:
    # Skip files that only remove code.
    if pr_patch_file.removed and not pr_patch_file.added:
      continue
    # Skip files that match an EXCLUDE_PATH_REGEX
    excluded = False
    for exclude_regex in EXCLUDE_PATH_REGEX:
      if re.search(exclude_regex, pr_patch_file.path):
        excluded = True
        break
    if excluded: continue
    file_list.append(pr_patch_file.path)
    valid_lines[pr_patch_file.path] = set()
    for hunk in pr_patch_file:
      if hunk.target_length > 0:
        for line_number in range(
            hunk.target_start,
            hunk.target_start + hunk.target_length):
          # This line is modified by the diff, add it to the valid set of lines.
          valid_lines[pr_patch_file.path].add(line_number)

  # Now we also have a list of files in repo.
  try:
    lint_results=subprocess.check_output([
        args.lint_command,
        '--output=emacs',
        ('--filter=%s' % CPPLINT_FILTER),
        ('--repository=..')
    ] + file_list, stderr=subprocess.STDOUT).decode('utf-8').split('\n')
  except subprocess.CalledProcessError as e:
    # Nothing to do if there is an exception.
    lint_results=e.output.decode('utf-8').split('\n')

  all_comments = []
  for line in lint_results:
    # Match an output line from the linter, in this format:
    # path/to/file:line#: Lint message goes here [lint type] [confidence#]
    m = re.match(r'([^:]+):([0-9]+): *(.*[^ ]) +\[([^]]+)\] \[(\d+)\]$', line)
    if m:
      all_comments.append({
          'filename': m.group(1),
          'line': int(m.group(2)),
          'text': m.group(3),
          'type': m.group(4),
          'confidence': int(m.group(5)),
          'original_line': line})

  pr_comments = []
  for comment in all_comments:
    if comment['filename'] in valid_lines:
      if (comment['line'] in valid_lines[comment['filename']] and
          comment['confidence'] >= MINIMUM_CONFIDENCE):
        pr_comments.append(comment)
  if args.verbose:
    print('Got %d relevant lint comments' % len(pr_comments))

  # Next, get all existing review comments that we posted on the PR and delete them.
  comments_to_delete = []
  page = 1
  per_page=100
  keep_reading = True
  while keep_reading:
    if args.verbose:
      print('Read page %d of comments' % page)
    request_url = 'https://api.github.com/repos/%s/%s/pulls/%s/comments?per_page=%d&page=%d' % (repo_owner, repo_name, args.pr_number, per_page, page)
    comments = json.loads(subprocess.check_output([args.curl,
                                                   '-s', '-X', 'GET',
                                                   '-H', 'Accept: application/vnd.github.v3+json',
                                                   '-H', 'Authorization: token %s' % args.token,
                                                   request_url]).decode('utf-8').rstrip('\n'))
    for comment in comments:
      if HIDDEN_COMMENT_TAG in comment['body']:
        comments_to_delete.append(comment['id'])
    page = page + 1
    if len(comments) < per_page:
      # Stop once we're read less than a full page of comments.
      keep_reading = False
  if comments_to_delete:
    print('Delete previous lint comments:', comments_to_delete)
  for comment_id in comments_to_delete:
    # Delete all of these comments.
    # DELETE /repos/{owner}/{repo}/pulls/{pull_number}/comments
    request_url = 'https://api.github.com/repos/%s/%s/pulls/comments/%d' % (repo_owner, repo_name, comment_id)
    delete_output = subprocess.check_output([args.curl,
                                             '-s', '-X', 'DELETE',
                                             '-H', 'Accept: application/vnd.github.v3+json',
                                             '-H', 'Authorization: token %s' % args.token,
                                             request_url]).decode('utf-8').rstrip('\n')
  if len(pr_comments) > 0:
    comments_to_send = []
    for pr_comment in pr_comments:
      # Post each comment.
      # POST /repos/{owner}/{repo}/pulls/{pull_number}/comments
      request_url = 'https://api.github.com/repos/%s/%s/pulls/%s/reviews' % (repo_owner, repo_name, args.pr_number)
      comments_to_send.append({
          'body': (
              LINT_COMMENT_HEADER +
              pr_comment['text'] +
              LINT_COMMENT_FOOTER +
              HIDDEN_COMMENT_TAG +
              '<hidden value=%s></hidden>' % json.dumps(pr_comment['original_line'].replace('"','"'))
                   ),
          'path': pr_comment['filename'],
          'line': pr_comment['line'],
      })
      print(pr_comment['original_line'])

    request_body = {
        'commit_id': commit_sha,
        'event': 'COMMENT',
        'comments': comments_to_send
    }
    json_text = json.dumps(request_body)
    run_output = json.loads(subprocess.check_output([args.curl,
                                                     '-s', '-X', 'POST',
                                                     '-H', 'Accept: application/vnd.github.v3+json',
                                                     '-H', 'Authorization: token %s' % args.token,
                                                     request_url, '-d', json_text]
                                                    + ([] if not args.verbose else ['-v'])).decode('utf-8').rstrip('\n'))
    if 'message' in run_output and 'errors' in run_output:
      print('%s error when posting comments:\n%s' %
            (run_output['message'], '\n'.join(run_output['errors'])))
      if args.in_github_action:
        print('::error ::%s error when posting comments:%0A%s' %
              (run_output['message'], '%0A'.join(run_output['errors'])))
      exit(1)
    else:
      print('Posted %d lint warnings successfully' % len(pr_comments))

    if args.in_github_action:
      # Also post a GitHub log comment.
      lines = ['Found %d lint warnings:' % len(pr_comments)]
      for comment in pr_comments:
        lines.append(comment['original_line'])
      print('::warning ::%s' % '%0A'.join(lines))
  else:
    print('No lint warnings found.')
    exit(0)

def parse_cmdline_args():
  parser = argparse.ArgumentParser(description='Run cpplint on code and add results as PR comments.')
  parser.add_argument('-t', '--token', required=True, help='GitHub access token')
  parser.add_argument('-p', '--pr_number', required=True, help='Pull request number')
  parser.add_argument('-l', '--lint_command', help='Lint command to run', default='cpplint.py')
  parser.add_argument('-r', '--repo', metavar='URL', help='GitHub repo of the pull request, default is current repo')
  parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose mode')
  parser.add_argument('-C', '--curl', default='curl', metavar='COMMAND', help='Curl command to use for making request')
  parser.add_argument('-A', '--in_github_action', action='store_true', help='Enable special logging for GitHub actions')
  args = parser.parse_args()
  return args

if __name__ == '__main__':
  main()


text:
/*
 * Author: yuanzm
 * Last-Edit-Date: 2014/12/10
 */
;(function() {
	'use strict';
	var $sizeRadio = $("input[name='size']"),
 		$startButton = $("#startButton"),
		$stopButton = $("#stopButton"),
		$turboSpeed = $("#turboSpeed"),
		$displayarea = $("#displayarea"),
		$selectButton = $("#selectButton");

	$(function() {
		var ascii = new AsciiAnimation(ANIMATIONS);
		ascii.init();
	});
	function AsciiAnimation(asciiArray) {
		this.asciiArray = asciiArray;
		this.asciiIndex = '';
		this.speed = 200;
		this.currentIndex = -1;
		this.nextFrame = null;
		this.allFrames = null;
	}
	AsciiAnimation.prototype = {
		constructor: AsciiAnimation,
		fontArray: ['7pt', '12pt', '24pt'],
		init: function() {
			$stopButton.prop('disabled', true);
			this.bindHandler(this);
		},
		bindHandler: function(self) {
			$sizeRadio.bind('click', function() { self.changeFontSize(self); });
			$startButton.bind('click', function() { self.startAnimation(self); });
			$stopButton.bind('click', function() { self.stopAnimation(self); });
			$turboSpeed.bind('click', function() { self.speed = $turboSpeed.prop('checked') ? 50:200; });
		},
		changeFontSize: function(self) {
			$sizeRadio.each(function(index) {
				if($(this).prop('checked')) { $displayarea.css('font-size', self.fontArray[index])}
			})
		},
		chooseAnimation: function(self) {
			self.asciiIndex = self.asciiArray[$selectButton.val()];
			self.allFrames = self.asciiIndex.split("=====\n");
		},
		startAnimation: function(self) {
			self.chooseAnimation(self);
			if (self.allFrames != '') {
				self.actionAnimation(self, 0);
				$stopButton.prop('disabled', false);
				$startButton.prop('disabled', true);
				$selectButton.prop('disabled', true);
			}
		},
		stopAnimation: function(self) {
			clearTimeout(self.nextFrame);
			$displayarea.val(self.asciiIndex);
			$stopButton.prop('disabled', true);
			$startButton.prop('disabled', false);
			$selectButton.prop('disabled', false);
		},
		actionAnimation: function(self, index) {
			self.currentIndex = index < self.allFrames.length - 1?(index + 1):0;
			$displayarea.val(self.allFrames[index]);
			self.nextFrame = setTimeout(self.actionAnimation, self.speed, self, self.currentIndex);
		}
	}
})()


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

namespace ShadowsOfShadows.Items
{
    [ItemType(ItemType.Armor)]
    public abstract class HeadArmor : Wearable
    {
        public int DP { get; set; }

        protected HeadArmor() : base("Head Armor") { }

        protected HeadArmor(String name, int dp) : base(name, "Defence Power " + dp.ToString() + "\n")
        {
            DP = dp;
        }

        public override void Equip()
        {
            Screen.MainConsole.Player.DefencePower += DP;
        }

        public override void UnEquip()
        {
            Screen.MainConsole.Player.DefencePower -= DP;
        }

        public override bool IsLike(Item item)
        {
            return (item is HeadArmor);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent" >

  <ListView
      android:id="@+id/activity_log"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="40dp">
  </ListView>
</FrameLayout>


text:
<?php

namespace Fd\TablaBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="grupo_etario")
 * @ORM\Entity(repositoryClass="Fd\TablaBundle\Repository\GrupoEtarioRepository")
 */
class GrupoEtario {

    /**
     *
     * @ORM\Column(name = "id", type = "integer", nullable = false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy = "AUTO")
     */
    private $id;
    /**
     * @var string $nombre
     *
     * @ORM\Column(type="string", length=1, nullable=false)
     */
    private $codigo;

    /**
     *
     * @ORM\Column(type="string", length=35, nullable=false)
     */
    private $descripcion;
    /**
     * @ORM\Column(type="integer", nullable=false)
     */
    private $orden;

    public function __toString() {
        return $this->getDescripcion();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set codigo
     *
     * @param string $codigo
     * @return GrupoEtario
     */
    public function setCodigo($codigo)
    {
        $this->codigo = $codigo;

        return $this;
    }

    /**
     * Get codigo
     *
     * @return string
     */
    public function getCodigo()
    {
        return $this->codigo;
    }

    /**
     * Set descripcion
     *
     * @param string $descripcion
     * @return GrupoEtario
     */
    public function setDescripcion($descripcion)
    {
        $this->descripcion = $descripcion;

        return $this;
    }

    /**
     * Get descripcion
     *
     * @return string
     */
    public function getDescripcion()
    {
        return $this->descripcion;
    }

    /**
     * Set orden
     *
     * @param integer $orden
     * @return GrupoEtario
     */
    public function setOrden($orden)
    {
        $this->orden = $orden;

        return $this;
    }

    /**
     * Get orden
     *
     * @return integer
     */
    public function getOrden()
    {
        return $this->orden;
    }
}


text:
package org.springframework.cloud.dataflow.server.local.security;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;

import org.springframework.cloud.dataflow.server.local.LocalDataflowResource;
import org.springframework.data.authentication.UserCredentials;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.cloud.dataflow.server.local.security.SecurityTestUtils.basicAuthorizationHeader;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests the root URL when security with file-based user list is enabled.
 *
 * @author Gunnar Hillert
 * @author David Turanski
 */
public class LocalServerSecurityRootWithUsersFileTests {

	private final static LocalDataflowResource localDataflowResource = new LocalDataflowResource(
			"classpath:org/springframework/cloud/dataflow/server/local/security/fileBasedUsers.yml");

	@ClassRule
	public static TestRule springDataflowAndLdapServer = RuleChain.outerRule(localDataflowResource);

	private static UserCredentials viewOnlyUser = new UserCredentials("bob", "bobspassword");
	private static UserCredentials fullUser = new UserCredentials("fulluser", "fullpassword");

	@Test
	public void testAccessRootUrlAndCheckAllLinksWithFullUser() throws Exception {
		localDataflowResource.getMockMvc()
				.perform(get("/").header("Authorization", basicAuthorizationHeader(fullUser.getUsername(), fullUser.getPassword()))).andDo(print())
				.andExpect(status().isOk())
				.andExpect(jsonPath("$._links.*", hasSize(38)))
				.andExpect(jsonPath("$._links.dashboard.href", is("http://localhost/dashboard")))
				.andExpect(jsonPath("$._links.streams/definitions.href", is("http://localhost/streams/definitions")))
				.andExpect(jsonPath("$._links.streams/definitions/definition.href", is("http://localhost/streams/definitions/{name}")))
				.andExpect(jsonPath("$._links.streams/deployments.href", is("http://localhost/streams/deployments")))
				.andExpect(jsonPath("$._links.streams/deployments/deployment.href", is("http://localhost/streams/deployments/{name}")))
				.andExpect(jsonPath("$._links.streams/validation.href", is("http://localhost/streams/validation/{name}")))
				.andExpect(jsonPath("$._links.runtime/apps.href", is("http://localhost/runtime/apps")))
				.andExpect(jsonPath("$._links.runtime/apps/app.href", is("http://localhost/runtime/apps/{appId}")))
				.andExpect(jsonPath("$._links.runtime/apps/instances.href", is("http://localhost/runtime/apps/{appId}/instances")))
				.andExpect(jsonPath("$._links.metrics/streams.href", is("http://localhost/metrics/streams")))
				.andExpect(jsonPath("$._links.tasks/definitions.href", is("http://localhost/tasks/definitions")))
				.andExpect(jsonPath("$._links.tasks/definitions/definition.href", is("http://localhost/tasks/definitions/{name}")))
				.andExpect(jsonPath("$._links.tasks/validation.href", is("http://localhost/tasks/validation/{name}")))
				.andExpect(jsonPath("$._links.tasks/executions.href", is("http://localhost/tasks/executions")))
				.andExpect(jsonPath("$._links.tasks/executions/name.href", is("http://localhost/tasks/executions{?name}")))
				.andExpect(jsonPath("$._links.tasks/executions/current.href", is("http://localhost/tasks/executions/current")))
				.andExpect(jsonPath("$._links.tasks/executions/execution.href", is("http://localhost/tasks/executions/{id}")))
				.andExpect(jsonPath("$._links.jobs/executions.href", is("http://localhost/jobs/executions")))
				.andExpect(jsonPath("$._links.jobs/executions/name.href", is("http://localhost/jobs/executions{?name}")))
				.andExpect(jsonPath("$._links.jobs/executions/execution.href", is("http://localhost/jobs/executions/{id}")))
				.andExpect(jsonPath("$._links.jobs/executions/execution/steps.href", is("http://localhost/jobs/executions/{jobExecutionId}/steps")))
				.andExpect(jsonPath("$._links.jobs/executions/execution/steps/step.href", is("http://localhost/jobs/executions/{jobExecutionId}/steps/{stepId}")))
				.andExpect(jsonPath("$._links.jobs/executions/execution/steps/step/progress.href", is("http://localhost/jobs/executions/{jobExecutionId}/steps/{stepId}/progress")))
				.andExpect(jsonPath("$._links.jobs/instances/name.href", is("http://localhost/jobs/instances{?name}")))
				.andExpect(jsonPath("$._links.jobs/instances/instance.href", is("http://localhost/jobs/instances/{id}")))
				.andExpect(jsonPath("$._links.tools/parseTaskTextToGraph.href", is("http://localhost/tools")))
				.andExpect(jsonPath("$._links.tools/convertTaskGraphToText.href", is("http://localhost/tools")))
				.andExpect(jsonPath("$._links.counters.href", is("http://localhost/metrics/counters")))
				.andExpect(jsonPath("$._links.counters/counter.href", is("http://localhost/metrics/counters/{name}")))
				.andExpect(jsonPath("$._links.field-value-counters.href", is("http://localhost/metrics/field-value-counters")))
				.andExpect(jsonPath("$._links.field-value-counters/counter.href", is("http://localhost/metrics/field-value-counters/{name}")))
				.andExpect(jsonPath("$._links.aggregate-counters.href", is("http://localhost/metrics/aggregate-counters")))
				.andExpect(jsonPath("$._links.aggregate-counters/counter.href", is("http://localhost/metrics/aggregate-counters/{name}")))
				.andExpect(jsonPath("$._links.apps.href", is("http://localhost/apps")))
				.andExpect(jsonPath("$._links.about.href", is("http://localhost/about")))
				.andExpect(jsonPath("$._links.audit-records.href", is("http://localhost/audit-records")))
				.andExpect(jsonPath("$._links.completions/stream.href", is("http://localhost/completions/stream{?start,detailLevel}")))
				.andExpect(jsonPath("$._links.completions/task.href", is("http://localhost/completions/task{?start,detailLevel}")));
	}

	@Test
	public void testAccessRootUrlAndCheckAllLinksWithViewOnlyUser() throws Exception {
		localDataflowResource.getMockMvc()
				.perform(get("/").header("Authorization", basicAuthorizationHeader(viewOnlyUser.getUsername(), viewOnlyUser.getPassword()))).andDo(print())
				.andExpect(status().isOk())
				.andExpect(jsonPath("$._links.*", hasSize(38)))
				.andExpect(jsonPath("$._links.dashboard.href", is("http://localhost/dashboard")))
				.andExpect(jsonPath("$._links.streams/definitions.href", is("http://localhost/streams/definitions")))
				.andExpect(jsonPath("$._links.streams/definitions/definition.href", is("http://localhost/streams/definitions/{name}")))
				.andExpect(jsonPath("$._links.streams/deployments.href", is("http://localhost/streams/deployments")))
				.andExpect(jsonPath("$._links.streams/deployments/deployment.href", is("http://localhost/streams/deployments/{name}")))
				.andExpect(jsonPath("$._links.streams/validation.href", is("http://localhost/streams/validation/{name}")))
				.andExpect(jsonPath("$._links.runtime/apps.href", is("http://localhost/runtime/apps")))
				.andExpect(jsonPath("$._links.runtime/apps/app.href", is("http://localhost/runtime/apps/{appId}")))
				.andExpect(jsonPath("$._links.runtime/apps/instances.href", is("http://localhost/runtime/apps/{appId}/instances")))
				.andExpect(jsonPath("$._links.metrics/streams.href", is("http://localhost/metrics/streams")))
				.andExpect(jsonPath("$._links.tasks/definitions.href", is("http://localhost/tasks/definitions")))
				.andExpect(jsonPath("$._links.tasks/definitions/definition.href", is("http://localhost/tasks/definitions/{name}")))
				.andExpect(jsonPath("$._links.tasks/validation.href", is("http://localhost/tasks/validation/{name}")))
				.andExpect(jsonPath("$._links.tasks/executions.href", is("http://localhost/tasks/executions")))
				.andExpect(jsonPath("$._links.tasks/executions/name.href", is("http://localhost/tasks/executions{?name}")))
				.andExpect(jsonPath("$._links.tasks/executions/current.href", is("http://localhost/tasks/executions/current")))
				.andExpect(jsonPath("$._links.tasks/executions/execution.href", is("http://localhost/tasks/executions/{id}")))
				.andExpect(jsonPath("$._links.jobs/executions.href", is("http://localhost/jobs/executions")))
				.andExpect(jsonPath("$._links.jobs/executions/name.href", is("http://localhost/jobs/executions{?name}")))
				.andExpect(jsonPath("$._links.jobs/executions/execution.href", is("http://localhost/jobs/executions/{id}")))
				.andExpect(jsonPath("$._links.jobs/executions/execution/steps.href", is("http://localhost/jobs/executions/{jobExecutionId}/steps")))
				.andExpect(jsonPath("$._links.jobs/executions/execution/steps/step.href", is("http://localhost/jobs/executions/{jobExecutionId}/steps/{stepId}")))
				.andExpect(jsonPath("$._links.jobs/executions/execution/steps/step/progress.href", is("http://localhost/jobs/executions/{jobExecutionId}/steps/{stepId}/progress")))
				.andExpect(jsonPath("$._links.jobs/instances/name.href", is("http://localhost/jobs/instances{?name}")))
				.andExpect(jsonPath("$._links.jobs/instances/instance.href", is("http://localhost/jobs/instances/{id}")))
				.andExpect(jsonPath("$._links.tools/parseTaskTextToGraph.href", is("http://localhost/tools")))
				.andExpect(jsonPath("$._links.tools/convertTaskGraphToText.href", is("http://localhost/tools")))
				.andExpect(jsonPath("$._links.counters.href", is("http://localhost/metrics/counters")))
				.andExpect(jsonPath("$._links.counters/counter.href", is("http://localhost/metrics/counters/{name}")))
				.andExpect(jsonPath("$._links.field-value-counters.href", is("http://localhost/metrics/field-value-counters")))
				.andExpect(jsonPath("$._links.field-value-counters/counter.href", is("http://localhost/metrics/field-value-counters/{name}")))
				.andExpect(jsonPath("$._links.aggregate-counters.href", is("http://localhost/metrics/aggregate-counters")))
				.andExpect(jsonPath("$._links.aggregate-counters/counter.href", is("http://localhost/metrics/aggregate-counters/{name}")))
				.andExpect(jsonPath("$._links.apps.href", is("http://localhost/apps")))
				.andExpect(jsonPath("$._links.about.href", is("http://localhost/about")))
				.andExpect(jsonPath("$._links.audit-records.href", is("http://localhost/audit-records")))
				.andExpect(jsonPath("$._links.completions/stream.href", is("http://localhost/completions/stream{?start,detailLevel}")))
				.andExpect(jsonPath("$._links.completions/task.href", is("http://localhost/completions/task{?start,detailLevel}")));
	}
}


text:
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var types = require("./types");
var isArray = types.builtInTypes.array;
var isNumber = types.builtInTypes.number;
var Ap = Array.prototype;
var slice = Ap.slice;
var map = Ap.map;

function Path(value, parentPath, name) {
    if (!(this instanceof Path)) {
        throw new Error("Path constructor cannot be invoked without 'new'");
    }

    if (parentPath) {
        if (!(parentPath instanceof Path)) {
            throw new Error("");
        }
    } else {
        parentPath = null;
        name = null;
    }

    // The value encapsulated by this Path, generally equal to
    // parentPath.value[name] if we have a parentPath.
    this.value = value;

    // The immediate parent Path of this Path.
    this.parentPath = parentPath;

    // The name of the property of parentPath.value through which this
    // Path's value was reached.
    this.name = name;

    // Calling path.get("child") multiple times always returns the same
    // child Path object, for both performance and consistency reasons.
    this.__childCache = null;
}

var Pp = Path.prototype;

function getChildCache(path) {
    // Lazily create the child cache. This also cheapens cache
    // invalidation, since you can just reset path.__childCache to null.
    return path.__childCache || (path.__childCache = Object.create(null));
}

function getChildPath(path, name) {
    var cache = getChildCache(path);
    var actualChildValue = path.getValueProperty(name);
    var childPath = cache[name];
    if (!hasOwn.call(cache, name) ||
        // Ensure consistency between cache and reality.
        childPath.value !== actualChildValue) {
        childPath = cache[name] = new path.constructor(
            actualChildValue, path, name
        );
    }
    return childPath;
}

// This method is designed to be overridden by subclasses that need to
// handle missing properties, etc.
Pp.getValueProperty = function getValueProperty(name) {
    return this.value[name];
};

Pp.get = function get(name) {
    var path = this;
    var names = arguments;
    var count = names.length;

    for (var i = 0; i < count; ++i) {
        path = getChildPath(path, names[i]);
    }

    return path;
};

Pp.each = function each(callback, context) {
    var childPaths = [];
    var len = this.value.length;
    var i = 0;

    // Collect all the original child paths before invoking the callback.
    for (var i = 0; i < len; ++i) {
        if (hasOwn.call(this.value, i)) {
            childPaths[i] = this.get(i);
        }
    }

    // Invoke the callback on just the original child paths, regardless of
    // any modifications made to the array by the callback. I chose these
    // semantics over cleverly invoking the callback on new elements because
    // this way is much easier to reason about.
    context = context || this;
    for (i = 0; i < len; ++i) {
        if (hasOwn.call(childPaths, i)) {
            callback.call(context, childPaths[i]);
        }
    }
};

Pp.map = function map(callback, context) {
    var result = [];

    this.each(function(childPath) {
        result.push(callback.call(this, childPath));
    }, context);

    return result;
};

Pp.filter = function filter(callback, context) {
    var result = [];

    this.each(function(childPath) {
        if (callback.call(this, childPath)) {
            result.push(childPath);
        }
    }, context);

    return result;
};

function emptyMoves() {}
function getMoves(path, offset, start, end) {
    isArray.assert(path.value);

    if (offset === 0) {
        return emptyMoves;
    }

    var length = path.value.length;
    if (length < 1) {
        return emptyMoves;
    }

    var argc = arguments.length;
    if (argc === 2) {
        start = 0;
        end = length;
    } else if (argc === 3) {
        start = Math.max(start, 0);
        end = length;
    } else {
        start = Math.max(start, 0);
        end = Math.min(end, length);
    }

    isNumber.assert(start);
    isNumber.assert(end);

    var moves = Object.create(null);
    var cache = getChildCache(path);

    for (var i = start; i < end; ++i) {
        if (hasOwn.call(path.value, i)) {
            var childPath = path.get(i);
            if (childPath.name !== i) {
                throw new Error("");
            }
            var newIndex = i + offset;
            childPath.name = newIndex;
            moves[newIndex] = childPath;
            delete cache[i];
        }
    }

    delete cache.length;

    return function() {
        for (var newIndex in moves) {
            var childPath = moves[newIndex];
            if (childPath.name !== +newIndex) {
                throw new Error("");
            }
            cache[newIndex] = childPath;
            path.value[newIndex] = childPath.value;
        }
    };
}

Pp.shift = function shift() {
    var move = getMoves(this, -1);
    var result = this.value.shift();
    move();
    return result;
};

Pp.unshift = function unshift(node) {
    var move = getMoves(this, arguments.length);
    var result = this.value.unshift.apply(this.value, arguments);
    move();
    return result;
};

Pp.push = function push(node) {
    isArray.assert(this.value);
    delete getChildCache(this).length
    return this.value.push.apply(this.value, arguments);
};

Pp.pop = function pop() {
    isArray.assert(this.value);
    var cache = getChildCache(this);
    delete cache[this.value.length - 1];
    delete cache.length;
    return this.value.pop();
};

Pp.insertAt = function insertAt(index, node) {
    var argc = arguments.length;
    var move = getMoves(this, argc - 1, index);
    if (move === emptyMoves) {
        return this;
    }

    index = Math.max(index, 0);

    for (var i = 1; i < argc; ++i) {
        this.value[index + i - 1] = arguments[i];
    }

    move();

    return this;
};

Pp.insertBefore = function insertBefore(node) {
    var pp = this.parentPath;
    var argc = arguments.length;
    var insertAtArgs = [this.name];
    for (var i = 0; i < argc; ++i) {
        insertAtArgs.push(arguments[i]);
    }
    return pp.insertAt.apply(pp, insertAtArgs);
};

Pp.insertAfter = function insertAfter(node) {
    var pp = this.parentPath;
    var argc = arguments.length;
    var insertAtArgs = [this.name + 1];
    for (var i = 0; i < argc; ++i) {
        insertAtArgs.push(arguments[i]);
    }
    return pp.insertAt.apply(pp, insertAtArgs);
};

function repairRelationshipWithParent(path) {
    if (!(path instanceof Path)) {
        throw new Error("");
    }

    var pp = path.parentPath;
    if (!pp) {
        // Orphan paths have no relationship to repair.


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

/** Type definition for shared pointers to instances of FNewsFeedItem. */
typedef TSharedPtr<struct FNewsFeedItem> FNewsFeedItemPtr;

/** Type definition for shared references to instances of FNewsFeedItem. */
typedef TSharedRef<struct FNewsFeedItem> FNewsFeedItemRef;

/**
 * Implements a view model for the news feed list.
 */
struct FNewsFeedItem
{
	/** The news excerpt. */
	FText Excerpt;

	/** The full news text. */
	FText FullText;

	/** Holds the name of the icon. */
	FString IconName;

	/** The date and time at which the news item was issued. */
	FDateTime Issued;

	/** The news item's unique identifier. */
	FGuid ItemId;

	/** Whether this news item has been marked as read. */
	bool Read;

	/** The news title. */
	FText Title;

	/** The URL to the full news release. */
	FString Url;

public:

	/**
	 * Creates and initializes a new item with the specified identifier.
	 *
	 * @param InItemId The item identifier.
	 */
	FNewsFeedItem( const FGuid& InItemId )
		: ItemId(InItemId)
	{ }
};


text:
const code = `
Flexio.connection()
  .url('https://api.example.com')
  .headers({
    'Authorization': 'Bearer customtoken',
    'MyCustom': 'HeaderValue'
  })
  .save({
    name: 'Custom Headers'
  }, function(err, result) {
    console.log(result)
  })`

const fn = (Flexio, callback) => {
  Flexio.connection()
    .url('https://api.example.com')
    .headers({
      'Authorization': 'Bearer customtoken',
      'MyCustom': 'HeaderValue'
    })
    .save({
      name: 'Custom Headers'
    }, callback)
}

export default {
  title: 'Create a connection with custom headers',
  code,
  fn
}


text:
static void onWokenFromSleep(const struct Event *event);
static void onButtonsStoppedBouncing(void *state);

static uint8_t buttonStateSampled;

void buttonsInitialise(void)
{
	PMD0bits.IOCMD = 0;
	ANSELA &= ~BUTTON_PORT_MASK;
	PIE0bits.IOCIE = 1;
	IOCAN |= BUTTON_PORT_MASK;
	IOCAP |= BUTTON_PORT_MASK;
	buttonStateSampled = BUTTON_STATE_NOW;

	static const struct EventSubscription onWokenFromSleepSubscription =
	{
		.type = WOKEN_FROM_SLEEP,
		.handler = &onWokenFromSleep,
		.state = (void *) 0
	};

	eventSubscribe(&onWokenFromSleepSubscription);
}

static void onWokenFromSleep(const struct Event *event)
{
	if (!PIR0bits.IOCIF)
		return;

	IOCAF = 0;

	static const struct NearSchedule onButtonsStoppedBouncingSchedule =
	{
		.ticks = MS_TO_TICKS(20),
		.handler = &onButtonsStoppedBouncing
	};

	nearSchedulerAddOrUpdate(&onButtonsStoppedBouncingSchedule);
}

static void onButtonsStoppedBouncing(void *state)
{
	uint8_t buttonsChanged = buttonStateSampled ^ BUTTON_STATE_NOW;
	if (!buttonsChanged)
		return;

	if (buttonsChanged & BUTTON1_PORT_MASK)
	{
		static const struct ButtonsPressed button1EventArgs = { .mask = 0x01 };
		if ((buttonStateSampled & BUTTON1_PORT_MASK) == 0)
			eventPublish(BUTTONS_RELEASED, &button1EventArgs);
		else
			eventPublish(BUTTONS_PRESSED, &button1EventArgs);
	}

	if (buttonsChanged & BUTTON2_PORT_MASK)
	{
		static const struct ButtonsPressed button2EventArgs = { .mask = 0x02 };
		if ((buttonStateSampled & BUTTON2_PORT_MASK) == 0)
			eventPublish(BUTTONS_RELEASED, &button2EventArgs);
		else
			eventPublish(BUTTONS_PRESSED, &button2EventArgs);
	}

	buttonStateSampled ^= buttonsChanged;
}


text:
package ch.fhnw.ether.examples.threed;

import ch.fhnw.ether.controller.DefaultController;
import ch.fhnw.ether.controller.IController;
import ch.fhnw.ether.platform.Platform;
import ch.fhnw.ether.scene.DefaultScene;
import ch.fhnw.ether.scene.IScene;
import ch.fhnw.ether.scene.camera.Camera;
import ch.fhnw.ether.scene.camera.ICamera;
import ch.fhnw.ether.scene.mesh.MeshUtilities;
import ch.fhnw.ether.view.DefaultView;
import ch.fhnw.ether.view.IView;
import ch.fhnw.util.math.Vec3;

public final class SimpleCubeExample {
	public static void main(String[] args) {
		new SimpleCubeExample();
	}

	public SimpleCubeExample() {
		// Init platform
		Platform.get().init();

		// Create controller
		IController controller = new DefaultController();
		controller.run(time -> {
			// Create view
			IView view = new DefaultView(controller, 100, 100, 500, 500, IView.INTERACTIVE_VIEW, "Simple Cube");

			// Add UI
			//controller.setUI(new UI(controller));

			// Create scene
			IScene scene = new DefaultScene(controller);
			controller.setScene(scene);

			// Create and add camera
			ICamera camera = new Camera(new Vec3(0, -5, 5), Vec3.ZERO);
			scene.add3DObject(camera);
			controller.setCamera(view, camera);

			// Add cube
			scene.add3DObject(MeshUtilities.createCube());
			//scene.add3DObject(MeshUtilities.createDisk(6));
			//scene.add3DObject(MeshUtilities.createCylinder(6, true));

			// Add an exit button
			//controller.getUI().addWidget(new Button(0, 0, "Quit", "Quit", IKeyEvent.VK_ESCAPE, (button, v) -> System.exit(0)));
		});

		Platform.get().run();
	}
}


text:
// ----------------------------------------------------------------------------
// Copyright 2006-2010, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
//  2007/08/09  Martin D. Flynn
//     -Initial release
// ----------------------------------------------------------------------------
package org.opengts.geocoder;

import org.opengts.util.*;

public interface SubdivisionProvider
{

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

    /**
    *** Returns true if this operation will take less than about 20ms to complete
    *** the returned value is used to determine whether the 'getReverseGeocode' operation
    *** should be performed immediately, or lazily (ie. in a separate thread).
    *** @return True if this is a fast (ie. local) operation
    **/
    public boolean isFastOperation();

    /**
    *** Return the subdivision of the specified point
    *** (in the US, this is "US/<stateCode>" as in "US/CA")
    **/
    public String getSubdivision(GeoPoint gp);

}


text:
pyfar
===================

Classifier
-------------------
.. automodule:: baseline_algorithm
  :members:

.. automodule:: classifier
  :members:

Utilities
-------------------
.. automodule:: utils
  :members:

DTW
-------------------
.. automodule:: dtw
  :members:

Pipeline
-------------------
.. automodule:: pipeline
  :members:

Ventricular beat modelling
--------------------------

.. automodule:: ventricular_beat_stdev
  :members:

.. automodule:: ventricular_beat_bank
  :members:


text:
package org.jbpm.compiler.xml.processes;

import org.drools.core.xml.ExtensibleXmlParser;
import org.jbpm.workflow.core.Node;
import org.jbpm.workflow.core.node.RuleSetNode;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

public class RuleSetNodeHandler extends AbstractNodeHandler {

    protected Node createNode() {
        return new RuleSetNode();
    }

    public void handleNode(final Node node, final Element element, final String uri,
            final String localName, final ExtensibleXmlParser parser)
            throws SAXException {
        super.handleNode(node, element, uri, localName, parser);
        RuleSetNode ruleSetNode = (RuleSetNode) node;
        String ruleFlowGroup = element.getAttribute("ruleFlowGroup");
        if (ruleFlowGroup != null && ruleFlowGroup.length() > 0) {
        	ruleSetNode.setRuleFlowGroup(ruleFlowGroup);
        }
    }

    @SuppressWarnings("unchecked")
	public Class generateNodeFor() {
        return RuleSetNode.class;
    }

	public void writeNode(Node node, StringBuilder xmlDump, boolean includeMeta) {
		RuleSetNode ruleSetNode = (RuleSetNode) node;
		writeNode("ruleSet", ruleSetNode, xmlDump, includeMeta);
        String ruleFlowGroup = ruleSetNode.getRuleFlowGroup();
        if (ruleFlowGroup != null) {
            xmlDump.append("ruleFlowGroup=\"" + ruleFlowGroup + "\" ");
        }
        if (ruleSetNode.getTimers() != null || (includeMeta && containsMetaData(ruleSetNode))) {
            xmlDump.append(">\n");
            if (ruleSetNode.getTimers() != null) {
            	writeTimers(ruleSetNode.getTimers(), xmlDump);
            }
            if (includeMeta) {
            	writeMetaData(ruleSetNode, xmlDump);
            }
            endNode("ruleSet", xmlDump);
        } else {
            endNode(xmlDump);
        }
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:gravity="center_horizontal"
        android:orientation="vertical" >

        <ImageView
            android:layout_width="55dp"
            android:layout_height="55dp"
            android:src="@drawable/icon_pfd_fruits" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"
            android:text="Fruits"
            android:textColor="@android:color/black"
            android:textSize="23sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="The bottom line: "
            android:textColor="@android:color/black"
            android:textStyle="bold" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="7dp"
            android:text="On average, a 50-calorie share is a whole fruit. One small piece of fruit counts as 1 share. One half-cup juice or two tablespoons dried fruit counts as 1 share."
            android:textColor="@android:color/black" />

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:weightSum="1.0" >

            <LinearLayout
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:gravity="center"
                android:orientation="vertical"
                android:paddingBottom="5dp" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingBottom="3dp"
                    android:paddingTop="5dp"
                    android:text="Daily Shares"
                    android:textColor="@android:color/black"
                    android:textSize="17sp"
                    android:textStyle="bold" >
                </TextView>

                <TextView
                    android:id="@+id/dialog_textView_pfd_fruit_shares"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingBottom="5dp"
                    android:text="##"
                    android:textColor="@android:color/black"
                    android:textSize="30sp"
                    android:textStyle="bold" >
                </TextView>
            </LinearLayout>

            <TextView
                android:layout_width="1px"
                android:layout_height="fill_parent"
                android:background="@android:color/black" >
            </TextView>

            <LinearLayout
                android:layout_width="0px"
                android:layout_height="wrap_content"
                android:layout_weight=".5"
                android:gravity="center"
                android:orientation="vertical" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingBottom="3dp"
                    android:paddingTop="5dp"
                    android:text="Your Shares"
                    android:textColor="@android:color/black"
                    android:textSize="17sp"
                    android:textStyle="bold" >
                </TextView>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:paddingBottom="5dp" >

                    <ImageView
                        android:id="@+id/dialog_imageView_pfd_fruit_downShares"
                        android:layout_width="35dp"
                        android:layout_height="35dp"
                        android:clickable="true"
                        android:onClick="decrementShares"
                        android:src="@drawable/button_selector_down" >
                    </ImageView>

                    <TextView
                        android:id="@+id/dialog_editText_pfd_fruit_shares"
                        android:layout_width="55dp"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:paddingBottom="5dp"
                        android:text="0"
                        android:textColor="@android:color/black"
                        android:textSize="30sp"
                        android:textStyle="bold" >
                    </TextView>

                    <ImageView
                        android:id="@+id/dialog_imageView_pfd_fruit_upShares"
                        android:layout_width="35dp"
                        android:layout_height="35dp"
                        android:clickable="true"
                        android:onClick="incrementShares"
                        android:src="@drawable/button_selector_up" >
                    </ImageView>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>


text:
import Image from "next/image";
import Link from "next/link";
import React from "react";
import Layout from "../lib/components/Layout";

const Podcasting = () => {
  return (
    <Layout title="What I want to do">

What I want to do

          I am currently searching a freelance role as a developer and architect
          in an agile environment.

          My preferred role would be to help you and your team{" "}

            migrate a monolithic platform to a future-proof micro-service
            oriented environment

          . I got a track record in doing projects like this.

I am strong in Frontend technologies, especially
            React
          {" "}
          and worked a lot with Node.js.

          I am available as of mid of July 2018.

          Preferably in the Cologne, Düsseldorf area.

          Contact me via info@drublic.de.

            Contact me

          <Image
            src="/img/monolith-to-microservice.png"
            alt="What you have vs. what you want"
            width="813"
            height="299"
          />

About me

          I am a frontend architect and software engineer located in Cologne,
          Germany.

          Agile development and Scrum influence my daily work since 2012. I have
          ten years of experience in developing scalable web applications using
          cutting edge technologies based on Micro-Service Oriented Architecture
          including HTML/CSS and object-oriented JavaScript (frontend and
          backend), React is my Framework of choice. Within the last couple of
          years I worked a lot with Node.js.

          I love architecting systems in a high-performance environment with a
          focus on frontend development. My passion in JavaScript and CSS is as
          strong as my belief in agile methodologies.

          <Link href="/resume">
            My Résumé
          </Link>

          <Link href="/portfolio">
            My Projects
          </Link>

    </Layout>
  );
};

export default Podcasting;


text:
import sys

def swap_elements(array,swap_cases):

	array = array.split(' ')
	swap_cases = swap_cases.split(',')

	for x in range(0,len(swap_cases)):

		elements_to_swap = swap_cases[x].strip().split('-')
		pos_1 = int(elements_to_swap[0])
		pos_2 = int(elements_to_swap[1])

		auxiliar_element = array[pos_1]
		array[pos_1] = array[pos_2]
		array[pos_2] = auxiliar_element

	print(' '.join(array))

test_cases = open('test_cases','r')

for line in test_cases:

	line_splitted = line.strip().split(':')
	swap_elements(line_splitted[0].strip(),line_splitted[1].strip())


text:
package main

import (
	"os"
	"fmt"
	"io/ioutil"

	"github.com/Azure/azure-sdk-for-go/storage"
	"github.com/Azure/azure-go-samples/helpers"
)

const cnt = "blob03-container"

const accountName = "<<INSERT ACCOUNT NAME HERE>>"
const accountKey  = "<<INSERT ACCOUNT KEY HERE>>"

const blobSize = 8*512	// Each page is 512 bytes long.

func main() {

	if len(os.Args) < 2 {
		fmt.Printf("usage: blob03 blob-name\n")
		return
	}

	blob := os.Args[1]

	cli := helpers.GetStorageClient(accountName, accountKey).GetBlobService()

	// Create a container.

	_, err := cli.CreateContainerIfNotExists(cnt, storage.ContainerAccessTypeBlob)
	if err != nil {
		fmt.Printf("ERROR: Failed to create container '%s': %s\n", cnt, err.Error())
		return
	}

	fmt.Printf("Successfully created '%s'\n", cnt)

	// First, create an empty page blob
	if err := cli.PutPageBlob(cnt, blob, blobSize); err != nil {
		fmt.Printf("Failed to create '%s' in  '%s': %s\n", blob, cnt, err.Error())
		return
	}

	// Then, write some pages. We will write pages 0, 1, and 2, leaving five pages blank.

	data := helpers.RandBytes(1536)

	if err := writePage(cli, blob, 0, 511, data[0:512]); err != nil {
		return
	}
	if err := writePage(cli, blob, 512, 1023, data[512:1024]); err != nil {
		return
	}
	if err := writePage(cli, blob, 1024, 1535, data[1024:1536]); err != nil {
		return
	}

	// Now that we have written the pages, let's check what's been stored.

	url := cli.GetBlobURL(cnt,blob)

	// The first three pages should correspond to what was written.
	if err := validate(cli, blob, 0, 1535, data[0:1536]); err != nil {
		fmt.Printf("Failed validation of %s: %s\n", url, err.Error())
		return
	}

	// The next five pages should be all zeroes.
	if err := validate(cli, blob, 1536, blobSize-1, make([]byte,blobSize)); err != nil {
		fmt.Printf("Failed validation of %s: %s\n", url, err.Error())
		return
	}

	fmt.Printf("Successfully created, wrote to, and read a page blob at '%s\n", url)

	// Next, let's try clearing a page, that is, setting it to all zeroes.

	if err := clearPage(cli, blob, 512, 1023); err != nil {
		return
	}

	// Now that we have written the pages, let's check what's been stored.

	// The first and third pages should correspond to what was written.
	if err := validate(cli, blob, 0, 511, data[0:512]); err != nil {
		fmt.Printf("Failed validation of %s: %s\n", url, err.Error())
		return
	}
	// The second page should be all zeroes.
	if err := validate(cli, blob, 512, 1023, make([]byte,1024)); err != nil {
		fmt.Printf("Failed validation of %s: %s\n", url, err.Error())
		return
	}
	if err := validate(cli, blob, 1024, 1535, data[0:1536]); err != nil {
		fmt.Printf("Failed validation of %s: %s\n", url, err.Error())
		return
	}

	// The last five pages should still be all zeroes.
	if err := validate(cli, blob, 1536, blobSize-1, make([]byte,blobSize)); err != nil {
		fmt.Printf("Failed validation of %s: %s\n", url, err.Error())
		return
	}

	// We can check which pages have data by getting the valid page ranges.

	ranges,err := cli.GetPageRanges(cnt,blob)
	if err != nil {
		fmt.Printf("Failed to get page ranges for %s: %s\n", url, err.Error())
		return
	}

	fmt.Printf("Successfully cleared a page at '%s\n", url)

	for _,rng := range ranges.PageList {
		fmt.Printf("[%d,%d]\n", rng.Start, rng.End)
	}

	pl := ranges.PageList

	if len(pl) != 2 || pl[0].Start != 0 || pl[0].End != 511 || pl[1].Start != 1024 || pl[1].End != 1535 {
		fmt.Printf("Incorrect page list returned\n")
		return
	}

	fmt.Printf("Successfully checked page ranges of '%s\n", url)
}

func writePage(cli storage.BlobStorageClient, name string, startByte, endByte int64, chunk []byte) error {

	if err := cli.PutPage(cnt, name, startByte, endByte, storage.PageWriteTypeUpdate, chunk); err != nil {
		url := cli.GetBlobURL(cnt,name)
		fmt.Printf("Failed to write pages to %s: %s\n", url, err.Error())
		return err
	}
	return nil
}

func clearPage(cli storage.BlobStorageClient, name string, startByte, endByte int64) error {

	if err := cli.PutPage(cnt, name, startByte, endByte, storage.PageWriteTypeClear, nil); err != nil {
		url := cli.GetBlobURL(cnt,name)
		fmt.Printf("Failed to clear pages of %s: %s\n", url, err.Error())
		return err
	}
	return nil
}

func validate(cli storage.BlobStorageClient, blob string, startByte, endByte int64, data []byte) error {

	url := cli.GetBlobURL(cnt,blob)

	reader,err := cli.GetBlob(cnt, blob)
	if err != nil {
		return fmt.Errorf("Failed to read from %s: %s\n", url, err.Error())
	}

	defer reader.Close()

	dataRead,err := ioutil.ReadAll(reader)

	if err != nil {
		return fmt.Errorf("Failed to read from %s: %s\n", url, err.Error())
	}

	same := true
	for i := startByte; i <= endByte; i++ {
		if data[i] != dataRead[i] {
			same = false
		}
	}

	if !same {
		return fmt.Errorf("Failed to read data properly from %s: %s\n", url, err.Error())
	}

	return nil
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/gcm_driver/crypto/gcm_message_cryptographer.h"

#include <algorithm>

#include "base/big_endian.h"
#include "base/logging.h"
#include "crypto/hkdf.h"

namespace gcm {
namespace {

// Size, in bytes, of the nonce for a record. This must be at least the size
// of a uint64_t, which is used to indicate the record sequence number.
const uint64_t kNonceSize = 12;

// The default record size as defined by draft-thomson-http-encryption-01.
const size_t kDefaultRecordSize = 4096;

// Key size, in bytes, of a valid AEAD_AES_128_GCM key.
const size_t kContentEncryptionKeySize = 16;

// Salt size, in bytes, that will be used together with the key to create a
// unique content encryption key for a given message.
const size_t kSaltSize = 16;

}  // namespace

const size_t GCMMessageCryptographer::kAuthenticationTagBytes = 16;

GCMMessageCryptographer::GCMMessageCryptographer() {}

GCMMessageCryptographer::~GCMMessageCryptographer() {}

bool GCMMessageCryptographer::Encrypt(const base::StringPiece& plaintext,
                                      const base::StringPiece& key,
                                      const base::StringPiece& salt,
                                      size_t* record_size,
                                      std::string* ciphertext) const {
  DCHECK(ciphertext);
  DCHECK(record_size);

  if (salt.size() != kSaltSize)
    return false;

  std::string content_encryption_key = DeriveContentEncryptionKey(key, salt);
  std::string nonce = DeriveNonce(key, salt);

  // draft-nottingham-http-encryption-encoding-00 allows between 0 and 255
  // octets of padding to be inserted before the enciphered content, with the
  // length of the padding stored in the first octet of the payload. Since
  // there is no necessity for payloads to contain padding, don't add any.
  std::string record;
  record.reserve(plaintext.size() + 1);
  record.append(1, '\0');
  plaintext.AppendToString(&record);

  std::string encrypted_record;
  if (!EncryptDecryptRecordInternal(ENCRYPT, record, content_encryption_key,
                                    nonce, &encrypted_record)) {
    return false;
  }

  // The advertised record size must be at least one more than the padded
  // plaintext to ensure only one record.
  *record_size = std::max(kDefaultRecordSize, record.size() + 1);

  ciphertext->swap(encrypted_record);
  return true;
}

bool GCMMessageCryptographer::Decrypt(
    const base::StringPiece& ciphertext,
    const base::StringPiece& key,
    const base::StringPiece& salt,
    size_t record_size,
    std::string* plaintext) const {
  DCHECK(plaintext);

  if (salt.size() != kSaltSize || record_size <= 1)
    return false;

  // The |ciphertext| must be at least kAuthenticationTagBytes + 1 bytes, which
  // would be used for an empty message. Per
  // https://tools.ietf.org/html/draft-thomson-webpush-encryption-01#section-3,
  // the |record_size| parameter must be large enough to use only one record.
  if (ciphertext.size() < kAuthenticationTagBytes + 1 ||
      ciphertext.size() >= record_size + kAuthenticationTagBytes + 1) {
    return false;
  }

  std::string content_encryption_key = DeriveContentEncryptionKey(key, salt);
  std::string nonce = DeriveNonce(key, salt);

  std::string decrypted_record;
  if (!EncryptDecryptRecordInternal(DECRYPT, ciphertext, content_encryption_key,
                                    nonce, &decrypted_record)) {
    return false;
  }

  DCHECK(!decrypted_record.empty());

  // Records can contain between 0 and 255 octets of padding, indicated by the
  // first octet of the decrypted message. Padding bytes that are not set to
  // zero are considered a fatal decryption failure as well. Since AES-GCM
  // includes an authentication check, neither verification nor removing the
  // padding have to be done in constant time.
  size_t padding_length = static_cast<size_t>(decrypted_record[0]);
  if (padding_length >= decrypted_record.size())
    return false;

  for (size_t i = 1; i <= padding_length; ++i) {
    if (decrypted_record[i] != 0)
      return false;
  }

  base::StringPiece decoded_record_string_piece(decrypted_record);
  decoded_record_string_piece.remove_prefix(1 + padding_length);
  decoded_record_string_piece.CopyToString(plaintext);

  return true;
}

std::string GCMMessageCryptographer::DeriveContentEncryptionKey(
    const base::StringPiece& key,
    const base::StringPiece& salt) const {
  crypto::HKDF hkdf(key, salt,
                    "Content-Encoding: aesgcm128",
                    kContentEncryptionKeySize,
                    0,  /* iv_bytes_to_generate */
                    0   /* subkey_secret_bytes_to_generate */);

  return hkdf.client_write_key().as_string();
}

std::string GCMMessageCryptographer::DeriveNonce(
    const base::StringPiece& key,
    const base::StringPiece& salt) const {
  crypto::HKDF hkdf(key, salt,
                    "Content-Encoding: nonce",
                    kNonceSize,
                    0,  /* iv_bytes_to_generate */
                    0   /* subkey_secret_bytes_to_generate */);

  // draft-thomson-http-encryption-01 defines that the result should be XOR'ed
  // with the record's sequence number, but because Web Push encryption is
  // limited to a single record we do not have to do that.

  return hkdf.client_write_key().as_string();
}

}  // namespace gcm


text:
require "uploadify_rails/controllers/base"
require "uploadify_rails/models/resource"
require "uploadify_rails/models/parent"
require "uploadify_rails/engine"
require "uploadify_rails/version"


text:
package be.ac.ua.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.SOURCE)
@Target({
	ElementType.CONSTRUCTOR,
	ElementType.METHOD
})
public @interface requires {
    String value();
}


text:
package sun.awt.windows;

import java.awt.*;
import java.awt.peer.*;
import java.lang.reflect.Field;

import sun.awt.SunToolkit;
import sun.awt.AWTAccessor;

public class WPopupMenuPeer extends WMenuPeer implements PopupMenuPeer {
    // We can't use target.getParent() for TrayIcon popup
    // because this method should return null for the TrayIcon
    // popup regardless of that whether it has parent or not.

    public WPopupMenuPeer(PopupMenu target) {
        this.target = target;
        MenuContainer parent = null;

        // We can't use target.getParent() for TrayIcon popup
        // because this method should return null for the TrayIcon
        // popup regardless of that whether it has parent or not.
        boolean isTrayIconPopup = AWTAccessor.getPopupMenuAccessor().isTrayIconPopup(target);
        if (isTrayIconPopup) {
            parent = AWTAccessor.getMenuComponentAccessor().getParent(target);
        } else {
            parent = target.getParent();
        }

        if (parent instanceof Component) {
            WComponentPeer parentPeer = (WComponentPeer) WToolkit.targetToPeer(parent);
            if (parentPeer == null) {
                // because the menu isn't a component (sigh) we first have to wait
                // for a failure to map the peer which should only happen for a
                // lightweight container, then find the actual native parent from
                // that component.
                parent = WToolkit.getNativeContainer((Component)parent);
                parentPeer = (WComponentPeer) WToolkit.targetToPeer(parent);
            }
            createMenu(parentPeer);
            // fix for 5088782: check if menu object is created successfully
            checkMenuCreation();
        } else {
            throw new IllegalArgumentException(
                "illegal popup menu container class");
        }
    }

    native void createMenu(WComponentPeer parent);

    public void show(Event e) {
        Component origin = (Component)e.target;
        WComponentPeer peer = (WComponentPeer) WToolkit.targetToPeer(origin);
        if (peer == null) {
            // A failure to map the peer should only happen for a
            // lightweight component, then find the actual native parent from
            // that component.  The event coorinates are going to have to be
            // remapped as well.
            Component nativeOrigin = WToolkit.getNativeContainer(origin);
            e.target = nativeOrigin;

            // remove the event coordinates
            for (Component c = origin; c != nativeOrigin; c = c.getParent()) {
                Point p = c.getLocation();
                e.x += p.x;
                e.y += p.y;
            }
        }
        _show(e);
    }

    /*
     * This overloaded method is for TrayIcon.
     * Its popup has special parent.
     */
    void show(Component origin, Point p) {
        WComponentPeer peer = (WComponentPeer) WToolkit.targetToPeer(origin);
        Event e = new Event(origin, 0, Event.MOUSE_DOWN, p.x, p.y, 0, 0);
        if (peer == null) {
            Component nativeOrigin = WToolkit.getNativeContainer(origin);
            e.target = nativeOrigin;
        }
        e.x = p.x;
        e.y = p.y;
        _show(e);
    }

    public native void _show(Event e);
}


text:
* Significant performance improvements
* Update to Unicode version 13.0.0

## 0.3.6

* Update to Unicode version 12.1.0
* Update Quickcheck dependency version bounds
* Test with GHC 8.6.5

## 0.3.5

* Update dependency version bounds
* Test with GHC 8.6.2

## 0.3.4

* GHC 8.4.1 support

## 0.3.3

* GHC 8.2.1 support

## 0.3.2

* Work around a GHC/LLVM issue for ARM

## 0.3.1

* Update dependency versions

## 0.3.0

* Support Unicode version 9.0

## 0.2.1

* Improve speed and resource hog during compilation

## 0.2.0

* Support Unicode version 8.0
* Switch to pure Haskell implementation

## 0.1.0.1

* Initial release based on utf8proc C implementation


text:
<?php
$db = new mysqli('localhost', 'appd2dpr_php', '9&3mPMjCJM8+uKy6o', 'appd2dpr_mobileApp');
/*$tokentest = 'SELECT * FROM devices WHERE authtoken="'.$db->real_escape_string($_COOKIE['token']).'"';
if(!$tokenresult = $db->query($tokentest)){
	die('Error: ' . $db->error);
}
if($tokenresult->num_rows == 0){
	die('Incorrect token');
}
*/
$userID = $db->real_escape_string($_GET["userID"]);
$devID = $db->real_escape_string($_GET["devID"]);
file_put_contents("recent.txt", "GET" . file_get_contents("php://input"));
$locQuery = 'SELECT * FROM tracker_table WHERE userID="'.$userID.'" AND deviceID="'.$devID.'"';

if(!$locations=$db->query($locQuery)){
		die("Error: " . $db->error);
}
$loc = array();
while($locationRow=$locations->fetch_assoc()){
	$loc = array($locationRow["latitude"], $locationRow["longitude"]);
}
echo json_encode($loc);
?>


text:
package testing

import (
	"fmt"
	"net/http"
	"testing"

	th "github.com/gophercloud/gophercloud/testhelper"
	"github.com/gophercloud/gophercloud/testhelper/client"
)

func mockResetStateResponse(t *testing.T, id string, state string) {
	th.Mux.HandleFunc("/servers/"+id+"/action", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "POST")
		th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
		th.TestJSONRequest(t, r, fmt.Sprintf(`{"os-resetState": {"state": "%s"}}`, state))
		w.WriteHeader(http.StatusAccepted)
	})
}


text:
using System;
using Xamarin.Forms;

namespace AltBeaconLibrary.Sample
{
	public class ListItemView : ViewCell
	{
		public ListItemView()
		{
			View = BuildContent();
		}

		private View BuildContent()
		{
			var viewLayout = new StackLayout()
			{
				Orientation = StackOrientation.Vertical,
				VerticalOptions = LayoutOptions.Fill,
				Spacing = 0,
				Padding = 0,
			};

			var beaconId = new Label {
				Text = "E4C8A4FC-F68B-470D-959F-29382AF72CE7",
				TextColor = Color.Black,
				FontFamily = "sans-serif",
				FontSize = 17
			};

			beaconId.SetBinding(Label.TextProperty, "Id");

			var beaconIdLayout = new StackLayout {
				Orientation = StackOrientation.Horizontal,
				HorizontalOptions = LayoutOptions.End,
				Spacing = 0,
				Padding = new Thickness(0, 10, 10, 5),
				Children = { beaconId }
			};

			viewLayout.Children.Add(beaconIdLayout);

			var beaconDistance = new Label {
				Text = "1.3m",
				TextColor = Color.Black,
				FontFamily = "sans-serif-light",
				FontSize = 36
			};

			beaconDistance.SetBinding(Label.TextProperty, "Distance");

			var beaconDistanceLayout = new StackLayout {
				Orientation = StackOrientation.Horizontal,
				HorizontalOptions = LayoutOptions.End,
				Spacing = 0,
				Padding = new Thickness(0, 0, 10, 10),
				Children = { beaconDistance }
			};

			viewLayout.Children.Add(beaconDistanceLayout);

			return viewLayout;
		}
	}
}