text:
package org.jnetpcap.app;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;

import org.apache.log4j.Logger;
import org.jnetpcap.Pcap;
import org.jnetpcap.PcapBpfProgram;
import org.jnetpcap.nio.JBuffer;
import org.jnetpcap.nio.JMemory.Type;
import org.jnetpcap.packet.JMemoryPacket;
import org.jnetpcap.packet.JPacket;
import org.jnetpcap.packet.PcapPacket;
import org.jnetpcap.packet.PcapPacketHandler;
import org.jnetpcap.protocol.network.Ip4;
import org.jnetpcap.protocol.tcpip.Tcp;

/**
 * Based on a demonstration application for reassembling IP fragments from Sky
 * Technologies Inc.
 *
 * Reassemble the IP fragments and if there is any data push it to a handler.
 *
 * @author Mark Bednarczyk
 * @author Sly Technologies, Inc.
 * @auther Colin Crist
 */
public class IpReassembler implements PcapPacketHandler<Object> {

	private static final Logger log = Logger.getLogger(IpReassembler.class);

	/**
	 * Our custom interface that allows listeners to get our special reassembled
	 * IP packets and also provide them with the actual reassembled buffer.
	 *
	 * @author Mark Bednarczyk
	 * @author Sly Technologies, Inc.
	 * @param <T>
	 */
	public interface IpReassemblyBufferHandler {
		public void nextIpDatagram(IpReassemblyBuffer buffer);
	}

	public interface IpReassemblyPayloadHander {
		public void nextBlock(long l, byte[] block);
	}

	/**
	 * A special buffer used for reassembling the original IP datagram. The
	 * reassembled buffer contains an IP header upfront and it suitable for
	 * peering with a packet and then decoding.
	 *
	 *

	 * +-----------+-----------+-----------+--˜˜˜˜--+
	 * | Ip Header | Ip frag 1 | Ip frag 2 | etc... |
	 * +-----------+-----------+-----------+--˜˜˜˜--+
	 *

	 *
	 * The header comes from the first segment that was seen part of this IP
	 * datagram. The original header is used as a template and then several
	 * fields are reset to reflect the state of reassembled packet. The fields
	 * modified are:
	 *

	 *
Ip4.flags

	 *
Ip4.length

	 *
Ip4.hlen

	 *
Ip4.offset

	 *

	 *
	 * @author Mark Bednarczyk
	 * @author Sly Technologies, Inc.
	 */
	public static class IpReassemblyBuffer extends JBuffer implements Comparable<IpReassemblyBuffer> {

		/**
		 * The IP header found at the beggining of this buffer
		 */
		private final Ip4 header = new Ip4();

		/**
		 * Total length of the reassembled IP fragments including the ip header
		 */
		private int ipDatagramLength = -1;

		/**
		 * Keeps track of how many bytes have been copied into this buffer. When
		 * bytesCopiedIntoBuffer == ipDatagramLength, where
		 * bytesCopiedIntoBuffer keeps track of the total size of the original
		 * datagram in its entirety (including Ip4 header), then the reassembly
		 * is complete.
		 */
		private int bytesCopiedIntoBuffer = 20;

		/**
		 * Offset where the Ip payload begins in the reassembled IP datagram.
		 * Always constant since our IP header is constant as well.
		 */
		private final int start = 20; // length Ip4 header

		/**
		 * Timestamp when this buffer is officially timedout
		 */
		private final long timeout;

		/**
		 * A hash of Ip4.source, Ip4.destination, Ip4.id, Ip4.type
		 */
		private final int hash;

		private long timestampInMicros;

		/**
		 * Override the default hashcode with our special Ip4 based one
		 */
		@Override
		public int hashCode() {
			return this.hash;
		}

		/**
		 * Creates a new buffer for IP fragment reassebly. The buffer appends an
		 * Ip4 header to the front of the buffer. The supplied ip header is only
		 * used as a template and a copy is made. This allows the buffer to
		 * retain all the vital Ip4 information found in the original Ip4
		 * datagram before it was fragmented.
		 *
		 * @param ip
		 *            ip header of one of the fragments to be used as a template
		 *            for the reassembled packet
		 * @param size
		 *            amount of memory to allocate for reassembly
		 * @param timeout
		 *            timestamp in millis when this buffer should be timed out
		 * @param hash
		 *            special Ip4 based hash used for identifying this buffer
		 *            quickly
		 */
		public IpReassemblyBuffer(Ip4 ip, int size, long timeout, int hash) {
			super(size); // allocate memory

			this.timeout = timeout;
			this.hash = hash;

			transferFrom(ip); // copy fragment's Ip header to our buffer
		}

		/**
		 * Deep copy the supplied Ip4 header to the front of the buffer. Reset
		 * some ip fields to reflect the state of this buffer.
		 *
		 * @param ip
		 *            source Ip4 header to use as template
		 */
		private void transferFrom(Ip4 ip) {
			/*
			 * Copy ip header as a template
			 */
			ip.transferTo(this, 0, 20, 0);

			/*
			 * Peer a temporary working Ip4 header to the start of our buffer.
			 * It contains our template Ip4 header data.
			 */
			header.peer(this, 0, 20);

			/*
			 * Now reset a few things that are no longer neccessary in a
			 * reassembled datagram
			 */
			header.hlen(5); // Clear IP optional headers
			header.clearFlags(Ip4.FLAG_MORE_FRAGMENTS); // FRAG flag
			header.offset(0); // Offset is now 0
			header.checksum(0); // Reset header CRC, unless we calculate it
			// again
		}

		/**
		 * Adds a IP fragment to the buffer. This fragment is also the last
		 * framgent of the fragment series which carries special information
		 * about the original IP datagram.
		 *
		 * @param packet
		 *            a packet buffer containing IP fragment data
		 * @param offset
		 *            offset into this buffer where the fragment data should be
		 *            copied to
		 * @param length
		 *            the length of the fragment data
		 * @param packetOffset
		 *            offset into the packet buffer where fragment data begins
		 */
		public void addLastSegment(JBuffer packet, int offset, int length, int packetOffset) {

			addSegment(packet, offset, length, packetOffset);

			this.ipDatagramLength = start + offset + length;

			/*
			 * Trucate the size of the JBuffer to match that of ip reassebly
			 * buffer now that we know that we have received the last fragment
			 * and where it ends
			 */
			super.setSize(this.ipDatagramLength);

			/*
			 * Set Ip4 total length field, now that we know what it is
			 */
			header.length(ipDatagramLength); // Set Ip4 total length field
		}

		/**
		 * Adds a IP fragment to the buffer. The fragment data is copied into
		 * this buffer at specified offset from the supplied packet data buffer.
		 *
		 * @param packet
		 *            a packet buffer containing IP fragment data
		 * @param offset
		 *            offset into this buffer where the fragment data should be
		 *            copied to
		 * @param length
		 *            the length of the fragment data
		 * @param packetOffset
		 *            offset into the packet buffer where fragment data begins
		 */
		public void addSegment(JBuffer packet, int offset, int length, int packetOffset) {

			/*
			 * Keep track of how much data we're copied so far. Needed to
			 * determine if the reassembly process is complete.
			 */
			this.bytesCopiedIntoBuffer += length;

			/*
			 * Do the actual copy of fragment data into this buffer. The
			 * transfer is done using a native copy call.
			 */
			packet.transferTo(this, packetOffset, length, offset + start);
		}

		/**
		 * For ordering buffers according to their timeout value. This is
		 * specifically useful when using a PriorityQueue which will order the
		 * buffers for us according to the timeout timestamp. The oldest buffers
		 * are on top of the queue, while the youngest are at the bottom.
		 */
		@Override
		public int compareTo(IpReassemblyBuffer o) {
			return (int) (o.timeout - this.timeout);
		}

		/**
		 * Checks if the buffer reassembly is complete. If the number of bytes
		 * copied into this buffer including the ip header up front, equals the
		 * length of the original IP datagram, that means the fragmentation
		 * succeeded and is complete.
		 *
		 * @return true if fragmentation succeeded and completely done
		 */
		public boolean isComplete() {
			return this.ipDatagramLength == this.bytesCopiedIntoBuffer;
		}

		/**
		 * Compares the timeout timestamp against the current time. If timeout
		 * timestamp is still in the future, then it returns false. If the
		 * timestamp is in the past, then true is returned and buffer is
		 * considered timedout.
		 *
		 * @return true if buffer is timedout, otherwise false
		 */
		public boolean isTimedout() {
			return this.timeout < System.currentTimeMillis(); // Future or
			// past
		}

		/**
		 * Returns the working Ip4 header instance found at the front of this
		 * buffer
		 *
		 * @return Ip4 header for this IP datagram
		 */
		public Ip4 getIpHeader() {
			return header;
		}

		public void setTimestamp(long timestampInMicros) {
			this.timestampInMicros = timestampInMicros;

		}

		public long getTimestamp() {
			return timestampInMicros;
		}

	}

	/**
	 * Default buffer size to allocate for reassembly. Needs to be large enough
	 * to hold the Ip4 header upfront and the contetents of all fragment for a
	 * single fragmented Ip4 datagram.
	 */
	private static final int DEFAULT_REASSEMBLY_SIZE = 256 * 1024; // 8k

	// packets

	public static void doReassemble(Pcap pcap, IpReassemblyPayloadHander handler) {
		pcap.loop(-1, new IpReassembler(5 * 1000, new IpReassemblyBufferHandler() {

			private int packetNo;

			@Override
			public void nextIpDatagram(IpReassemblyBuffer buffer) {

				if (buffer.isComplete() == false) {
					log.error("WARNING: missing fragments");
				} else {

					/*
					 * Create a packet pointer. Uninitialized packet.
					 */
					JPacket packet = new JMemoryPacket(Type.POINTER);
					packetNo++;
					/**
					 * The buffer contains Ip4 header upfront followed by
					 * original Ip4 datagram payload. We peer the packet's data
					 * buffer to the reassmbly buffer, starting at the Ip4
					 * header.
					 */
					packet.peer(buffer);
					packet.getCaptureHeader().wirelen(buffer.size());
					packet.getCaptureHeader().caplen(buffer.size());

					/*
					 * Decode the packet. We know the first header is the Ip4
					 * header.
					 */
					packet.scan(Ip4.ID);
					/*
					 * Compute IP header checksum based on our new packet
					 */
					Ip4 ip = packet.getHeader(new Ip4());
					ip.checksum(ip.calculateChecksum());

					Tcp tcp = packet.getHeader(new Tcp());
					int offset = tcp.getHeaderOffset() + tcp.getHeaderLength();

					if (offset < packet.size()) {
						// If there is any data...
						handler.nextBlock(buffer.getTimestamp(), packet.getByteArray(offset, new byte[packet.size() - offset]));
					}
				}
			}
		}), null);

	}

	public static void reassemble(File file, final IpReassemblyPayloadHander handler) {
		Pcap pcap = openPcap(file);

		if (pcap != null) {
			doReassemble(pcap, handler);
		}
	}

	public static void reassemble(File file, final IpReassemblyPayloadHander handler, String filter) {
		Pcap pcap = openPcap(file);

		if (pcap != null) {
			if (filter != null) {
				log.info("using filter: " + filter);
				PcapBpfProgram program = new PcapBpfProgram();

				if (pcap.compile(program, filter, 0, 0xFFFFFF00) != Pcap.OK) {
					log.error("filter would not compile: "+ pcap.getErr());
					return;
				}

				if (pcap.setFilter(program) != Pcap.OK) {
					log.error("cannot set filter: " + pcap.getErr());
					return;
				}
			}
			doReassemble(pcap, handler);

		}
	}

	private static Pcap openPcap(File file) {
		StringBuilder errbuf = new StringBuilder();
		Pcap pcap = Pcap.openOffline(file.getAbsolutePath(), errbuf);
		if (pcap == null) {
			log.error(errbuf.toString());
		}
		return pcap;
	}

	/**
	 * Keeps track of all IP datagrams being reassembled
	 */
	private final Map<Integer, IpReassemblyBuffer> buffers = new HashMap<Integer, IpReassemblyBuffer>();

	/**
	 * User registered handler.
	 */
	private final IpReassemblyBufferHandler handler;

	/**
	 * Ip4 header we use for incoming packets from libpcap
	 */
	private final Ip4 ip = new Ip4(); // Ip4 header

	/**
	 * Amount of time in milli seconds, after which reassembly buffers are
	 * timedout out of the queue.
	 */
	private final long timeout;

	/**
	 * Timeout queue to which all new reassembly buffers are added. The queue is
	 * prioritized according to timeout timestamp of each buffer.
	 */
	private final Queue<IpReassemblyBuffer> timeoutQueue = new PriorityQueue<IpReassemblyBuffer>();

	/**
	 * Creates a reassembly handler that reassembles all incoming IP packet.
	 *
	 * @param timeout
	 *            sets the default amount of time in millis, before reassembly
	 *            buffers are timedout
	 * @param handler
	 *            user supplied handler to call with reassembled buffers
	 */
	public IpReassembler(long timeout, IpReassemblyBufferHandler handler) {
		this.timeout = timeout;
		if (handler == null) {
			throw new NullPointerException();
		}
		this.handler = handler;
	}

	/**
	 * Process an Ip4 fragment. Fragment is copied into appropriate reassembly
	 * buffer
	 *
	 * @param packet
	 *            Ip4 fragment packet
	 * @param ip
	 *            our working Ip4 header already peered to the packet
	 */
	private IpReassemblyBuffer bufferFragment(PcapPacket packet, Ip4 ip) {
		IpReassemblyBuffer buffer = getBuffer(packet, ip);

		log.info("buffering frag");
		/*
		 * Lets keep in mind that ip.getOffset() is a header offset into the
		 * packet buffer, while ip.offset() is the Ip4.offset field which is the
		 * fragment offset into the overall datagram, in multiples of 8 bytes
		 */
		final int hlen = ip.hlen() * 4;
		final int len = ip.length() - hlen;
		final int packetOffset = ip.getOffset() + hlen;
		final int dgramOffset = ip.offset() * 8;
		buffer.addSegment(packet, dgramOffset, len, packetOffset);

		if (buffer.isComplete()) {
			if (buffers.remove(ip.hashCode()) == null) {
				log.error("bufferFragment(): failed to remove buffer");
				System.exit(0);
			}
			timeoutQueue.remove(buffer);

			dispatch(buffer);
		}

		return buffer;
	}

	/**
	 * Process an Ip4 fragment. Fragment is copied into appropriate reassembly
	 * buffer. This is also a special fragment as its the last fragment of the
	 * fragmented IP datagram.
	 *
	 * @param packet
	 *            Ip4 fragment packet
	 * @param ip
	 *            our working Ip4 header already peered to the packet
	 */
	private IpReassemblyBuffer bufferLastFragment(PcapPacket packet, Ip4 ip) {
		IpReassemblyBuffer buffer = getBuffer(packet, ip);

		/*
		 * Lets keep in mind that ip.getOffset() is a header offset into the
		 * packet buffer, while ip.offset() is the Ip4.offset field which is the
		 * fragment offset into the overall datagram, in multiples of 8 bytes
		 */
		final int hlen = ip.hlen() * 4;
		final int len = ip.length() - hlen;
		final int packetOffset = ip.getOffset() + hlen;
		final int dgramOffset = ip.offset() * 8;
		buffer.addLastSegment(packet, dgramOffset, len, packetOffset);

		if (buffer.isComplete()) {
			if (buffers.remove(buffer.hashCode()) == null) {
				log.error("bufferLastFragment(): failed to remove buffer");
				System.exit(0);
			}
			timeoutQueue.remove(buffer);

			dispatch(buffer);
		}

		return buffer;
	}

	/**
	 * Calls on user's handlers nextIpDatagram() callback method.
	 *
	 * @param buffer
	 *            reassembled buffer to send to the user's callback
	 */
	private void dispatch(IpReassemblyBuffer buffer) {
		handler.nextIpDatagram(buffer);
	}

	/**
	 * Retrieves a reassembly buffer for this particular Ip packet. The supplied
	 * Ip4 header is used to determine if a buffer already exists and if not a
	 * new one is created.
	 *
	 * @param packet
	 *
	 * @param ip
	 *            Ip4 header of current Ip4 fragment
	 * @return a reassembly buffer used for reassembly of this Ip4 datagram
	 */
	private IpReassemblyBuffer getBuffer(PcapPacket packet, Ip4 ip) {

		IpReassemblyBuffer buffer = buffers.get(ip.hashCode());
		if (buffer == null) { // First time we're seeing this id

			/*
			 * Calculate when the buffer should be timedout due to missing
			 * fragments
			 */
			final long bufTimeout = System.currentTimeMillis() + this.timeout;
			buffer = new IpReassemblyBuffer(ip, DEFAULT_REASSEMBLY_SIZE, bufTimeout, ip.hashCode());
			buffer.setTimestamp(packet.getCaptureHeader().timestampInMicros());
			buffers.put(ip.hashCode(), buffer);
		}

		return buffer;
	}

	/**
	 * Catch incoming packets from libpcap and if they are Ip packets reassemble
	 * them.
	 *
	 * @param packet
	 *            a temporary singleton packet received from libpcap
	 * @param user
	 *            user object
	 */
	@Override
	public void nextPacket(PcapPacket packet, Object user) {

		if (packet.hasHeader(ip)) {
			/*
			 * Check if we have an IP fragment
			 */
			if ((ip.flags() & Ip4.FLAG_MORE_FRAGMENTS) != 0) {
				bufferFragment(packet, ip);

				/*
				 * record the last fragment
				 */
			} else {

				bufferLastFragment(packet, ip);

				/*
				 * Here we have a non-fragmented IP packet so we just pass it on
				 */
			}

			/*
			 * Our crude timeout mechanism, should be implemented as a separate
			 * thread
			 */
			timeoutBuffers();
		}
	}

	/**
	 * Check the timeout queue and timeout any buffers that are timedout. The
	 * timed out buffer are dispatched, incomplete to the user's handler.
	 * Buffers that are still on the queue, are incomplete but have not timedout
	 * yet are ignored.
	 */
	private void timeoutBuffers() {
		while (timeoutQueue.isEmpty() == false) {

			if (timeoutQueue.peek().isTimedout()) {
				dispatch(timeoutQueue.poll());
			} else {
				break;
			}
		}
	}
}


text:
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace WeehibaideeLelukowem
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(AreEqual(
                new DirectoryInfo("C:\\Scratch"),
                new DirectoryInfo("C:\\Scratch\\")));

            Console.WriteLine(AreEqual(
                new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework"),
                new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\1033\\..\\..")));

            Console.WriteLine(AreEqual(
                new DirectoryInfo("C:\\Scratch\\"),
                new DirectoryInfo("C:\\Scratch\\4760\\..\\..")));

            Console.WriteLine("Press ENTER to continue");
            Console.ReadLine();
        }

        private static bool AreEqual(DirectoryInfo dir1, DirectoryInfo dir2)
        {
            return AreEqual(dir1.FullName, dir2.FullName);
        }

        private static bool AreEqual(string folderPath1, string folderPath2)
        {
            folderPath1 = Path.GetFullPath(folderPath1);
            folderPath2 = Path.GetFullPath(folderPath2);

            if (folderPath1.Length == folderPath2.Length)
            {
                return string.Equals(folderPath1, folderPath2/*, StringComparison.OrdinalIgnoreCase*/);
            }
            else if (folderPath1.Length == folderPath2.Length + 1)
            {
                // folderPath1 = @"F:\temp\"
                // folderPath2 = @"F:\temp"
                return folderPath1.Contains(folderPath2 /*, StringComparison.OrdinalIgnoreCase*/);
            }
            else if (folderPath1.Length + 1 == folderPath2.Length)
            {
                // folderPath1 = @"F:\temp"
                // folderPath2 = @"F:\temp\"
                return folderPath2.Contains(folderPath1 /*, StringComparison.OrdinalIgnoreCase*/);
            }

            return false;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.coolweather.app.service;

import java.util.ArrayList;
import java.util.List;

import com.coolweather.app.R;
import com.coolweather.app.activity.WeatherActivity;
import com.coolweather.app.model.WeatherInfo;
import com.coolweather.app.receiver.AutoUpdateReceiver;
import com.coolweather.app.util.HttpCallbackListener;
import com.coolweather.app.util.HttpUtil;
import com.coolweather.app.util.Utility;
import com.coolweather.app.util.WeatherInfoAdapter;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.View;

public class AutoUpdateService extends Service {

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				updateWeather();
			}
		}).start();

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		String cityName=prefs.getString("city_name", "");
		String date=prefs.getString("publishDate", "");
		Notification notification = new Notification(R.drawable.logo,
				"»¶Ó½øÈë¿áÎÒÌìÆø", System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, WeatherActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
				notificationIntent, 0);
		notification.setLatestEventInfo(this, date,
				cityName, pendingIntent);
		startForeground(1, notification);

		AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
		int anHour = 60 * 60 * 1000;
		long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
		Intent i = new Intent(this, AutoUpdateReceiver.class);
		PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
		manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
		return super.onStartCommand(intent, flags, startId);
	}

	/*
	 * ¸üÐÂÌìÆøÐÅÏ¢
	 */
	private void updateWeather() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		String weatherCode = prefs.getString("weather_code", "");
		String address = "https://api.heweather.com/x3/weather?cityid="
				+ weatherCode + "&key=b37e2d400e814e82b2926d680aed42d6";
		HttpUtil.sendHttpResquest(address, new HttpCallbackListener() {

			@Override
			public void onFinish(String response) {
				Utility.handleWeatherResponse(AutoUpdateService.this, response);
			}

			@Override
			public void onError(Exception e) {
				e.printStackTrace();
			}
		});
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

}


text:
'''Creating functions for view callables'''
import datetime

from pyramid.httpexceptions import (
    HTTPNotFound,
    HTTPFound
)
from pyramid.security import remember, forget
from pyramid.view import view_config
from python_learning_journal.models.entries import Entry

from python_learning_journal.security import check_credentials

@view_config(route_name='list', renderer='../templates/index.jinja2')
def list_view(request):
    """View for the home route."""
    entries = request.dbsession.query(Entry).all()
    return {
        'page': 'List',
        'entry': entries,
    }

@view_config(route_name='detail', renderer='../templates/detail.jinja2')
def detail_view(request):
    """View for the detail route."""
    the_id = int(request.matchdict['id'])
    session = request.dbsession
    entry = session.query(Entry).get(the_id)
    if not entry:
        raise HTTPNotFound

    return {
        'page': 'Entry',
        'entry': entry
    }

@view_config(route_name="new", renderer="../templates/new_entry.jinja2")
def create_view(request):
    """View for adding a new expense to the database."""
    if request.method == "POST" and request.POST:
        if not request.POST['title']:
            return {
                'title': request.POST['title'],
                'error': "Hey dude, you're missing a little something"
            }
        new_entry = Entry(
            title=request.POST['title'],
            entry=request.POST['entry'],
            creation_date=datetime.datetime.now()
        )
        request.dbsession.add(new_entry)
        return HTTPFound(
            location=request.route_url('list')
        )

    return {}

@view_config(route_name="edit", renderer="../templates/edit_entry.jinja2")
def update_view(request):
    '''View for editing an entry.'''
    the_id = int(request.matchdict['id'])
    entry = request.dbsession.query(Entry).get(the_id)
    if not entry:
        raise HTTPNotFound
    if request.method == "GET":
        return {
            "page": "Edit Page",
            "title": entry.title,
            "entry": entry.entry
        }
    if request.method == "POST":
        entry.title = request.POST['title']
        entry.entry = request.POST['entry']
        request.dbsession.flush()
        return HTTPFound(request.route_url('detail', id=entry.id))

@view_config(route_name='login', renderer='../templates/login.jinja2')
def login(request):
    if request.method == 'POST':
        username = request.params.get('username', '')
        password = request.params.get('password', '')
        if check_credentials(username, password):
            headers = remember(request, username)
            return HTTPFound(location=request.route_url('list'), headers=headers)
    return {}

@view_config(route_name='logout')
def logout(request):
    headers = forget(request)
    return HTTPFound(request.route_url('list'), headers=headers)


text:
require 'spec_helper'

module Singularity
  describe Request do
    before {
      @request = Request.new(@data, @uri, @release)
    }

    describe '#is_paused' do
      before {
        stub_is_paused(@request, "PAUSED")
        @request.is_paused
      }
      it "should check if the request is paused" do
        expect(WebMock).to have_requested(:get, @uri+'/api/requests/request/'+@id)
      end
    end

    describe '#create' do
      before {
        WebMock.stub_request(:post, /.*/)
        @request.create
      }

      it 'should have created a request' do
        expect(WebMock).to have_requested(:post, @uri+'/api/requests').
          with(body: hash_including({'id' => @id}))
      end
    end

    describe '#delete' do
      before {
        WebMock.stub_request(:delete, /.*/)
        @request.delete
      }
      it 'should delete the request' do
        expect(WebMock).to have_requested(:delete, @uri+'/api/requests/request/'+@id)
      end
    end

    context 'when paused' do
      before {
        stub_is_paused(@request, "PAUSED")
        WebMock.stub_request(:post, /.*/)
        @response = @request.is_paused
        @request.deploy
      }

      it "should check if the request is paused" do
        expect(WebMock).to have_requested(:get, @uri+'/api/requests/request/'+@id).twice
      end

      it "should find PAUSED == true" do
        expect(@response).to equal(true)
      end

      it "should not have deployed the request" do
        expect(WebMock).not_to have_requested(:post, /.*/)
      end

    end

    context 'when not paused' do
      before {
        stub_is_paused(@request, "RUNNING")
        WebMock.stub_request(:post, /.*/)
        @response = @request.is_paused
        @request.deploy
      }

      it "should check if the request is paused" do
        expect(WebMock).to have_requested(:get, @uri+'/api/requests/request/'+@id).twice
      end

      it "should find PAUSED == false" do
        expect(@response).to equal(false)
      end

      it 'should deploy the request' do
        expect(WebMock).to have_requested(:post, @uri+'/api/deploys').
          with(body: hash_including({'user' => `whoami`.chomp}))
      end

    end

  end
end


text:
Deploying containers with an emulated domain identity is simple, and based around existing workflows using Windows Server and Active Directory.

Deploying this feature requires:
- An existing Active Directory domain, running at Windows Server 2012 or later functional level
- Windows Server 2016 with the Container role and Docker installed. This will be referred to as a **Container host**. These hosts need to be joined to the domain.

This guide will cover the following steps to deploy a container in detail:

1. Create a group Managed Service Account in the Active Directory for each application/service
2. Give each container host access to use the group Managed Service Account
3. Add configuration files on each container host that store details about the group Managed Service Accounts. These will be referred to as **Credential Specs**
4. Start containers with a parameter telling which credential spec to use

### Active Directory Setup Steps
These steps could be done using "Active Directory Users and Computers", or automated through Windows PowerShell. This guide focuses on Windows PowerShell.

For a more details on using Group Managed Service Accounts, see https://technet.microsoft.com/en-us/library/jj128431(v=ws.11).aspx

1. Before you can create the first gMSA, the domain needs a master root key. Run `Get-KdsRootKey` as a domain administrator to check if one has already been created. If there isn't a master root key created for your domain, see [Create the Key Distribution Service KDS Root Key](https://technet.microsoft.com/en-us/library/jj128430(v=ws.11).aspx) for steps to create one.

In a test environment with only one DC, this will create a root key and make it effective immediately. Do not use this for production environments.
```powershell
Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10))
```

2. Now, an Active Directory Domain Administrator can use `New-ADServiceAccount` to create a group Managed Service Account. `AccountName`, `DnsHostName`, and `ServicePrincipalName` must be passed in to uniquely identify the new account. You also need to specify what accounts can access the account after `PrincipalsAllowedToRetrieveManagedPassword`, such as a list of the container hosts or a security group containing all of container hosts that should be able to run a container using the account. In the example below "Server14362" is a container host that has already been joined to the domain. Security groups are easier to maintain if you have multiple hosts.
```
New-ADServiceAccount -name WebApplication1 -DnsHostName wa1-production.contoso.com  -ServicePrincipalNames http/wa1-production.contoso.com -PrincipalsAllowedToRetrieveManagedPassword Server14362$
```
> Tip: Create additional accounts for dev or preproduction use if needed – eg: "ProductionA" "PreprodA" "DevA"

## Container Host Setup Steps
1. First, Container hosts should be set up using the existing [deployment guide](https://msdn.microsoft.com/virtualization/windowscontainers/deployment/deployment)
2. Join the container host to the Active Directory domain
3. Verify the container host can access the gMSA
```powershell
Install-AdServiceAccount WebApplication1
Test-AdServiceAccount WebApplication1
```
This should return "True"

### Creating CredentialSpecs
1. Install and load the ActiveDirectory PowerShell module
```
Add-WindowsFeature RSAT-AD-PowerShell
Import-Module ActiveDirectory
```
2. Load the CredentialSpec module. It should be provided along with this document.
```
Import-Module ./CredentialSpec.psm1
```
3. Create a credential spec for each account using `New-CredentialSpec`. This will retrieve the needed gMSA details, and automatically format them in the needed JSON credential spec format. The `Name` will be used when starting the container later, and does not need to match the name of the container, or that of the gMSA.
```
Import-Module .\CredentialSpec.psm1
New-CredentialSpec -Name WebApplication1 -AccountName WebApplication1
```

### Viewing CredentialSpecs
The `Get-CredentialSpec` cmdlet will list the credential spec files stored on the container host.

```
Name            Path
----            ----
WebApplication1 C:\ProgramData\Docker\CredentialSpecs\WebApplication1.json
```

For reference, here is an example of the contents of WebApplication1.json
```
{"CmsPlugins":["ActiveDirectory"],"DomainJoinConfig":{"DnsName":"contoso.com","Guid":"244818ae-87ca-4fcd-92ec-e79e5252348a","DnsTreeName":"contoso.com","NetBiosName":"DEMO","Sid":"S-1-5-21-2126729477-2524075714-3094792973","MachineAccountName":"WebApplication1"},"ActiveDirectoryConfig":{"GroupManagedServiceAccounts":[{"Name":"WebApplication1","Scope":"DEMO"},{"Name":"WebApplication1","Scope":"contoso.com"}]}}
```
This is the information needed to identify the group Managed Service Account.

## Running Containers
The same `docker run` command is used to start containers, with an additional parameter `--security-opt "credentialspec=..."`. The host will use the details in the given credentialspec and start the container with the account automatically mapped.
```
docker run -it --security-opt "credentialspec=file://WebApplication1.json" microsoft/windowsservercore cmd
```

You can run `nltest.exe /parentdomain` in a container to confirm that it can reach the Active Directory domain.

If it succeeds, it will return the full domain name:
```
c:\>nltest.exe /parentdomain
contoso.com (1)
```

If it fails, then a connection couldn't be made. Be sure that it was launched with the right options, and make sure the host can access the gMSA.

```
C:\>nltest.exe /parentdomain
Getting parent domain failed: Status = 1722 0x6ba RPC_S_SERVER_UNAVAILABLE
```

## Configuring other services to accept connections from containers
Services and other processes running as 'Local System' or 'Network Service' in the container will now use the gMSA as they authenticate to other resources.

For example, an Asp.net app running as the default 'Local System' account could be reconfigured from using SQL authentication:
```
"ConnectionString": "Server=192.168.5.18;Database=MusicStore;Integrated Security=False;User Id=sa;Password=Password1;MultipleActiveResultSets=True;Connect Timeout=30"
```
To using Windows Integrated Authentication:
```
"ConnectionString": "Server=192.168.5.18;Database=MusicStore;Integrated Security=True;MultipleActiveResultSets=True;Connect Timeout=30"
```

Then run inside a container started with a credential spec:

```powershell
docker run -p 80:80 --security-opt "credentialspec=file://WebApplication1.json" -it musicstore-iis cmd
```

At this point, SQL would see a login from the gMSA included in that credentialspec. Following the examples above - this would be "contoso\WebApplication1"

## Additional group Managed Service Accounts
In addition to the default account that will be mapped to 'Local System' and 'Network Service' in the container, additional group Managed Service Accounts can also be added to a credentialspec. Once this is done, additional services can be configured to use this account inside the container instead of the default account.

Here's an example where two additional accounts - 'LogApp' and 'AuditApp' are added:

```powershell
New-CredentialSpec –Name "App2" –Domain (Get-ADDomain) –AccountName "ProductionApp" –AdditionalAccounts @{DomainName="domain.contoso.com";AccountName="LogApp"}, @{DomainName="domain.contoso.com";AccountName="AuditApp"}
```

A scheduled task or service can now be configured to use these accounts.

Example scheduled task:

```powershell
$action = New-ScheduledTaskAction "c:\myLogApp\runTask.cmd"
$trigger = New-ScheduledTaskTrigger -At 22:00 -Daily
$principal = New-ScheduledTaskPrincipal -UserID contoso\LogApp$ -LogonType Password
Register-ScheduledTask myLogTask –Action $action –Trigger $trigger –Principal $principal
```

> Tip: If you are using additional gMSA, the container will need to be rebuilt to use a different account name later. It may be better to share an image without the extra gMSAs, then have a shorter Dockerfile to build a layer that adds the right users for each deployment.


text:
package org.nd4j.bytebuddy.method.integer.relative;

import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.jar.asm.MethodVisitor;
import net.bytebuddy.jar.asm.Opcodes;

/**
 * @author Adam Gibson
 */
public class RelativeLoadIntParam implements ByteCodeAppender {
    private int offset = -1;

    public RelativeLoadIntParam(int offset) {
        this.offset = offset;
    }

    @Override
    public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
        methodVisitor.visitIntInsn(Opcodes.ILOAD,offset);
        return new Size(1,1);
    }
}


text:
from unittest import TestCase

from bottle import Bottle, redirect
from bottle_swagger import SwaggerPlugin
from webtest import TestApp

class TestBottleSwagger(TestCase):
    VALID_JSON = {"id": "123", "name": "foo"}
    INVALID_JSON = {"not_id": "123", "name": "foo"}

    SWAGGER_DEF = {
        "swagger": "2.0",
        "info": {"version": "1.0.0", "title": "bottle-swagger"},
        "consumes": ["application/json"],
        "produces": ["application/json"],
        "definitions": {
            "Thing": {
                "type": "object",
                "required": ["id"],
                "properties": {
                    "id": {"type": "string"},
                    "name": {"type": "string"}
                }
            }
        },
        "paths": {
            "/thing": {
                "get": {
                    "responses": {
                        "200": {
                            "description": "",
                            "schema": {
                                "$ref": "#/definitions/Thing"
                            }
                        }
                    }
                },
                "post": {
                    "parameters": [{
                        "name": "thing",
                        "in": "body",
                        "required": True,
                        "schema": {
                            "$ref": "#/definitions/Thing"
                        }
                    }],
                    "responses": {
                        "200": {
                            "description": "",
                            "schema": {
                                "$ref": "#/definitions/Thing"
                            }
                        }
                    }
                }
            },
            "/thing/{thing_id}": {
                "get": {
                    "parameters": [{
                        "name": "thing_id",
                        "in": "path",
                        "required": True,
                        "type": "string"
                    }],
                    "responses": {
                        "200": {
                            "description": "",
                            "schema": {
                                "$ref": "#/definitions/Thing"
                            }
                        }
                    }
                }
            },
            "/thing_query": {
                "get": {
                    "parameters": [{
                        "name": "thing_id",
                        "in": "query",
                        "required": True,
                        "type": "string"
                    }],
                    "responses": {
                        "200": {
                            "description": "",
                            "schema": {
                                "$ref": "#/definitions/Thing"
                            }
                        }
                    }
                }
            },
            "/thing_header": {
                "get": {
                    "parameters": [{
                        "name": "thing_id",
                        "in": "header",
                        "required": True,
                        "type": "string"
                    }],
                    "responses": {
                        "200": {
                            "description": "",
                            "schema": {
                                "$ref": "#/definitions/Thing"
                            }
                        }
                    }
                }
            },
            "/thing_formdata": {
                "post": {
                    "consumes": [
                        "application/x-www-form-urlencoded",
                        "multipart/form-data"
                    ],
                    "parameters": [{
                        "name": "thing_id",
                        "in": "formData",
                        "required": True,
                        "type": "string"
                    }],
                    "responses": {
                        "200": {
                            "description": "",
                            "schema": {
                                "$ref": "#/definitions/Thing"
                            }
                        }
                    }
                }
            }
        }
    }

    def test_valid_get_request_and_response(self):
        response = self._test_request()
        self.assertEqual(response.status_int, 200)

    def test_valid_post_request_and_response(self):
        response = self._test_request(method='POST')
        self.assertEqual(response.status_int, 200)

    def test_invalid_request(self):
        response = self._test_request(method='POST', request_json=self.INVALID_JSON)
        self._assert_error_response(response, 400)

    def test_invalid_response(self):
        response = self._test_request(response_json=self.INVALID_JSON)
        self._assert_error_response(response, 500)

    def test_disable_request_validation(self):
        self._test_disable_validation(validate_requests=False, expected_request_status=200,
                                      expected_response_status=500)

    def test_disable_response_validation(self):
        self._test_disable_validation(validate_responses=False, expected_request_status=400,
                                      expected_response_status=200)

    def test_disable_all_validation(self):
        self._test_disable_validation(validate_requests=False, validate_responses=False, expected_request_status=200,
                                      expected_response_status=200)

    def test_exception_handling(self):
        def throw_ex():
            raise Exception("Exception occurred")

        response = self._test_request(response_json=throw_ex)
        self._assert_error_response(response, 500)

    def test_invalid_route(self):
        response = self._test_request(url="/invalid")
        self._assert_error_response(response, 404)

    def test_ignore_invalid_route(self):
        swagger_plugin = self._make_swagger_plugin(ignore_undefined_routes=True)
        response = self._test_request(swagger_plugin=swagger_plugin, url="/invalid")
        self.assertEqual(response.status_int, 200)
        response = self._test_request(swagger_plugin=swagger_plugin, url="/invalid", method='POST',
                                      request_json=self.INVALID_JSON, response_json=self.INVALID_JSON)
        self.assertEqual(response.status_int, 200)

    def test_redirects(self):
        def _test_redirect(swagger_plugin):
            def redir():
                redirect("/actual_thing")

            response = self._test_request(response_json=redir, swagger_plugin=swagger_plugin)
            self.assertEqual(response.status_int, 302)

        _test_redirect(self._make_swagger_plugin())
        _test_redirect(self._make_swagger_plugin(ignore_undefined_routes=True))

    def test_path_parameters(self):
        response = self._test_request(url="/thing/123", route_url="/thing/<thing_id>")
        self.assertEqual(response.status_int, 200)

    def test_query_parameters(self):
        response = self._test_request(url="/thing_query?thing_id=123", route_url="/thing_query")
        self.assertEqual(response.status_int, 200)

    def test_header_parameters(self):
        response = self._test_request(url="/thing_header", route_url="/thing_header", headers={'thing_id': '123'})
        self.assertEqual(response.status_int, 200)

    def test_formdata_parameters(self):
        response = self._test_request(url="/thing_formdata", route_url="/thing_formdata", method='POST', request_json='thing_id=123', content_type='multipart/form-data')
        self.assertEqual(response.status_int, 200)

    def test_get_swagger_schema(self):
        bottle_app = Bottle()
        bottle_app.install(self._make_swagger_plugin())
        test_app = TestApp(bottle_app)
        response = test_app.get(SwaggerPlugin.DEFAULT_SWAGGER_SCHEMA_URL)
        self.assertEquals(response.json, self.SWAGGER_DEF)

    def _test_request(self, swagger_plugin=None, method='GET', url='/thing', route_url=None, request_json=VALID_JSON,
                      response_json=VALID_JSON, headers=None, content_type='application/json'):
        if swagger_plugin is None:
            swagger_plugin = self._make_swagger_plugin()
        if response_json is None:
            response_json = {}
        if route_url is None:
            route_url = url

        bottle_app = Bottle()
        bottle_app.install(swagger_plugin)

        @bottle_app.route(route_url, method)
        def do_thing(*args, **kwargs):
            return response_json() if hasattr(response_json, "__call__") else response_json

        test_app = TestApp(bottle_app)
        if method.upper() == 'GET':
            response = test_app.get(url, expect_errors=True, headers=headers)
        elif method.upper() == 'POST':
            if content_type == 'application/json':
                response = test_app.post_json(url, request_json, expect_errors=True, headers=headers)
            else:
                response = test_app.post(url, request_json, content_type=content_type, expect_errors=True, headers=headers)
        else:

            raise Exception("Invalid method {}".format(method))

        return response

    def _test_disable_validation(self, validate_requests=True, validate_responses=True, expected_request_status=200,
                                 expected_response_status=200):
        swagger_plugin = self._make_swagger_plugin(validate_requests=validate_requests,
                                                   validate_responses=validate_responses)

        response = self._test_request(swagger_plugin=swagger_plugin, method='POST', request_json=self.INVALID_JSON)
        self.assertEqual(response.status_int, expected_request_status)

        response = self._test_request(swagger_plugin=swagger_plugin, response_json=self.INVALID_JSON)
        self.assertEqual(response.status_int, expected_response_status)

    def _assert_error_response(self, response, expected_status):
        self.assertEqual(response.status_int, expected_status)
        self.assertEqual(response.json['code'], expected_status)
        self.assertIsNotNone(response.json['message'])

    def _make_swagger_plugin(self, *args, **kwargs):
        return SwaggerPlugin(self.SWAGGER_DEF, *args, **kwargs)


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="converter.css">
	<title>Rivil Converter</title>

English

		<form name="form1">
			<textarea name="textarea1" class="latin" title="Input Words" cols="4"
			          onchange="cv();" onkeyup="cv();"></textarea>
		</form>

Rivil

Rivil (latin alphabet)


text:
package com.github.stuartervine.awssugar;

public interface Sender {
    String send(String message, String queueName);

    ExplicitSender explicit(String queueName);
}


text:
package fr.openwide.core.commons.util.collections;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.common.base.Equivalence;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

public final class CollectionUtils {

	private CollectionUtils() { }

	/**
	 * Replaces all elements in dst by those in src.
	 *
This method is view-proof : it will work as expected even if src is a view of dst,
	 * i.e. if src's content depends on dst's (see for example
	 * {@link Collections#unmodifiableCollection(Collection)}, {@link Sets#union(java.util.Set, java.util.Set)}, ...).
	 *
In the process, this method may copy the elements of src in a new collection,
	 * hence it is not advisable to use it on large collections or in frequently called methods.
	 * @param dst The collection whose content is to be replaced. Not null.
	 * @param src The collection whose content is to be copied to dst, or null to simply clear dst.
	 */
	public static <T> void replaceAll(Collection<T> dst, Collection<? extends T> src) {
		if (src == null) {
			dst.clear();
		} else {
			Collection<T> elements = Lists.newArrayList(src);
			dst.clear();
			dst.addAll(elements);
		}
	}

	/**
	 * Same as {@link CollectionUtils#replaceAll(Collection, Collection)}, but for {@link Map Maps}
	 */
	public static <K, V> void replaceAll(Map<K, V> dst, Map<? extends K, ? extends V> src) {
		if (src == null) {
			dst.clear();
		} else {
			Map<K, V> elements = Maps.newLinkedHashMap(src);
			dst.clear();
			dst.putAll(elements);
		}
	}

	/**
	 * WARNING: very low efficiency (O(N*N))
	 * @return A list containing the elements of source that are not in filter, using equivalence to distinguish different elements.
	 */
	public static <T> List<T> difference(Iterable<? extends T> source, Iterable<? extends T> filter, Equivalence<? super T> equivalence) {
		final List<T> result = new LinkedList<T>();
		if (source != null && filter != null) {
			sourceLoop: for (T sourceElement : source) {
				for (T filterElement : filter) {
					if (equivalence.equivalent(sourceElement, filterElement)) {
						continue sourceLoop;
					}
				}
				result.add(sourceElement);
			}
		} else if (source != null && filter == null) {
			Iterables.addAll(result, source);
		}
		return result;
	}

	/**
	 * WARNING: very low efficiency (O(N*N))
	 * @return A list containing the elements of source that are also in filter, using equivalence to distinguish different elements.
	 */
	public static <T> List<T> intersection(Iterable<? extends T> source, Iterable<? extends T> filter, Equivalence<? super T> equivalence) {
		final List<T> result = new LinkedList<T>();
		if (source != null && filter != null) {
			sourceLoop: for (T sourceElement : source) {
				for (T filterElement : filter) {
					if (equivalence.equivalent(sourceElement, filterElement)) {
						result.add(sourceElement);
						continue sourceLoop;
					}
				}
			}
		}
		return result;
	}

}


text:
<?php namespace Comodojo\Dispatcher\Response\Preprocessor;

use \Comodojo\Dispatcher\Response\Model as Response;
use \Exception;

class Status301 extends Status200 {

    /**
     * {@inheritdoc}
     */
    public function consolidate(Response $response) {

        $location = $response->getLocation()->get();

        if (empty($location)) {
            throw new Exception("Invalid location, cannot redirect");
        }

        $response->getHeaders()->set("Location", $location);

        $content = $response->getContent();

        if (empty($content->get())) {

            $content->set(sprintf('<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=%1$s" />
        <title>Redirecting to %1$s</title>

        Redirecting to %1$s.

', htmlspecialchars($location, ENT_QUOTES, 'UTF-8')));

        }

        parent::consolidate();

    }

}


text:
package com.microsoft.azure.management.hdinsight.v2015_03_01_preview;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The properties of cluster.
 */
public class ClusterGetProperties {
    /**
     * The version of the cluster.
     */
    @JsonProperty(value = "clusterVersion")
    private String clusterVersion;

    /**
     * The type of operating system. Possible values include: 'Windows',
     * 'Linux'.
     */
    @JsonProperty(value = "osType")
    private OSType osType;

    /**
     * The cluster tier. Possible values include: 'Standard', 'Premium'.
     */
    @JsonProperty(value = "tier")
    private Tier tier;

    /**
     * The cluster definition.
     */
    @JsonProperty(value = "clusterDefinition", required = true)
    private ClusterDefinition clusterDefinition;

    /**
     * The security profile.
     */
    @JsonProperty(value = "securityProfile")
    private SecurityProfile securityProfile;

    /**
     * The compute profile.
     */
    @JsonProperty(value = "computeProfile")
    private ComputeProfile computeProfile;

    /**
     * The provisioning state, which only appears in the response. Possible
     * values include: 'InProgress', 'Failed', 'Succeeded', 'Canceled',
     * 'Deleting'.
     */
    @JsonProperty(value = "provisioningState")
    private HDInsightClusterProvisioningState provisioningState;

    /**
     * The date on which the cluster was created.
     */
    @JsonProperty(value = "createdDate")
    private String createdDate;

    /**
     * The state of the cluster.
     */
    @JsonProperty(value = "clusterState")
    private String clusterState;

    /**
     * The quota information.
     */
    @JsonProperty(value = "quotaInfo")
    private QuotaInfo quotaInfo;

    /**
     * The list of errors.
     */
    @JsonProperty(value = "errors")
    private List<Errors> errors;

    /**
     * The list of connectivity endpoints.
     */
    @JsonProperty(value = "connectivityEndpoints")
    private List<ConnectivityEndpoint> connectivityEndpoints;

    /**
     * Get the version of the cluster.
     *
     * @return the clusterVersion value
     */
    public String clusterVersion() {
        return this.clusterVersion;
    }

    /**
     * Set the version of the cluster.
     *
     * @param clusterVersion the clusterVersion value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withClusterVersion(String clusterVersion) {
        this.clusterVersion = clusterVersion;
        return this;
    }

    /**
     * Get the type of operating system. Possible values include: 'Windows', 'Linux'.
     *
     * @return the osType value
     */
    public OSType osType() {
        return this.osType;
    }

    /**
     * Set the type of operating system. Possible values include: 'Windows', 'Linux'.
     *
     * @param osType the osType value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withOsType(OSType osType) {
        this.osType = osType;
        return this;
    }

    /**
     * Get the cluster tier. Possible values include: 'Standard', 'Premium'.
     *
     * @return the tier value
     */
    public Tier tier() {
        return this.tier;
    }

    /**
     * Set the cluster tier. Possible values include: 'Standard', 'Premium'.
     *
     * @param tier the tier value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withTier(Tier tier) {
        this.tier = tier;
        return this;
    }

    /**
     * Get the cluster definition.
     *
     * @return the clusterDefinition value
     */
    public ClusterDefinition clusterDefinition() {
        return this.clusterDefinition;
    }

    /**
     * Set the cluster definition.
     *
     * @param clusterDefinition the clusterDefinition value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withClusterDefinition(ClusterDefinition clusterDefinition) {
        this.clusterDefinition = clusterDefinition;
        return this;
    }

    /**
     * Get the security profile.
     *
     * @return the securityProfile value
     */
    public SecurityProfile securityProfile() {
        return this.securityProfile;
    }

    /**
     * Set the security profile.
     *
     * @param securityProfile the securityProfile value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withSecurityProfile(SecurityProfile securityProfile) {
        this.securityProfile = securityProfile;
        return this;
    }

    /**
     * Get the compute profile.
     *
     * @return the computeProfile value
     */
    public ComputeProfile computeProfile() {
        return this.computeProfile;
    }

    /**
     * Set the compute profile.
     *
     * @param computeProfile the computeProfile value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withComputeProfile(ComputeProfile computeProfile) {
        this.computeProfile = computeProfile;
        return this;
    }

    /**
     * Get the provisioning state, which only appears in the response. Possible values include: 'InProgress', 'Failed', 'Succeeded', 'Canceled', 'Deleting'.
     *
     * @return the provisioningState value
     */
    public HDInsightClusterProvisioningState provisioningState() {
        return this.provisioningState;
    }

    /**
     * Set the provisioning state, which only appears in the response. Possible values include: 'InProgress', 'Failed', 'Succeeded', 'Canceled', 'Deleting'.
     *
     * @param provisioningState the provisioningState value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withProvisioningState(HDInsightClusterProvisioningState provisioningState) {
        this.provisioningState = provisioningState;
        return this;
    }

    /**
     * Get the date on which the cluster was created.
     *
     * @return the createdDate value
     */
    public String createdDate() {
        return this.createdDate;
    }

    /**
     * Set the date on which the cluster was created.
     *
     * @param createdDate the createdDate value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withCreatedDate(String createdDate) {
        this.createdDate = createdDate;
        return this;
    }

    /**
     * Get the state of the cluster.
     *
     * @return the clusterState value
     */
    public String clusterState() {
        return this.clusterState;
    }

    /**
     * Set the state of the cluster.
     *
     * @param clusterState the clusterState value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withClusterState(String clusterState) {
        this.clusterState = clusterState;
        return this;
    }

    /**
     * Get the quota information.
     *
     * @return the quotaInfo value
     */
    public QuotaInfo quotaInfo() {
        return this.quotaInfo;
    }

    /**
     * Set the quota information.
     *
     * @param quotaInfo the quotaInfo value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withQuotaInfo(QuotaInfo quotaInfo) {
        this.quotaInfo = quotaInfo;
        return this;
    }

    /**
     * Get the list of errors.
     *
     * @return the errors value
     */
    public List<Errors> errors() {
        return this.errors;
    }

    /**
     * Set the list of errors.
     *
     * @param errors the errors value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withErrors(List<Errors> errors) {
        this.errors = errors;
        return this;
    }

    /**
     * Get the list of connectivity endpoints.
     *
     * @return the connectivityEndpoints value
     */
    public List<ConnectivityEndpoint> connectivityEndpoints() {
        return this.connectivityEndpoints;
    }

    /**
     * Set the list of connectivity endpoints.
     *
     * @param connectivityEndpoints the connectivityEndpoints value to set
     * @return the ClusterGetProperties object itself.
     */
    public ClusterGetProperties withConnectivityEndpoints(List<ConnectivityEndpoint> connectivityEndpoints) {
        this.connectivityEndpoints = connectivityEndpoints;
        return this;
    }

}


text:
<?php
/*
$notifyquery="SELECT * FROM notify_attendance WHERE StudentID=$username";
if ($notifyquery_run=mysqli_query($link,$notifyquery)){
    if (mysqli_num_rows($notifyquery_run) != NULL) {
        while ($notifyquery_row = mysqli_fetch_assoc($notifyquery_run)) {
            $attendance =100- $notifyquery_row['Absence'];
            echo 'You have a poor attendance of ' . $attendance . '% for this year.'.'

';
            $delequery="DELETE FROM notify_attendance WHERE StudentID=$username";
            $delequery_run=mysqli_query($link,$delequery);
        }
    }

}
*/
$username=$_SESSION['username'];
$query = "SELECT Role FROM users WHERE username = '$username'";
$query_run = mysqli_query($link, $query);
$query_row = mysqli_fetch_assoc($query_run);
$role = $query_row['Role'];
if ($role== 'student') {
    $attendance_query = "SELECT Attendance, Date FROM attendance WHERE StudentID = '$username'";
    $attendance_query_run = mysqli_query($link, $attendance_query);
    $count = 0;
    $days = 0;
    while ($attendance_row = mysqli_fetch_assoc($attendance_query_run)) {
        $attendance = $attendance_row['Attendance'];
        $date = $attendance_row['Date'];
        $days++;
        if (strtoupper($attendance) == 'A') {
            $count++;
        }
    }
    if ($count>0) {
        $absence = floor(($count * 10000) / ($days * 100));
        $attendance = 100 - $absence;
        if ($absence > 20) {
            echo '
You have a poor attendance rate of ' . $attendance . '%.
';
        }
    }
}


text:
package org.apache.axis2.jaxws.sample.headershandler;

import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;

public class HandlerTracker {

    private static final String filelogname = "target/HeadersHandlerTests.log";

    private String classname;

    private static final String CLOSE = "CLOSE";
    private static final String GET_HEADERS = "GET_HEADERS";
    private static final String HANDLE_FAULT_INBOUND = "HANDLE_FAULT_INBOUND";
    private static final String HANDLE_MESSAGE_INBOUND = "HANDLE_MESSAGE_INBOUND";
    private static final String HANDLE_FAULT_OUTBOUND = "HANDLE_FAULT_OUTBOUND";
    private static final String HANDLE_MESSAGE_OUTBOUND = "HANDLE_MESSAGE_OUTBOUND";
    private static final String POST_CONSTRUCT = "POST_CONSTRUCT";
    private static final String PRE_DESTROY = "PRE_DESTROY";
    private static final String ADDED_HEADER = "ADDED_HEADER";
    private static final String CHECKED_HEADER = "CHECKED_HEADER";
    private static final String REMOVED_HEADER = "REMOVED_HEADER";

    // should pass classname for "name"
    public HandlerTracker(String name) {
        classname = name;
    }

    public void postConstruct() {
        log_to_file(POST_CONSTRUCT);
    }

    public void preDestroy() {
        log_to_file(PRE_DESTROY);
    }

    public void close() {
        log_to_file(CLOSE);
    }

    public void getHeaders() {
        log_to_file(GET_HEADERS);
    }

    public void addHeader(String xmlHeader) {
    	log_to_file(ADDED_HEADER + " " + xmlHeader);
    }

    public void checkHeader(String xmlHeader) {
    	log_to_file(CHECKED_HEADER + " " + xmlHeader);
    }

    public void removedHeader(String xmlHeader) {
    	log_to_file(REMOVED_HEADER + " " + xmlHeader);
    }

    public void handleFault(boolean outbound) {
        if (outbound) {
            log_to_file(HANDLE_FAULT_OUTBOUND);
        } else {
            log_to_file(HANDLE_FAULT_INBOUND);
        }
    }

    public void handleMessage(boolean outbound) {
        if (outbound) {
            log_to_file(HANDLE_MESSAGE_OUTBOUND);
        } else {
            log_to_file(HANDLE_MESSAGE_INBOUND);
        }
    }

    public void log(String msg, boolean outbound) {
        log_to_file(msg + " " + (outbound ? "OUTBOUND" : "INBOUND"));
    }

    /*
     * we have to open and close the file every time we write
     * as other handler method calls may be interleaved with this one
     */
    private void log_to_file(String msg) {
        try {
            FileWriter fw = new FileWriter(filelogname, true);
            fw.write(classname + " " + msg + "\n");
            fw.flush();
            fw.close();
        } catch (Exception e) {
        }
    }

    public void log_exception_to_file(String filename, Throwable e) {
    	try {
    		FileWriter fw = new FileWriter(filename, true);
    		StringWriter sw = new StringWriter();
    	    PrintWriter pw = new PrintWriter(sw);
    	    e.printStackTrace(pw);
    	    fw.write(sw.toString());
    	    fw.flush();
    	    fw.close();
    	} catch (Exception ex) {
    	}
    }

    public void log_to_my_file(String filename, String msg) {
    	try {
    		FileWriter fw = new FileWriter(filename, true);
    	    fw.write(msg);
    	    fw.flush();
    	    fw.close();
    	} catch (Exception ex) {
    	}
    }

}


text:
/**
 * @file
 * Defines a backwards-compatible shim for jquery.cookie.
 */

/**
 * The core/js-cookie library object.
 *
 * @global
 *
 * @var {object} Cookies
 */

(($, Drupal, cookies) => {
  const deprecatedMessageSuffix = `is deprecated in Drupal 9.0.0 and will be removed in Drupal 10.0.0. Use the core/js-cookie library instead. See https://www.drupal.org/node/3104677`;

  /**
   * Determines if an object is a function.
   *
   * @param {Object} obj
   *   The object to check.
   *
   * @return {boolean}
   *   True if the object is a function.
   */
  const isFunction = (obj) =>
    Object.prototype.toString.call(obj) === '[object Function]';

  /**
   * Decodes cookie value for compatibility with jquery.cookie.
   *
   * @param {string} value
   *   The cookie value to parse.
   * @param {boolean} parseJson
   *   Whether cookie value should be parsed from JSON.
   *
   * @return {string}
   *   The cookie value for the reader to return.
   */
  const parseCookieValue = (value, parseJson) => {
    if (value.indexOf('"') === 0) {
      value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
    }

    try {
      value = decodeURIComponent(value.replace(/\+/g, ' '));
      return parseJson ? JSON.parse(value) : value;
    } catch (e) {
      // Exceptions on JSON parsing should be ignored.
    }
  };

  /**
   * Wraps the cookie value to support unsanitized values.
   *
   * Decoding strings is the job of the converter when using js-cookie, and
   * the shim uses the same decode function as that library when the deprecated
   * raw option is not used.
   *
   * @param {string} cookieValue
   *   The cookie value.
   * @param {string} cookieName
   *   The cookie name.
   * @param {reader~converterCallback} converter
   *   A function that takes the cookie value for further processing.
   * @param {boolean} readUnsanitized
   *   Uses the unsanitized value when set to true.
   * @param {boolean} parseJson
   *   Whether cookie value should be parsed from JSON.
   *
   * @return {string}
   *   The cookie value that js-cookie will return.
   */
  const reader = (
    cookieValue,
    cookieName,
    converter,
    readUnsanitized,
    parseJson,
  ) => {
    const value = readUnsanitized
      ? cookieValue
      : parseCookieValue(cookieValue, parseJson);

    if (converter !== undefined && isFunction(converter)) {
      return converter(value, cookieName);
    }

    return value;
  };

  /**
   * Gets or sets a browser cookie.
   *
   * @example
   * // Returns 'myCookie=myCookieValue'.
   * $.cookie('myCookie', 'myCookieValue');
   * @example
   * // Returns 'myCookieValue'.
   * $.cookie('myCookie');
   *
   * @example
   * // Returns the literal URI-encoded value of {"key": "value"} as the cookie
   * // value along with the path as in the above example.
   * $.cookie('myCookie', { key: 'value' });
   * @example
   * $.cookie.json = true;
   * // Returns { key: 'value' }.
   * $.cookie('myCookie');
   *
   * @param {string} key
   *   The name of the cookie.
   * @param {string|Object|Function|undefined} value
   *   A js-cookie converter callback when used as a getter. This callback must
   *   be a function when using this shim for backwards-compatibility with
   *   jquery.cookie. When used as a setter, value is the string or JSON object
   *   to be used as the cookie value.
   * @param {Object|undefined} options
   *   Overrides the default options when used as a setter. See the js-cookie
   *   library README.md file for details.
   *
   * @return {string}
   *   Returns the cookie name, value, and other properties based on the
   *   return value of the document.cookie setter.
   *
   * @deprecated in Drupal 9.0.0 and is removed from Drupal 10.0.0.
   *   Use the core/js-cookie library instead.
   *
   * @see https://www.drupal.org/node/3104677
   * @see https://github.com/js-cookie/js-cookie/blob/v3.0.1/README.md
   */
  $.cookie = (key, value = undefined, options = undefined) => {
    Drupal.deprecationError({
      message: `jQuery.cookie() ${deprecatedMessageSuffix}`,
    });

    if (value !== undefined && !isFunction(value)) {
      // The caller is setting a cookie value and not trying to retrieve the
      // cookie value using a converter callback.
      const attributes = { ...$.cookie.defaults, ...options };

      if (typeof attributes.expires === 'string' && attributes.expires !== '') {
        attributes.expires = new Date(attributes.expires);
      }

      const cookieSetter = cookies.withConverter({
        write: (cookieValue) => encodeURIComponent(cookieValue),
      });

      value =
        $.cookie.json && !$.cookie.raw ? JSON.stringify(value) : String(value);

      return cookieSetter.set(key, value, attributes);
    }

    // Use either js-cookie or pass in a converter to get the raw cookie value,
    // which has security implications, but remains in place for
    // backwards-compatibility.
    const userProvidedConverter = value;
    const cookiesShim = cookies.withConverter({
      read: (cookieValue, cookieName) =>
        reader(
          cookieValue,
          cookieName,
          userProvidedConverter,
          $.cookie.raw,
          $.cookie.json,
        ),
    });

    if (key !== undefined) {
      return cookiesShim.get(key);
    }

    const results = cookiesShim.get();
    Object.keys(results).forEach((resultKey) => {
      if (results[resultKey] === undefined) {
        delete results[resultKey];
      }
    });

    return results;
  };

  /**
   * @prop {Object} defaults
   *   The default options when setting a cookie.
   * @prop {string} defaults.path
   *   The default path for the cookie is ''.
   * @prop {undefined} defaults.expires
   *   There is no default value for the expires option. The default expiration
   *   is set to an empty string.
   */
  $.cookie.defaults = { path: '', ...cookies.defaults };

  /**
   * @prop {boolean} json
   *   True if the cookie value should be parsed as JSON.
   */
  $.cookie.json = false;

  /**
   * @prop {boolean} json
   *   True if the cookie value should be returned as-is without decoding
   *   URI entities. In jquery.cookie, this also would not encode the cookie
   *   name, but js-cookie does not allow this.
   */
  $.cookie.raw = false;

  /**
   * Removes a browser cookie.
   *
   * @param {string} key
   *   The name of the cookie.
   * @param {Object} options
   *   Optional options. See the js-cookie library README.md for more details.
   *
   * @return {boolean}
   *   Returns true when the cookie is successfully removed.
   *
   * @deprecated in Drupal 9.0.0 and is removed from Drupal 10.0.0.
   *   Use the core/js-cookie library instead.
   *
   * @see https://www.drupal.org/node/3104677
   * @see https://github.com/js-cookie/js-cookie/blob/v3.0.1/README.md
   */
  $.removeCookie = (key, options) => {
    Drupal.deprecationError({
      message: `jQuery.removeCookie() ${deprecatedMessageSuffix}`,
    });
    cookies.remove(key, { ...$.cookie.defaults, ...options });
    return !cookies.get(key);
  };
})(jQuery, Drupal, window.Cookies);


text:
package javax.swing;

import gnu.java.lang.CPStringBuilder;

import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.swing.plaf.ButtonUI;

/**
 * A general purpose push button. JButtons can display a label,
 * an {@link Icon} or both.
 *
 * @author Ronald Veldema (rveldema@cs.vu.nl)
 */
public class JButton extends AbstractButton
  implements Accessible
{

  /**
   * Accessibility support for JButtons.
   */
  protected class AccessibleJButton
    extends AbstractButton.AccessibleAbstractButton
  {
    /**
     * Returns the accessible role that this component represents.
     * This is {@link AccessibleRole#PUSH_BUTTON} for JButtons.
     *
     * @return the accessible role that this component represents
     */
    public AccessibleRole getAccessibleRole()
    {
      return AccessibleRole.PUSH_BUTTON;
    }
  }

  private static final long serialVersionUID = -1907255238954382202L;

  /**
   * Indicates if this button is capable to become the default button.
   */
  private boolean defaultCapable;

  /**
   * Creates a new button with an empty string for the button text and no
   * icon.
   */
  public JButton()
  {
    this(null, null);
  }

  /**
   * Creates a new button from the specified action.
   *
   * @param a  the action (null permitted).
   *
   * @see AbstractButton#setAction(Action)
   */
  public JButton(Action a)
  {
    this();
    setAction(a);
  }

  /**
   * Creates a new button with the specified icon (and an empty string for
   * the button text).
   *
   * @param icon  the icon (null permitted).
   */
  public JButton(Icon icon)
  {
    this(null, icon);
  }

  /**
   * Creates a new button with the specified text and no icon.
   *
   * @param text  the button text (null permitted, will be
   *     substituted by an empty string).
   */
  public JButton(String text)
  {
    this(text, null);
  }

  /**
   * Creates a new button with the specified text and icon.
   *
   * @param text  the button text (null permitted, will be
   *     substituted by an empty string).
   * @param icon  the icon (null permitted).
   */
  public JButton(String text, Icon icon)
  {
    super();
    setModel(new DefaultButtonModel());
    init(text, icon);
    defaultCapable = true;
  }

  protected void configurePropertiesFromAction(Action a)
  {
    super.configurePropertiesFromAction(a);
  }

  /**
   * Returns the object that provides accessibility features for this
   * JButton component.
   *
   * @return The accessible context (an instance of {@link AccessibleJButton}).
   */
  public AccessibleContext getAccessibleContext()
  {
    if (accessibleContext == null)
      accessibleContext = new AccessibleJButton();
    return accessibleContext;
  }

  /**
   * Returns the suffix ("ButtonUI" in this case) used to
   * determine the class name for a UI delegate that can provide the look and
   * feel for a JButton.
   *
   * @return "ButtonUI".
   */
  public String getUIClassID()
  {
    // Returns a string that specifies the name of the L&F class that renders
    // this component.
    return "ButtonUI";
  }

  /**
   * Returns true if this button is the default button in
   * its JRootPane. The default button gets automatically
   * activated when the user presses ENTER (or whatever
   * key this is bound to in the current Look and Feel).
   *
   * @return true if this button is the default button in
   *         its JRootPane
   *
   * @see #isDefaultCapable()
   * @see #setDefaultCapable(boolean)
   * @see JRootPane#getDefaultButton()
   * @see JRootPane#setDefaultButton(JButton)
   */
  public boolean isDefaultButton()
  {
    // The default button is managed by the JRootPane, so the safest way
    // to determine this property is to ask the root pane of this button,
    // if it exists.
    JRootPane rp = SwingUtilities.getRootPane(this);
    boolean isDefault = false;
    if (rp != null)
      isDefault = rp.getDefaultButton() == this;
    return isDefault;
  }

  /**
   * Returns true if this button can act as the default button.
   * This is true by default.
   *
   * @return true if this button can act as the default button
   *
   * @see #setDefaultCapable(boolean)
   * @see #isDefaultButton()
   * @see JRootPane#getDefaultButton()
   * @see JRootPane#setDefaultButton(JButton)
   */
  public boolean isDefaultCapable()
  {
    // Returns whether or not this button is capable of being the default
    // button on the RootPane.
    return defaultCapable;
  }

  /**
   * Returns an implementation-dependent string describing the attributes of
   * this JButton.
   *
   * @return A string describing the attributes of this JButton
   *         (never null).
   */
  protected String paramString()
  {
    String superParam = super.paramString();

    // 41 is the maximum number of chars which may be needed.
    CPStringBuilder sb = new CPStringBuilder(41);
    sb.append(",defaultButton=").append(isDefaultButton());
    sb.append(",defaultCapable=").append(defaultCapable);

    return superParam + sb.toString();
  }

  /**
   * Overrides JComponent.removeNotify to check if this button is currently
   * set as the default button on the RootPane, and if so, sets the RootPane's
   * default button to null to ensure the RootPane doesn't hold onto an invalid
   * button reference.
   */
  public void removeNotify()
  {
    JRootPane root = SwingUtilities.getRootPane(this);
    if (root != null && root.getDefaultButton() == this)
      root.setDefaultButton(null);
    super.removeNotify();
  }

  /**
   * Sets the defaultCapable property which indicates if
   * this button may become the default button in its JRootPane.
   *
   * @param defaultCapable true if this button can become the
   *        default button in its JRootPane, false otherwise
   *
   * @see #setDefaultCapable(boolean)
   * @see #isDefaultButton()
   * @see JRootPane#getDefaultButton()
   * @see JRootPane#setDefaultButton(JButton)
   */
  public void setDefaultCapable(boolean defaultCapable)
  {
    this.defaultCapable = defaultCapable;
  }

  /**
   * Sets this button's UI delegate to the default (obtained from the
   * {@link UIManager}) for the current look and feel.
   */
  public void updateUI()
  {
    setUI((ButtonUI) UIManager.getUI(this));
  }
}