text:
package com.github.bleeding182.relativetimespan;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by David on 22.02.2016.
 */
public class TimeAdapter extends RecyclerView.Adapter<TimeAdapter.ViewHolder> {

    public static final long[] mTimestamps = new long[]{
            0,
            DateUtils.SECOND_IN_MILLIS,
            2 * DateUtils.SECOND_IN_MILLIS,
            5 * DateUtils.SECOND_IN_MILLIS,
            10 * DateUtils.SECOND_IN_MILLIS,
            30 * DateUtils.SECOND_IN_MILLIS,
            DateUtils.MINUTE_IN_MILLIS,
            2 * DateUtils.MINUTE_IN_MILLIS,
            5 * DateUtils.MINUTE_IN_MILLIS,
            10 * DateUtils.MINUTE_IN_MILLIS,
            30 * DateUtils.MINUTE_IN_MILLIS,
            DateUtils.HOUR_IN_MILLIS,
            2 * DateUtils.HOUR_IN_MILLIS,
            5 * DateUtils.HOUR_IN_MILLIS,
            10 * DateUtils.HOUR_IN_MILLIS,
            24 * DateUtils.HOUR_IN_MILLIS,
            36 * DateUtils.HOUR_IN_MILLIS,
            72 * DateUtils.HOUR_IN_MILLIS,
            4 * DateUtils.DAY_IN_MILLIS,
            5 * DateUtils.DAY_IN_MILLIS,
            7 * DateUtils.DAY_IN_MILLIS,
            14 * DateUtils.DAY_IN_MILLIS,
            21 * DateUtils.DAY_IN_MILLIS,
            DateUtils.DAY_IN_MILLIS * 30,
            2 * DateUtils.DAY_IN_MILLIS * 30,
            3 * DateUtils.DAY_IN_MILLIS * 30,
            DateUtils.DAY_IN_MILLIS * 30 * 12,
            2 * DateUtils.DAY_IN_MILLIS * 30 * 12
    };
    private int mFlags;
    private long mMinResolution;
    private long mTransitionResolution = DateUtils.DAY_IN_MILLIS;

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final Context context = parent.getContext();
        final LayoutInflater inflater = LayoutInflater.from(context);
        final View view = inflater.inflate(R.layout.item_list_entry, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Context context = holder.itemView.getContext();
        long now = System.currentTimeMillis();
        holder.mTextView1.setText(DateUtils.getRelativeDateTimeString(context,
                now - mTimestamps[position], mMinResolution, mTransitionResolution, mFlags));
        holder.mTextView2.setText(DateUtils.getRelativeTimeSpanString(now - mTimestamps[position], now, mMinResolution, mFlags));
    }

    @Override
    public int getItemCount() {
        return mTimestamps.length;
    }

    public void addFlag(int flag) {
        mFlags |= flag;
        notifyDataSetChanged();
    }

    public void removeFlag(int flag) {
        mFlags &= ~flag;
        notifyDataSetChanged();
    }

    public void setMinResolution(long minResolution) {
        mMinResolution = minResolution;
        notifyDataSetChanged();
    }

    public void setTransitionResolution(long transitionResolution) {
        mTransitionResolution = transitionResolution;
        notifyDataSetChanged();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public final TextView mTextView1;
        public final TextView mTextView2;

        public ViewHolder(View itemView) {
            super(itemView);
            mTextView1 = (TextView) itemView.findViewById(android.R.id.text1);
            mTextView2 = (TextView) itemView.findViewById(android.R.id.text2);
        }
    }

}


text:
/*! `crmsh` grammar compiled for Highlight.js 11.4.0 */
(()=>{var e=(()=>{"use strict";return e=>{
const t="group clone ms master location colocation order fencing_topology rsc_ticket acl_target acl_group user role tag xml"
;return{name:"crmsh",aliases:["crm","pcmk"],case_insensitive:!0,keywords:{
keyword:"params meta operations op rule attributes utilization read write deny defined not_defined in_range date spec in ref reference attribute type xpath version and or lt gt tag lte gte eq ne \\ number string",
literal:"Master Started Slave Stopped start promote demote stop monitor true false"
},contains:[e.HASH_COMMENT_MODE,{beginKeywords:"node",starts:{
end:"\\s*([\\w_-]+:)?",starts:{className:"title",end:"\\s*[\\$\\w_][\\w_-]*"}}
},{beginKeywords:"primitive rsc_template",starts:{className:"title",
end:"\\s*[\\$\\w_][\\w_-]*",starts:{end:"\\s*@?[\\w_][\\w_\\.:-]*"}}},{
begin:"\\b("+t.split(" ").join("|")+")\\s+",keywords:t,starts:{
className:"title",end:"[\\$\\w_][\\w_-]*"}},{
beginKeywords:"property rsc_defaults op_defaults",starts:{className:"title",
end:"\\s*([\\w_-]+:)?"}},e.QUOTE_STRING_MODE,{className:"meta",
begin:"(ocf|systemd|service|lsb):[\\w_:-]+",relevance:0},{className:"number",
begin:"\\b\\d+(\\.\\d+)?(ms|s|h|m)?",relevance:0},{className:"literal",
begin:"[-]?(infinity|inf)",relevance:0},{className:"attr",
begin:/([A-Za-z$_#][\w_-]+)=/,relevance:0},{className:"tag",begin:"</?",
end:"/?>",relevance:0}]}}})();hljs.registerLanguage("crmsh",e)})();

redpajama_set_name: RedPajamaGithub


text:
int
APPLY_SPECIFIC(conv_gw)(CudaNdarray *input, CudaNdarray *output,
                        CudaNdarray *km, cudnnConvolutionDescriptor_t desc,
                        float alpha, float beta, CudaNdarray **kerns) {
  cudnnStatus_t err = CUDNN_STATUS_SUCCESS;

  if (CudaNdarray_HOST_DIMS(input)[1] != CudaNdarray_HOST_DIMS(km)[1]) {
    PyErr_SetString(PyExc_ValueError,
                   "GpuDnnConv images and kernel must have the same stack size\n");
    return 1;
  }

  if (c_set_tensorNd(input, APPLY_SPECIFIC(input)) == -1)
    return 1;
  if (c_set_tensorNd(output, APPLY_SPECIFIC(output)) == -1)
    return 1;

  int nb_dim = CudaNdarray_NDIM(output);

#ifdef CONV_INPLACE
  Py_XDECREF(*kerns);
  *kerns = km;
  Py_INCREF(*kerns);
#else
  if (CudaNdarray_prep_output(kerns, nb_dim, CudaNdarray_HOST_DIMS(km)) != 0)
    return 1;
  if (beta != 0.0 && CudaNdarray_CopyFromCudaNdarray(*kerns, km))
    return 1;
#endif

  if (c_set_filterNd(*kerns, APPLY_SPECIFIC(kerns)) == -1)
    return 1;

#if defined(CUDNN_VERSION) && CUDNN_VERSION >= 3000
  {
    size_t worksize;
    void *workspace;
    cudnnConvolutionBwdFilterAlgo_t chosen_algo;

    if (CHOOSE_ALGO)
    {

      // A new convolution implementation should be selected, based either on
      // timing or heuristics, if in one of the two following cases :
      // - The implementation should only be chosen during the first execution
      //   of an apply node and this is the first execution of the apply node.
      // - The implementation should be chosen as often as necessary and the
      //   shapes of the inputs differ from the last time an implementation
      //   was chosen.
      bool reuse_previous_algo;
      if (CHOOSE_ALGO_ONCE)
      {
        // Only choose a new implementation of none has been chosen before.
        reuse_previous_algo = APPLY_SPECIFIC(previous_algo_set);
      }
      else
      {
        // Reuse the previous implementation if the the kernels and the outputs
        // have the same shapes as they had when the previous implementation
        // was selected
        bool same_shapes = true;
        for (int i = 0; (i < nb_dim) && same_shapes; i++)
        {
            same_shapes &= (CudaNdarray_HOST_DIMS(input)[i] ==
                            APPLY_SPECIFIC(previous_input_shape)[i]);
            same_shapes &= (CudaNdarray_HOST_DIMS(output)[i] ==
                            APPLY_SPECIFIC(previous_output_shape)[i]);
        }
        reuse_previous_algo = same_shapes;
      }

      // If the previously choosen implementation can't be reused, select a
      // new one based on the shapes of the current inputs
      if (!reuse_previous_algo)
      {
        // Obtain a convolution algorithm appropriate for the input and output
        // shapes. Either by choosing one according to heuristics or by making
        // CuDNN time every implementation and choose the best one.
        if (CHOOSE_ALGO_TIME)
        {
          // Time the different implementations to choose the best one
          int requestedCount = 1;
          int count;
          cudnnConvolutionBwdFilterAlgoPerf_t choosen_algo_perf;
          err = cudnnFindConvolutionBackwardFilterAlgorithm(_handle,
                                                            APPLY_SPECIFIC(input),
                                                            APPLY_SPECIFIC(output),
                                                            desc,
                                                            APPLY_SPECIFIC(kerns),
                                                            requestedCount,
                                                            &count,
                                                            &choosen_algo_perf);
          if (err != CUDNN_STATUS_SUCCESS) {
            PyErr_Format(PyExc_RuntimeError,
                         "GpuDnnConvGradW: error selecting convolution algo: "
                         "%s", cudnnGetErrorString(err));
            return 1;
          }

          chosen_algo = choosen_algo_perf.algo;
        }
        else
        {
          // Choose the convolution implementation using heuristics based on the
          // shapes of the inputs and the amount of memory available.

          // Get the amount of available memory
          size_t free = 0, total = 0;
          cudaError_t err2 = cudaMemGetInfo(&free, &total);
          if (err2 != cudaSuccess){
            cudaGetLastError();
            fprintf(stderr,
                    "Error when trying to find the memory information"
                    " on the GPU: %s\n", cudaGetErrorString(err2));
            return 1;
          }

          // Use heuristics to choose the implementation
          err = cudnnGetConvolutionBackwardFilterAlgorithm(_handle,
                                                           APPLY_SPECIFIC(input),
                                                           APPLY_SPECIFIC(output),
                                                           desc,
                                                           APPLY_SPECIFIC(kerns),
                                                           CUDNN_CONVOLUTION_BWD_FILTER_SPECIFY_WORKSPACE_LIMIT,
                                                           free,
                                                           &chosen_algo);

          if (err != CUDNN_STATUS_SUCCESS) {
            PyErr_Format(PyExc_RuntimeError,
                         "GpuDnnConvGradW: error selecting convolution algo: %s",
                         cudnnGetErrorString(err));
            return 1;
          }
        }

        // Store the shapes of the inputs and kernels as well as the chosen
        // algorithm for future use.
        APPLY_SPECIFIC(previous_bwd_f_algo) = chosen_algo;
        APPLY_SPECIFIC(previous_algo_set) = true;
        for (int i = 0; i < nb_dim; i++)
        {
            APPLY_SPECIFIC(previous_input_shape)[i] =
                                            CudaNdarray_HOST_DIMS(input)[i];
            APPLY_SPECIFIC(previous_output_shape)[i] =
                                            CudaNdarray_HOST_DIMS(output)[i];
        }

      }
      else
      {
        // Reuse the previously chosen convlution implementation
        chosen_algo = APPLY_SPECIFIC(previous_bwd_f_algo);
      }
    }
    else
    {
        chosen_algo = CONV_ALGO;
    }

    // The FFT implementation (only in v3 and onward) does not support strides,
    // 1x1 filters or inputs with a spatial dimension larger than 1024.
    // If the chosen implementation is FFT, validate that it can be used
    // on the current data and default on a safe implementation if it
    // can't.
    if (chosen_algo == CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT && nb_dim == 4)
    {

      // Extract the properties of the convolution descriptor
      int pad_h, pad_w, stride_v, stride_h, upscale_x, upscale_y;
      cudnnConvolutionMode_t mode;
      err = cudnnGetConvolution2dDescriptor(desc, &pad_h, &pad_w,
                                            &stride_v, &stride_h,
                                            &upscale_x, &upscale_y,
                                            &mode);

      if (err != CUDNN_STATUS_SUCCESS) {
        PyErr_Format(PyExc_RuntimeError,
                     "GpuDnnConvGradW: error getting convolution properties: %s",
                     cudnnGetErrorString(err));
        return 1;
      }

      // Extract the spatial size of the filters
      int filter_h = CudaNdarray_HOST_DIMS(*kerns)[2];
      int filter_w = CudaNdarray_HOST_DIMS(*kerns)[3];

      // Extract the spatial size of the input
      int input_h = CudaNdarray_HOST_DIMS(input)[2];
      int input_w = CudaNdarray_HOST_DIMS(input)[3];

      // Ensure that the selected implementation supports the requested
      // convolution. Fall back to a safe implementation otherwise.
      if (stride_v != 1 || stride_h != 1 || input_h > 1024 ||
          input_w > 1024 || (filter_h == 1 && filter_w == 1))
      {
        chosen_algo = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0;
      }
    }

    // Infer required workspace size from the chosen implementation
    err = cudnnGetConvolutionBackwardFilterWorkspaceSize(_handle,
                                                         APPLY_SPECIFIC(input),
                                                         APPLY_SPECIFIC(output),
                                                         desc,
                                                         APPLY_SPECIFIC(kerns),
                                                         chosen_algo,
                                                         &worksize);
    if (err != CUDNN_STATUS_SUCCESS) {
      PyErr_Format(PyExc_RuntimeError,
                   "GpuDnnConvGradW: error getting worksize: %s",
                   cudnnGetErrorString(err));
      return 1;
    }

    // Allocate workspace for the convolution
    workspace = get_work_mem(worksize);
    if (workspace == NULL && worksize != 0)
      return 1;

    // Perform the convolution
    err = cudnnConvolutionBackwardFilter_v3(
      _handle,
      (void *)&alpha,
      APPLY_SPECIFIC(input), CudaNdarray_DEV_DATA(input),
      APPLY_SPECIFIC(output), CudaNdarray_DEV_DATA(output),
      desc,
      chosen_algo,
      workspace, worksize,
      (void *)&beta,
      APPLY_SPECIFIC(kerns), CudaNdarray_DEV_DATA(*kerns));

  }
#else
  err = cudnnConvolutionBackwardFilter(
    _handle,
    (void *)&alpha,
    APPLY_SPECIFIC(input), CudaNdarray_DEV_DATA(input),
    APPLY_SPECIFIC(output), CudaNdarray_DEV_DATA(output),
    desc,
    (void *)&beta,
    APPLY_SPECIFIC(kerns), CudaNdarray_DEV_DATA(*kerns));
#endif

  if (err != CUDNN_STATUS_SUCCESS) {
    PyErr_Format(PyExc_RuntimeError, "GpuDnnConvGradW: error doing operation: %s",
                 cudnnGetErrorString(err));
    return 1;
  }
  return 0;
}


text:
<!DOCTYPE html>

    <title>Example 09.10 - Working with morph targets</title>


text:
import {vec3, mat4} from 'gl-matrix';

function touch2Mouse(e)
{
	var theTouch = e.changedTouches[0];
	var mouseEv;

	switch(e.type)
	{
		case "touchstart": mouseEv="mousedown"; break;
		case "touchend":   mouseEv="mouseup"; break;
		case "touchmove":  mouseEv="mousemove"; break;
		default: return;
	}

	var mouseEvent = document.createEvent("MouseEvent");
	mouseEvent.initMouseEvent(mouseEv, true, true, window, 1, theTouch.screenX, theTouch.screenY, theTouch.clientX, theTouch.clientY, false, false, false, false, 0, null);
	theTouch.target.dispatchEvent(mouseEvent);

	e.preventDefault();
}

export const ActiveToolDecorator = (superclass) => class extends superclass {
	constructor() {
		super();
		this._activeTool = null;
	}
	get activetool() { return this._activeTool; }
	set activetool(tool) {
		this._activeTool = tool;
		tool.view = this;
	}
	_render2d() {
		super._render2d();
		if(this._activeTool && this._activeTool.Render)
			this._activeTool.Render(this.gr, this._camera);
	}
	_attachEventListeners() {
		super._attachEventListeners();
		this.__onKeyDown = this._onKeyDown.bind(this);
		this.__onKeyUp = this._onKeyUp.bind(this);
		this.__onMouseMove = this._onMouseMove.bind(this);
		this.__onMouseDown = this._onMouseDown.bind(this);
		this.__onMouseUp = this._onMouseUp.bind(this);
		this.__onMouseWheel = this._onMouseWheel.bind(this);
		this.__onMouseOut = this._onMouseOut.bind(this);

		document.addEventListener('keydown', this.__onKeyDown, false);
		document.addEventListener('keyup', this.__onKeyUp, false);
		this.canvas2d.addEventListener('mousemove', this.__onMouseMove, false);
		this.canvas2d.addEventListener('mousedown', this.__onMouseDown, false);
		this.canvas2d.addEventListener('mouseup', this.__onMouseUp, false);
		this.canvas2d.addEventListener('wheel', this.__onMouseWheel, false);
		this.canvas2d.addEventListener('mouseout', this.__onMouseOut, false);
		this.canvas2d.addEventListener("touchstart", touch2Mouse, true);
		this.canvas2d.addEventListener("touchmove", touch2Mouse, true);
		this.canvas2d.addEventListener("touchend", touch2Mouse, true);
	}
	_detachEventListeners() {
		document.removeEventListener('keydown', this.__onKeyDown, false);
		document.removeEventListener('keyup', this.__onKeyUp, false);
		this.canvas2d.removeEventListener('mousemove', this.__onMouseMove, false);
		this.canvas2d.removeEventListener('mousedown', this.__onMouseDown, false);
		this.canvas2d.removeEventListener('mouseup', this.__onMouseUp, false);
		this.canvas2d.removeEventListener('wheel', this.__onMouseWheel, false);
		this.canvas2d.removeEventListener('mouseout', this.__onMouseOut, false);
		this.canvas2d.removeEventListener("touchstart", touch2Mouse, true);
		this.canvas2d.removeEventListener("touchmove", touch2Mouse, true);
		this.canvas2d.removeEventListener("touchend", touch2Mouse, true);
		super._detachEventListeners();
	}
	_onKeyDown(e) {
		if(this._activeTool && this._activeTool.kdown)
			this._activeTool.kdown(e);
	}
	_onKeyUp(e) {
		if(this._activeTool && this._activeTool.kup)
			this._activeTool.kup(e);
	}
	_onMouseMove(e) {
		if(this._activeTool && this._activeTool.mmove)
			this._activeTool.mmove(this._convertMouseEvent(e), this._camera);
	}
	_onMouseDown(e) {
		if(this._activeTool && this._activeTool.mdown)
			this._activeTool.mdown(this._convertMouseEvent(e), this._camera);
	}
	_onMouseUp(e) {
		if(this._activeTool && this._activeTool.mup)
			this._activeTool.mup(this._convertMouseEvent(e), this._camera);
	}
	_onMouseWheel(e) {
		if(this._activeTool && this._activeTool.mwheel)
			this._activeTool.mwheel(e);
	}
	_onMouseOut(e) {
		if(this._activeTool && this._activeTool.mout)
			this._activeTool.mout(e);
	}
	_convertMouseEvent(e) {
		var rect = this.canvas2d.getBoundingClientRect();
		var x = e.clientX - rect.left;
		var y = e.clientY - rect.top;
		var normedX = x / this.Width;
		var normedY = y / this.Height;
		var clipX = 2 * normedX - 1;
		var clipY = 1 - 2 * normedY;
		return {
			button: e.button,
			x: x,
			y: y,
			normedX: normedX,
			normedY: normedY,
			clipX: clipX,
			clipY: clipY
		}
	}
};


text:
class AliAnalysisDataContainer;

AliAnalysisTaskMcKnoUe* AddTaskMcKnoUe(const Char_t* taskname="McKnoUe", Bool_t  useMC  = kTRUE)
{
    // get the manager via the static access member. since it's static, you don't need
    // an instance of the class to call the function

    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        return 0x0;
    }
    // get the input event handler this handler is part of the managing system and feeds events to your task
    if (!mgr->GetInputEventHandler()) {
        return 0x0;
    }

    // now you create an instance of your task
    AliAnalysisTaskMcKnoUe* taskUE = new AliAnalysisTaskMcKnoUe("taskKno");
    if(!taskUE) return 0x0;
    taskUE->SetUseMC(useMC);
    // add your task to the manager
    mgr->AddTask(taskUE);

    mgr->ConnectInput(taskUE,0,mgr->GetCommonInputContainer());
    // same for the output
    mgr->ConnectOutput(taskUE,1,mgr->CreateContainer(Form("cList%s",taskname), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s", AliAnalysisManager::GetCommonFileName(),taskname)));

    //Printf("Set OutputFileName : \n %s\n", name.Data());

    // by default, a file is open for writing. here,  get the desired filename
    //    if (mgr->GetMCtruthEventHandler()) name += ":MC";

    // your task needs input: here you connect the manager to your task
    //mgr->ConnectInput(taskUE,0,mgr->GetCommonInputContainer());
    // same for the output
    //mgr->ConnectOutput(taskUE,1,mgr->CreateContainer("UE", TList::Class(), AliAnalysisManager::kOutputContainer, name+".root"));
    // this macro returns a pointer to the task, this will be convenient when you run the analysis in an analysis train on grids
    return taskUE;
}


text:
import os
import os.path
import signal
import sys
import daemon
try:
    import daemon.pidlockfile as pidlockfile
except:
    import daemon.pidfile as pidlockfile
import threading
import time
import socket

class MissingKeyException(Exception): pass
class InvalidKeyException(Exception): pass
class InvalidCommandException(Exception): pass

class HousekeeperKeyring:
    def __init__(self):
        self.keys_lock = threading.Lock()
        self.reset()

    def reset(self):
        self.keys_lock.acquire()
        self.keys = {}
        self.keys_lock.release()

    def check_expiration(self, service=None):
        def check(key):
            if key['timeout'] and key['expiration'] < time.time():
                del self.keys[service]

        self.keys_lock.acquire()
        if service:
            if service in self.keys:
                check(self.keys[service])
        else:
            services = self.keys.keys()
            for service in services:
                check(self.keys[service])
        self.keys_lock.release()

    def set_key(self, service, key, timeout=600):
        if not service or not key or timeout < 0:
            raise InvalidKeyException()

        self.keys_lock.acquire()
        self.keys[service] = {
            'key': key,
            'expiration': time.time() + timeout,
            'timeout': timeout,
        }
        self.keys_lock.release()

    def get_key(self, service):
        self.check_expiration(service)
        self.keys_lock.acquire()
        try:
            if self.keys.has_key(service):
                key = self.keys[service]
                key['expiration'] = time.time() + key['timeout']
                result = key['key']
            else:
                raise MissingKeyException("No key for '%s' service" % service)
        finally:
            self.keys_lock.release()
        return result

class HousekeeperDaemon(daemon.DaemonContext):
    def __init__(self, directory=os.path.expanduser('~/.housekeeper'), write_envfile=False, replace=True):
        self.directory = directory
        self.pidfile = os.path.join(directory, 'pid')
        self.envfile = os.path.join(directory, 'env')
        self.socketfile = os.path.join(directory, 'socket')
        self.keyring = HousekeeperKeyring()
        self.write_envfile = write_envfile
        self.replace = replace

        self.__startup()

        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

        self.env_content = "HOUSEKEEPER_SOCKET='%s'; export HOUSEKEEPER_SOCKET;" % self.socketfile
        print self.env_content
        sys.stdout.flush()

        super(HousekeeperDaemon, self).__init__(
            working_directory = self.directory,
            pidfile = pidlockfile.PIDLockFile(self.pidfile),
            detach_process = True,
        )

        self.signal_map = {
            signal.SIGTERM: 'terminate',
            signal.SIGHUP: None,
            signal.SIGUSR1: lambda *args: self.reset_keyring(),
        }

    def __startup(self):
        # Check if daemon already running
        if os.path.isfile(self.pidfile):
            try:
                pid = int(open(self.pidfile).read())
                # Check For the existence of a unix pid.
                os.kill(pid, 0)
            except (OSError, ValueError):
                sys.stderr.write("Removing stale locking file: %s\n" % self.pidfile)
                os.unlink(self.pidfile)
            else:
                if self.replace:
                    sys.stderr.write("Replacing daemon PID: %d\n" % pid)
                    os.kill(pid, signal.SIGTERM)
                else:
                    sys.stderr.write("Daemon already running PID: %d\n" % pid)
                    exit(1)

    def __check_expiration(self):
        class Checker(threading.Thread):
            def __init__(self, keyring):
                super(Checker, self).__init__()
                self.keyring = keyring
                self.event = threading.Event()
                # TODO: Kill the thread with stop() instead of with self.daemon
                self.daemon = True

            def run(self):
                while not self.event.isSet():
                    self.keyring.check_expiration()
                    self.event.wait(60)

            def stop(self):
                self.event.set()

        return Checker(self.keyring)

    def reset_keyring(self):
        self.keyring.reset()

    def handle_command(self, command):
        tokens = command.split(' ')
        if tokens[0] == 'GET' and len(tokens) == 2:
            return self.keyring.get_key(tokens[1])
        elif tokens[0] == 'SET' and len(tokens) >= 3:
            args = [tokens[1], tokens[2]]
            if len(tokens) > 3:
                args.append(int(tokens[3]))
            self.keyring.set_key(*args)
            return ''
        else:
            raise InvalidCommandException()

    def handle_connection(self, conn):
        socket_file = conn.makefile('rw')
        try:
            command = socket_file.readline()
            response = self.handle_command(command.strip())
            if response:
                socket_file.write(response + '\r\n')
            socket_file.write('OK\r\n')
            socket_file.flush()
            socket_file.close()
        except MissingKeyException:
            socket_file.write('MissingKeyException\r\nERROR\r\n')
        except InvalidKeyException:
            socket_file.write('InvalidKeyException\r\nERROR\r\n')
        except InvalidCommandException:
            socket_file.write('InvalidCommandException\r\nERROR\r\n')
        except ValueError:
            socket_file.write('InvalidCommandException\r\nERROR\r\n')
        finally:
            conn.close()

    def close(self):
        if os.path.exists(self.socketfile):
            os.unlink(self.socketfile)
        if os.path.exists(self.envfile):
            os.unlink(self.envfile)
        super(HousekeeperDaemon, self).close()

    def main(self):
        self.open()
        umask = os.umask(0022)

        self.checker = self.__check_expiration()
        self.checker.start()

        if os.path.lexists(self.socketfile):
            os.unlink(self.socketfile)

        if self.write_envfile:
            env = open(self.envfile, 'w')
            env.write(self.env_content)
            env.close()

        self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        os.umask(0077)
        self.socket.bind(self.socketfile)
        os.umask(umask)
        self.socket.listen(1)

        while True:
            try:
                conn, addr = self.socket.accept()
                self.handle_connection(conn)
            except socket.error:
                pass

def main():
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option("-d", "--directory",
        dest="directory",
        help="Uses DIRECTORY as working directory",
        metavar="DIRECTORY",
        default=os.path.expanduser('~/.housekeeper'),
    )
    parser.add_option("-e", "--write-env-file",
        dest="write_envfile",
        help="Write environment file in working directory",
        action="store_true",
        default=False,
    )
    parser.add_option("-r", "--replace",
        dest="replace",
        help="Replace running daemon if any",
        action="store_true",
        default=False,
    )

    (options, args) = parser.parse_args()

    daemon = HousekeeperDaemon(
        directory=options.directory,
        write_envfile=options.write_envfile,
        replace=options.replace,
    )
    daemon.main()

if __name__ == "__main__":
    main()


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <title>Typography : Rural Payments</title>

    <link href="/assets/govuk/stylesheets/govuk-template.css" media="screen" rel="stylesheet">

    <link href="/assets/govuk/stylesheets/govuk-template-print.css" media="print" rel="stylesheet">

    <link href="/assets/govuk/stylesheets/fonts.css" media="all" rel="stylesheet">

    <link rel="shortcut icon" href="/assets/govuk/images/favicon.ico" type="image/x-icon">

    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/assets/govuk/images/apple-touch-icon-144x144.png">

    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/assets/govuk/images/apple-touch-icon-114x114.png">

    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/assets/govuk/images/apple-touch-icon-72x72.png">

    <link rel="apple-touch-icon-precomposed" href="/assets/govuk/images/apple-touch-icon-57x57.png">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta property="og:image" content="/assets/govuk/images/opengraph-image.png">

    <link href="/assets/stylesheets/main.css" media="all" rel="stylesheet">

      Skip to main content

GOV.UK uses cookies to make the site simpler. Find out more about cookies

             GOV.UK

	    Menu

	      Rural Payments

Your businesses

Sign out

Help

				Beta
				This is a new service – your feedback will help us to improve it.

    Back to the index

Typography

All typography used in the site should be in alignment with the beta banner. If any design mockups illustrate this, then
					please question why and do not simply copy it!

Large heading with sub heading

This is an intro paragraph at 24px. Maecenas faucibus mollis interdum. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
			Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Curabitur blandit tempus porttitor. Vestibulum id ligula porta felis euismod semper.

A 36px heading

This is a body copy paragraph at 19px. Donec id elit non mi porta gravida at eget metus. Cum sociis natoque penatibus et
			magnis dis parturient montes, nasceturridiculus mus. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec
			sed odio dui.

A 24px heading

Etiam porta sem malesuada magna mollis euismod. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Sed posuere consectetur est at lobortis. Maecenas
			faucibus mollis interdum. Vestibulum id ligula porta felis euismod semper. Donec id elit non mi porta gravida at eget metus.

A 19px heading

Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Donec sed odio dui. Donec id elit
			non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit. Nullam quis risus eget urna mollis ornare vel eu leo.

Inset text

It can take up to 8 weeks to register a lasting power of attorney if there are no mistakes in the application.

Hidden text (progressive disclosure)

				Help with nationality

If you're not sure about your nationality, try to find out from an official document like a passport or national ID card.

We need to know your nationality so we can work out which elections you're entitled to vote in. If you can't provide your nationality, you'll have to send copies of identity documents through the post.

Unordered list

Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Vestibulum id ligula porta felis euismod semper.

Integer posuere erat a ante venenatis dapibus posuere velit aliquet.

Ordered list

Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Vestibulum id ligula porta felis visit gov.uk (link opens in a new browser window).

Integer posuere erat a ante venenatis dapibus posuere velit aliquet.

External links (Screen reader optimised)

Visit gov.uk (link opens in a new browser window)

Address using ( microdata )

Beech Farm

Pooley Bridge

Penrith

Cumbria

CH3 6NZ

United Kingdom

0147 9643 7770

joe.bloggs@beechfarm.co.uk

You cannot use Government Gateway to access this service.

You need to register with GOV.UK to use this service. People you want to act on behalf of a business will also need to register.

To do this, or to sign in if you are already registered, click the button below.

Register or sign in to GOV.UK services

Help

Cookies

Contact

Cymraeg

Built by Defra

Open Government Licence

All content is available under the Open Government Licence v3.0, except where otherwise stated

          © Crown copyright


text:
<?php

// Ovaj file mora biti uključen da bi mogli koristiti autoloading. Prije korištenja, spojiti se na PuTTY i unutar example
// direktorija pokrenuti naredbu "composer install"
require_once __DIR__ . '/../app/bootstrap.php';

use Adriatic\PHPAkademija\OOPIntro\Car;	// Car klasa se nalazi u src/OOPIntro/Car.php

$myCar = new Car('silver');
echo $myCar->getCurrentSpeed();


text:
module MediaStorage
  class AwsAdapter < AbstractAdapter
    attr_reader :prefix, :s3, :get_expiration, :put_expiration
    DEFAULT_EXPIRES_IN = 180

    def initialize(opts={})
      @prefix = opts[:prefix] || Rails.env
      @bucket_name = opts[:bucket]
      @get_expiration = opts.dig(:expiration, :get) || DEFAULT_EXPIRES_IN
      @put_expiration = opts.dig(:expiration, :put) || DEFAULT_EXPIRES_IN
      @s3 = Aws::S3::Resource.new(client: s3_client(opts))
    end

    def bucket
      @bucket ||= s3.bucket(@bucket_name)
    end

    def stored_path(content_type, medium_type, *path_prefix)
      extension = get_extension(content_type)
      path = prefix.to_s
      path += "/" unless path[-1] == '/'
      path += "#{medium_type}/"
      path += "#{path_prefix.join('/')}/" unless path_prefix.empty?
      path += "#{SecureRandom.uuid}.#{extension}"
      path
    end

    def get_path(path, opts={})
      expires = expires_in(opts[:get_expires] || get_expiration)
      if opts[:private]
        object(path).presigned_url(:get, expires_in: expires).to_s
      else
        "https://#{path}"
      end
    end

    def put_path(path, opts={})
      content_type = opts[:content_type]
      expires = expires_in(opts[:put_expires] || put_expiration)
      object(path).presigned_url(
        :put,
        content_type: content_type,
        expires_in: expires,
        acl: opts[:private] ? 'private' : 'public-read'
      ).to_s
    end

    def put_file(path, file_path, opts={})
      upload_options = {
        content_type: opts[:content_type],
        acl: opts[:private] ? 'private' : 'public-read'
      }
      upload_options[:content_encoding] = 'gzip' if opts[:compressed]
      if opts[:content_disposition]
        upload_options[:content_disposition] = opts[:content_disposition]
      end
      object(path).upload_file(file_path, upload_options)
    end

    def delete_file(path)
      object(path).delete
    end

    def encrypted_bucket?
      s3.client.get_bucket_encryption({ bucket: bucket.name })
      true
    rescue Aws::S3::Errors::ServerSideEncryptionConfigurationNotFoundError
      false
    end

    private

    def object(path)
      check_path(path)
      bucket.object(path)
    end

    def expires_in(mins)
      (mins * 60).to_i
    end

    def s3_client(opts)
      client_opts = opts.slice(*s3_client_opts)
      client_opts[:region] ||= ENV.fetch('AWS_REGION', 'us-east-1')
      Aws::S3::Client.new(client_opts)
    end

    def s3_client_opts
      %i(
        access_key_id
        secret_access_key
        region
        stub_responses
      )
    end
  end
end