text:
/*jslint browser: true*/
/*global Tangram, gui */

map = (function () {
    'use strict';

    function appendProtocol(url) {
        return window.location.protocol + url;
    }

    // default source, can be overriden by URL
    var default_tile_source = 'ghosts',
        rS;

    var locations = {
        'London': [51.508, -0.105, 15],
        'New York': [40.70531887544228, -74.00976419448853, 16],
        'Seattle': [47.609722, -122.333056, 15]
    };
    var osm_debug = false;

    /***** GUI/debug controls *****/

    /*** URL parsing ***/

    // URL hash pattern is one of:
    // #[source]
    // #[lat],[lng],[zoom]
    // #[source],[lat],[lng],[zoom]
    // #[source],[location name]
    var url_hash = window.location.hash.slice(1, window.location.hash.length).split(',');

    // Get location from URL
    var map_start_location = locations['New York'];

    if (url_hash.length == 3) {
        map_start_location = url_hash.slice(0, 3);
    }
    if (url_hash.length > 3) {
        map_start_location = url_hash.slice(1, 4);
    }
    else if (url_hash.length == 2) {
        map_start_location = locations[url_hash[1]];
    }

    if (url_hash.length > 4) {
        var url_ui = url_hash.slice(4);

        // Mode on URL?
        var url_mode;
        if (url_ui) {
            var re = new RegExp(/mode=(\w+)/);
            url_ui.forEach(function(u) {
                var match = u.match(re);
                url_mode = (match && match.length > 1 && match[1]);
            });
        }
    }

    // Put current state on URL
    function updateURL() {
        var map_latlng = map.getCenter(),
            url_options = [map_latlng.lat, map_latlng.lng, map.getZoom()];

        if (rS) {
            url_options.push('rstats');
        }

        if (gl_mode_options && gl_mode_options.effect != '') {
            url_options.push('mode=' + gl_mode_options.effect);
        }

        window.location.hash = url_options.join(',');
    }

    /*** Map ***/

    var map = L.map('map', {
        maxZoom: 20,
        minZoom: 12,
        inertia: false,
        keyboard: true
    });

    var layer = Tangram.leafletLayer({
        scene: 'scene.yaml',
        attribution: 'Tangram | © OSM contributors | Mapzen'
    });

    window.layer = layer;

    var scene = layer.scene;
    window.scene = scene;

    // Update URL hash on move
    map.attributionControl.setPrefix('');
    map.setView(map_start_location.slice(0, 2), map_start_location[2]);
    map.on('moveend', updateURL);

    // Resize map to window
    function resizeMap() {
        document.getElementById('map').style.width = window.innerWidth + 'px';
        document.getElementById('map').style.height = window.innerHeight + 'px';
        map.invalidateSize(false);
    }

    window.addEventListener('resize', resizeMap);
    resizeMap();

    // Render/GL stats: http://spite.github.io/rstats/
    // Activate with 'rstats' anywhere in options list in URL
    if (url_ui && url_ui.indexOf('rstats') >= 0) {
        var glS = new glStats();
        glS.fractions = []; // turn this off till we need it

        rS = new rStats({
            values: {
                frame: { caption: 'Total frame time (ms)', over: 5 },
                raf: { caption: 'Time since last rAF (ms)' },
                fps: { caption: 'Framerate (FPS)', below: 30 },
                rendertiles: { caption: 'Rendered tiles' },
                features: { caption: '# of geo features' },
                glbuffers: { caption: 'GL buffers (MB)' }
            },
            CSSPath : 'demos/lib/',
            plugins: [glS]
        });

        // Move it to the bottom-left so it doesn't obscure zoom controls
        var rSDOM = document.querySelector('.rs-base');
        rSDOM.style.bottom = '0px';
        rSDOM.style.top = 'inherit';
    }

    // For easier debugging access

    // GUI options for rendering modes/effects
    var gl_mode_options = {
        effect: url_mode || '',
        options: {
            'None': ''
        },
        setup: function (mode) {
            // Restore initial state
            var layer_styles = scene.styles.layers;
            for (var l in layer_styles) {
                if (this.initial.layers[l] != null) {
                    layer_styles[l].mode = this.initial.layers[l].mode;
                    layer_styles[l].visible = this.initial.layers[l].visible;
                }
            };

            // Mode-specific settings
            if (mode != '') {
                // Save settings to restore later
                for (l in layer_styles) {
                    if (this.initial.layers[l] == null) {
                        this.initial.layers[l] = {
                            // mode: (layer_styles[l].mode ? { name: layer_styles[l].mode.name } : null),
                            mode: layer_styles[l].mode,
                            visible: layer_styles[l].visible
                        };
                    }
                }
                this.initial.camera = this.initial.camera || scene.styles.camera.type;
            }

            // Recompile/rebuild
            scene.createCamera();
            scene.createLighting();
            scene.refreshModes();
            scene.rebuild();
            updateURL();
        }
    };

    // Feature selection
    function initFeatureSelection () {
        // Selection info shown on hover
        var selection_info = document.createElement('div');
        selection_info.setAttribute('class', 'label');
        selection_info.style.display = 'block';

        // Show selected feature on hover
        // Show selected feature on hover
        map.getContainer().addEventListener('mousemove', function (event) {
        // scene.container.addEventListener('mousemove', function (event) {
            var pixel = { x: event.clientX, y: event.clientY };
            scene.getFeatureAt(pixel).then(function(selection) {
                if (!selection) {
                    return;
                }
                var feature = selection.feature;
                if (feature != null) {

                    var label = '';
                    if (feature.properties.name != null) {
                        label = feature.properties.name;
                    }

                    if (label != '') {
                        selection_info.style.left = (pixel.x + 5) + 'px';
                        selection_info.style.top = (pixel.y + 15) + 'px';
                        selection_info.style.zIndex = 1000;
                        selection_info.innerHTML = '' + label + '';
                        scene.container.appendChild(selection_info);
                    }
                    else if (selection_info.parentNode != null) {
                        selection_info.parentNode.removeChild(selection_info);
                    }
                }
                else if (selection_info.parentNode != null) {
                    selection_info.parentNode.removeChild(selection_info);
                }
            });

            // Don't show labels while panning
            if (scene.panning == true) {
                if (selection_info.parentNode != null) {
                    selection_info.parentNode.removeChild(selection_info);
                }
            }
        });
    }

    /***** Render loop *****/
    window.addEventListener('load', function () {
        // Scene initialized
        layer.on('init', function() {
            initFeatureSelection();
        });
        layer.addTo(map);
    });

    return map;

}());


text:
var auth = require('../../config/authorization');

/**
 * Route para el index, no se implementa un controller
 * @param router
 */
module.exports = function (router) {

    /*
     * Index de la aplicación, si esta autenticado carga el index de angular
     */
    router.route('/').get(function (req, res) {
        var view = (req.isAuthenticated()) ? 'indexng' : 'index';
        res.render(view);
    });

    router.route('/database')
        .get(auth.requiresLogin, auth.requiresAdmin,  function (req, res) {
            res.send('database');
        });
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.maven.repository.internal;

import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifactType;
import org.eclipse.aether.collection.DependencyGraphTransformer;
import org.eclipse.aether.collection.DependencyManager;
import org.eclipse.aether.collection.DependencySelector;
import org.eclipse.aether.collection.DependencyTraverser;
import org.eclipse.aether.util.artifact.DefaultArtifactTypeRegistry;
import org.eclipse.aether.util.graph.manager.ClassicDependencyManager;
import org.eclipse.aether.util.graph.selector.AndDependencySelector;
import org.eclipse.aether.util.graph.selector.ExclusionDependencySelector;
import org.eclipse.aether.util.graph.selector.OptionalDependencySelector;
import org.eclipse.aether.util.graph.selector.ScopeDependencySelector;
import org.eclipse.aether.util.graph.transformer.ChainedDependencyGraphTransformer;
import org.eclipse.aether.util.graph.transformer.ConflictResolver;
import org.eclipse.aether.util.graph.transformer.JavaDependencyContextRefiner;
import org.eclipse.aether.util.graph.transformer.JavaScopeDeriver;
import org.eclipse.aether.util.graph.transformer.JavaScopeSelector;
import org.eclipse.aether.util.graph.transformer.NearestVersionSelector;
import org.eclipse.aether.util.graph.transformer.SimpleOptionalitySelector;
import org.eclipse.aether.util.graph.traverser.FatArtifactTraverser;
import org.eclipse.aether.util.repository.SimpleArtifactDescriptorPolicy;

/**
 * A utility class to assist in setting up a Maven-like repository system. Note: This component is meant to
 * assist those clients that employ the repository system outside of an IoC container, Maven plugins should instead
 * always use regular dependency injection to acquire the repository system.
 *
 * @author Benjamin Bentmann
 */
public final class MavenRepositorySystemUtils {

    private MavenRepositorySystemUtils() {
        // hide constructor
    }

    /**
     * Creates a new Maven-like repository system session by initializing the session with values typical for
     * Maven-based resolution. In more detail, this method configures settings relevant for the processing of dependency
     * graphs, most other settings remain at their generic default value. Use the various setters to further configure
     * the session with authentication, mirror, proxy and other information required for your environment.
     *
     * @return The new repository system session, never {@code null}.
     */
    public static DefaultRepositorySystemSession newSession() {
        DefaultRepositorySystemSession session = new DefaultRepositorySystemSession();

        DependencyTraverser depTraverser = new FatArtifactTraverser();
        session.setDependencyTraverser(depTraverser);

        DependencyManager depManager = new ClassicDependencyManager();
        session.setDependencyManager(depManager);

        DependencySelector depFilter = new AndDependencySelector(
                new ScopeDependencySelector("test", "provided"),
                new OptionalDependencySelector(),
                new ExclusionDependencySelector());
        session.setDependencySelector(depFilter);

        DependencyGraphTransformer transformer = new ConflictResolver(
                new NearestVersionSelector(), new JavaScopeSelector(),
                new SimpleOptionalitySelector(), new JavaScopeDeriver());
        transformer = new ChainedDependencyGraphTransformer(transformer, new JavaDependencyContextRefiner());
        session.setDependencyGraphTransformer(transformer);

        DefaultArtifactTypeRegistry stereotypes = new DefaultArtifactTypeRegistry();
        stereotypes.add(new DefaultArtifactType("pom"));
        stereotypes.add(new DefaultArtifactType("maven-plugin", "jar", "", "java"));
        stereotypes.add(new DefaultArtifactType("jar", "jar", "", "java"));
        stereotypes.add(new DefaultArtifactType("ejb", "jar", "", "java"));
        stereotypes.add(new DefaultArtifactType("ejb-client", "jar", "client", "java"));
        stereotypes.add(new DefaultArtifactType("test-jar", "jar", "tests", "java"));
        stereotypes.add(new DefaultArtifactType("javadoc", "jar", "javadoc", "java"));
        stereotypes.add(new DefaultArtifactType("java-source", "jar", "sources", "java", false, false));
        stereotypes.add(new DefaultArtifactType("war", "war", "", "java", false, true));
        stereotypes.add(new DefaultArtifactType("ear", "ear", "", "java", false, true));
        stereotypes.add(new DefaultArtifactType("rar", "rar", "", "java", false, true));
        stereotypes.add(new DefaultArtifactType("par", "par", "", "java", false, true));
        session.setArtifactTypeRegistry(stereotypes);

        session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(true, true));

        return session;
    }
}


text:
<?php

include_once dirname(__FILE__) . '/' . 'user_authentication/user_authentication.php';
include_once dirname(__FILE__) . '/' . 'grant_manager/user_grant_manager.php';
include_once dirname(__FILE__) . '/' . 'record_level_permissions_retrieve_strategy.php';
include_once dirname(__FILE__) . '/' . 'null_user_manager.php';

class SecureApplication
{
    /** @var AbstractUserAuthentication */
    private $userAuthentication;
    /** @var UserGrantManager */
    private $userGrantManager;
    /** @var HardCodedDataSourceRecordPermissionRetrieveStrategy */
    private $dataSourceRecordPermissionRetrieveStrategy;

    public function __construct()
    {
        $this->userAuthentication = new NullUserAuthentication();
        $this->userGrantManager = new NullUserGrantManager();
        $this->dataSourceRecordPermissionRetrieveStrategy = new NullDataSourceRecordPermissionRetrieveStrategy();
    }

    /** @param AbstractUserAuthentication $userAuthentication */
    public function SetUserAuthentication($userAuthentication)
    {
        $this->userAuthentication = $userAuthentication;
    }

    /** @return AbstractUserAuthentication */
    public function GetUserAuthentication()
    {
        return $this->userAuthentication;
    }

    /**
     * @param UserGrantManager $userGrantManager
     */
    public function SetUserGrantManager(UserGrantManager $userGrantManager) {
        $this->userGrantManager = $userGrantManager;
    }

    /**
     * @return UserGrantManager
     */
    public function GetUserGrantManager()
    {
        return $this->userGrantManager;
    }

    public function SetDataSourceRecordPermissionRetrieveStrategy(
        HardCodedDataSourceRecordPermissionRetrieveStrategy $value = null)
    {
        $this->dataSourceRecordPermissionRetrieveStrategy = $value;
    }

    /**
     * @return HardCodedDataSourceRecordPermissionRetrieveStrategy|null
     */
    public function GetDataSourceRecordPermissionRetrieveStrategy()
    {
        return $this->dataSourceRecordPermissionRetrieveStrategy;
    }

    /** @return boolean */
    public function isAuthenticationEnabled() {
        return !($this->userAuthentication instanceof NullUserAuthentication);
    }

}


text:
package org.codehaus.mojo.natives.msvc;

import org.codehaus.mojo.natives.NativeBuildException;
import org.codehaus.mojo.natives.c.AbstractCCompiler;
import org.codehaus.mojo.natives.compiler.Compiler;
import org.codehaus.mojo.natives.compiler.CompilerConfiguration;
import org.codehaus.plexus.util.cli.Commandline;

import java.io.File;
import java.util.Map;
import java.util.Properties;
import org.codehaus.plexus.component.annotations.Component;

@Component(role = Compiler.class, hint = "msvc")
public class MSVCCompiler
    extends AbstractCCompiler
{
    private Map environmentVariables;

    protected void setEnvironmentVariables( Map envs )
    {
        this.environmentVariables = envs;
    }

    protected Map getEnvironmentVariables()
    {
        if ( this.environmentVariables == null )
        {
            return new Properties();
        }

        return this.environmentVariables;
    }

    protected String getOutputFileOption()
    {
        return "/Fo";
    }

    protected Commandline getCommandLine( File src, File dest, CompilerConfiguration config )
        throws NativeBuildException
    {
        if ( config.getExecutable() == null || config.getExecutable().trim().length() == 0 )
        {
            config.setExecutable( "cl.exe" );
        }

        Commandline cl = super.getCommandLine( src, dest, config );

        return cl;
    }

}


text:
package shardkv

//
// Sharded key/value server.
// Lots of replica groups, each running op-at-a-time paxos.
// Shardmaster decides which group serves each shard.
// Shardmaster may change shard assignment from time to time.
//
// You will have to modify these definitions.
//

const (
	OK            = "OK"
	ErrNoKey      = "ErrNoKey"
	ErrWrongGroup = "ErrWrongGroup"
)

type Err string

// Put or Append
type PutAppendArgs struct {
	// You'll have to add definitions here.
	Key   string
	Value string
	Op    string // "Put" or "Append"
	// You'll have to add definitions here.
	// Field names must start with capital letters,
	// otherwise RPC will break.
}

type PutAppendReply struct {
	WrongLeader bool
	Err         Err
}

type GetArgs struct {
	Key string
	// You'll have to add definitions here.
}

type GetReply struct {
	WrongLeader bool
	Err         Err
	Value       string
}


text:
module TimestampsSpecHelper
  def timestampify(time)
    time.getutc.iso8601(3) unless time.nil?
  end

  def datestampify(date)
    date.strftime("%Y-%m-%d") unless date.nil?
  end
end


text:
START_ATF_NAMESPACE
    struct  DispHTMLFrameElement : IDispatch
    {
    };
END_ATF_NAMESPACE


text:
package problems.medium;

import java.util.List;
import java.util.Stack;

/**
 * Created by sherxon on 2/1/17.
 */

public class MiniParser {
    public NestedInteger deserialize(String s) {

        Stack<NestedInteger> stack = new Stack<>();
        char[] a = s.toCharArray();
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < a.length; i++) {
            if (a[i] == '[') {

                NestedInteger inn = new NestedInteger();
                if (!stack.isEmpty()) stack.peek().getList().add(inn);
                stack.add(inn);

            } else if (a[i] == ']') {

                if (sb.length() > 0) {
                    Integer n = Integer.parseInt(sb.toString());
                    NestedInteger inn = new NestedInteger(n);
                    stack.peek().getList().add(inn);
                    sb.setLength(0);
                }
                if (stack.size() > 1)
                    stack.pop();
            } else if (a[i] == ',') {
                if (sb.length() > 0) {
                    Integer n = Integer.parseInt(sb.toString());
                    NestedInteger inn = new NestedInteger(n);
                    stack.peek().getList().add(inn);
                    sb.setLength(0);
                }

            } else {
                sb.append(a[i]);
            }
        }
        if (sb.length() > 0) {
            if (stack.isEmpty()) return new NestedInteger(Integer.parseInt(sb.toString()));
            else stack.peek().setInteger(Integer.parseInt(sb.toString()));
        }

        return stack.peek();
    }

// This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation

    class NestedInteger {
        // Constructor initializes an empty nested list.
        public NestedInteger() {
        }

        // Constructor initializes a single integer.
        public NestedInteger(int value) {
        }

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger() {
            return false;
        }

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger() {
            return null;
        }

        // Set this NestedInteger to hold a single integer.
        public void setInteger(int value) {
        }

        // Set this NestedInteger to hold a nested list and adds a nested integer to it.
        public void add(NestedInteger ni) {
        }

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return null if this NestedInteger holds a single integer
        public List<NestedInteger> getList() {
            return null;
        }
    }
}


text:
package com.agadar.archmagus.spell;

import java.util.Random;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;

/** The archetype of all Spells. */
public abstract class Spell
{
	/** A Random object used by some child classes of Spell. */
	protected final static Random random = new Random();
	/** The index of this spell in the spellList. */
	public final int effectId;
	/** Used in localisation and stats. */
    private String name;

    protected Spell(int par1)
    {
        this.effectId = par1;
        Spells.registerSpell(this, par1);
    }

	/** Returns the minimum level that the spell can be. */
    public short getMinLevel()
    {
        return 1;
    }

    /** Returns the maximum level that the spell can be. */
    public short getMaxLevel()
    {
        return 1;
    }

    /** Returns the amount of mana the spell costs to cast. */
    public int getManaCost()
    {
    	return 1;
    }

    /** Returns the cooldown of this spell in game ticks. (20 ticks = 1 second) */
    public short getCooldown()
    {
    	return 20;
    }

    /** Returns the name of the sound played when this spell is cast. */
    public String getSoundName()
    {
    	return "mob.ghast.fireball";
    }

    /** Returns the name of the particles spawned when a spell book
     * that contains this spell is being held by an entity. */
    public String getParticleName()
    {
    	return "happyVillager";
    }

	/** Returns the amount of particles spawned per gametick when a spell book
	 *  that contains this spell is being held by an entity. (20 ticks = 1 second) */
	public double getParticleAmount()
	{
		return 1;
	}

    /** Sets the spell name. */
    protected Spell setName(String par1Str)
    {
        this.name = par1Str;
        return this;
    }

    /** Returns the name of key in translation table of this spell. */
    private String getName()
    {
        return "spell." + this.name;
    }

    /** Returns the correct translated name of the spell and the level in roman numbers. */
    public String getTranslatedName(int par1)
    {
        String s = StatCollector.translateToLocal(this.getName());

        if (this.getMinLevel() != this.getMaxLevel())
        	return s + " " + StatCollector.translateToLocal("spell.level." + par1);

        return s;
    }

    /** Ensures that a given level lies between this spell's minimum and maximum levels. */
    protected int getNormalizedLevel(short par1Level)
    {
    	return Math.max(getMinLevel(), Math.min(par1Level, getMaxLevel()));
    }

    /** Casts this spell based on the given level. NOTE: it is ALWAYS assumed !par2World.isRemote. */
	public abstract void castSpell(short par1Level, World par2World, EntityPlayer par3EntityPlayer);
}


text:
!*****************************************************************************************
!>
!  Test of [[c_pointer_test_module]].

    program c_pointer_test

    use c_pointer_test_module
    use iso_c_binding

    implicit none

    type(c_ptr) :: cp
    integer :: i !! counter

    call initialize_list()

    cp = create_model(989)
    do i=1,10
        call access_model(cp)
    end do
    call destroy_model(cp)

    call destroy_list()

    end program c_pointer_test
!*****************************************************************************************


text:
import _ from 'lodash';
import Range from './range.vue';

describe('range input', () => {
  test('renders with no props', () => {
    const wrapper = shallowMount(Range, {
      propsData: {
        name: 'foo',
        data: null,
        schema: {},
        args: {}
      },
      mocks: {
        $store: {
          commit: _.noop
        }
      }
    });

    expect(wrapper.html()).toContain('<div class="editor-range');
  });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cronartium verbenae var. asclepiadeum Willd.

### Remarks
null


text:
#include <cprocessing/cprocessing.hpp>
using namespace cprocessing;

/**
 * Storing Input.
 *
 * Move the mouse across the screen to change the position
 * of the circles. The positions of the mouse are recorded
 * into an array and played back every frame. Between each
 * frame, the newest value are added to the end of each array
 * and the oldest value is deleted.
 */

int num = 60;
float * mx = new float[num];
float * my = new float[num];

void setup() {
  size(640, 360);
  noStroke();
  fill(255, 153);
}

void draw() {
  background(51);

  // Cycle through the array, using a different entry on each frame.
  // Using modulo (%) like this is faster than moving all the values over.
  int which = frameCount % num;
  mx[which] = mouseX;
  my[which] = mouseY;

  for (int i = 0; i < num; i++) {
    // which+1 is the smallest (the oldest in the array)
    int index = (which+1 + i) % num;
    ellipse(mx[index], my[index], i, i);
  }
}


text:
/**
 * ElasticSearch index for the {@link org.eclipse.rdf4j.sail.lucene.LuceneSail}.
 */
package org.eclipse.rdf4j.sail.elasticsearch;


text:
using OpenQA.Selenium.IE;
using Riganti.Selenium.Core.Factories;

namespace Riganti.Selenium.Core.Drivers.Implementation
{
    public static class InternetExplorerHelpers
    {

        public static InternetExplorerDriver CreateInternetExplorerDriver(LocalWebBrowserFactory factory)
        {
            var options = new InternetExplorerOptions
            {
                BrowserCommandLineArguments = "-private"
            };

            return new InternetExplorerDriver(options);
        }

    }
}


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

namespace custom_formatter
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            User user = new User("pam", "Paulius", "Maruška", new DateTime(1983, 4, 12), "Vilnius, Lithuania");

            Console.WriteLine("User: {0}", user);
            Console.WriteLine("User: {0:FirstName} {0:LastName} ({0:Age,X8}) from {0:Location}", user);
            Console.WriteLine("User: {0:FirstName} {0:LastName} ({0:Age}) from {0:Location}", user);
            Console.WriteLine("User: {0:FirstName} {0:LastName} ({0:Birthday,d}) from {0:Location}", user);
            Console.WriteLine("User: {0:FirstName} {0:LastName} ({0:Birthday,yyyy}) from {0:Location}", user);
            Console.WriteLine("User: {0:FirstName|' '|LastName|' ('|Birthday,yyyy|') from '|Location}", user);
        }
    }
}


text:
package com.benstone.Utils;

import com.badlogic.gdx.utils.StringBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by Ben on 1/29/2016.
 */
public class FileUtils {

    ///////////////////////////////////////////////////////////////////////////
    //						    Utility Methods								 //
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Reads a given file and stores its contents into a String
     * @param file
     * @return
     * @throws IOException
     */
    public static String fileToString(File file) throws IOException
    {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);

        StringBuilder result = new StringBuilder();

        String line = br.readLine();

        while (line != null)
        {
            result.append(line + "\n");
            line = br.readLine();
        }

        fr.close();
        br.close();
        return result.toString();
    }

}


text:
class NodeBuild < Formula
  desc "Install NodeJS versions"
  homepage "https://github.com/OiNutter/node-build"
  url "https://github.com/OiNutter/node-build/archive/v2.0.2.tar.gz"
  sha256 "b48137946700320933014f4435f61c6b6375d0aa9c4f55faeb29a9e0e1ad934c"
  head "https://github.com/OiNutter/node-build.git"

  bottle :unneeded

  depends_on "autoconf" => [:recommended, :run]
  depends_on "pkg-config" => [:recommended, :run]
  depends_on "openssl" => :recommended

  def install
    ENV["PREFIX"] = prefix
    system "./install.sh"
  end

  test do
    system "#{bin}/node-build", "--definitions"
  end
end


text:
package org.javers.core.json.typeadapter.commit;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import org.javers.core.json.JsonTypeAdapterTemplate;
import org.javers.core.metamodel.object.CdoSnapshotState;
import org.javers.core.metamodel.property.Property;

/**
 * @author bartosz walacik
 */
public class CdoSnapshotStateTypeAdapter extends JsonTypeAdapterTemplate<CdoSnapshotState> {

    @Override
    public Class getValueType() {
        return CdoSnapshotState.class;
    }

    @Override
    public CdoSnapshotState fromJson(JsonElement json, JsonDeserializationContext jsonDeserializationContext) {
        throw new UnsupportedOperationException("use CdoSnapshotStateSerializer");
    }

    @Override
    public JsonElement toJson(CdoSnapshotState snapshotState, JsonSerializationContext context) {
        JsonObject jsonObject = new JsonObject();

        for (String propertyName : snapshotState.getProperties()) {
            jsonObject.add(propertyName, context.serialize(snapshotState.getPropertyValue(propertyName)));
        }

        return jsonObject;
    }
}


text:
<?php

namespace Rebond\Controller\Admin;

use Rebond\App;
use Rebond\Enums\Cms\Component;
use Rebond\Enums\Cms\Version;
use Rebond\Enums\Core\Code;
use Rebond\Enums\Core\Ratio;
use Rebond\Enums\Core\Result;
use Rebond\Enums\Core\Status;

use Rebond\Models\Cms\Page;
use Rebond\Models\Cms\UserSettings;
use Rebond\Models\FilterInfo;
use Rebond\Models\Search;
use Rebond\Repository\Cms\ComponentRepository;
use Rebond\Repository\Cms\ContentRepository;
use Rebond\Repository\Cms\FilterRepository;
use Rebond\Repository\Cms\GadgetRepository;
use Rebond\Repository\Cms\ModuleRepository;
use Rebond\Repository\Cms\PageRepository;
use Rebond\Repository\Core\FolderRepository;
use Rebond\Repository\Core\LogRepository;
use Rebond\Repository\Core\MediaRepository;
use Rebond\Repository\Core\RolePermissionRepository;
use Rebond\Repository\Core\UserRepository;
use Rebond\Repository\Core\UserRoleRepository;
use Rebond\Services\Auth;
use Rebond\Services\Converter;
use Rebond\Services\Core\FolderService;
use Rebond\Services\Core\MediaLinkService;
use Rebond\Services\Core\UserService;
use Rebond\Services\File;
use Rebond\Services\Lang;
use Rebond\Services\Log;
use Rebond\Services\Media;
use Rebond\Services\Nav;
use Rebond\Services\Template;

class ServiceController extends BaseAdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->app->setAjax(true);
    }

    public function deleteBackup()
    {
        if (!$this->hasPrivilege('admin.dev')) {
            return $this->noPrivilege('admin.dev');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // file selected
        $file = Converter::stringKey('file', 'post');

        $backupPath = $this->app->getPath('own-backup-file');

        if (isset($file)) {
            $filePath = $this->app->getPath('own-backup-file') . $file;
            if (!file_exists($filePath)) {
                $json['message'] = Lang::lang('backup_not_found');
                return json_encode($json);
            }
            $files = File::getFiles($backupPath);
            if (count($files) < 2) {
                $json['message'] = Lang::lang('backup_one_mininum');
                return json_encode($json);
            }
            if (stripos($filePath, 'launch') !== false) {
                $json['message'] = Lang::lang('backup_launch_not_deletable');
                return json_encode($json);
            }
            unlink($filePath);
            $json['result'] = Result::SUCCESS;
            $json['message'] = Lang::lang('deleted');
            return json_encode($json);
        }

        // all files in backup folder
        $files = File::getFiles($backupPath);
        foreach ($files as $file) {
            unlink($this->app->getPath('own-cache-file') . $file);
        }

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('backups_removed');
        return json_encode($json);
    }

    public function deleteBin()
    {
        if (!$this->hasPrivilege('admin.dev')) {
            return $this->noPrivilege('admin.dev');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // file selected
        $module = Converter::stringKey('module', 'post');
        $folder = Converter::stringKey('folder', 'post');
        $skin = Converter::stringKey('skin', 'post');
        $contentId = Converter::intKey('contentId', 'post');
        $file = Converter::stringKey('file', 'post');

        // module content & template
        if (isset($module, $contentId)) {
            $appData = '\Own\Repository\App\\' . $module . 'Repository';
            $item = $appData::loadById($contentId);
            if (!isset($item)) {
                $json['message'] = Lang::lang('item_not_found', [$module, $contentId]);
                return json_encode($json);
            }

            $item->delete();
            $json['result'] = Result::SUCCESS;
            $json['message'] = Lang::lang('deleted');
            return json_encode($json);
        }

        if (isset($file)) {
            $toDelete = null;
            if (isset($skin)) {
                $toDelete = $this->app->getConfig('site') . '/css/skin/' . $skin . '/';
            } else if (isset($module)) {
                $toDelete = $this->app->getPath('own-view') . 'App/' . $module . '/';
            } else if (isset($folder)) {
                $toDelete = $this->app->getPath('own-view') . $folder . '/';
            }
            if (isset($toDelete)) {
                if (!file_exists($toDelete . $file)) {
                    $json['message'] = Lang::lang('error_file_not_found', [$file]);
                    return json_encode($json);
                }
                if (!File::delete($toDelete, $file)) {
                    $json['message'] = Lang::lang('error_file_not_deleted', [$file]);
                    return json_encode($json);
                }
                $json['result'] = Result::SUCCESS;
                $json['message'] = Lang::lang('deleted');
                return json_encode($json);
            }
        }

        $json['message'] = Lang::lang('error_parameters_invalid');
        return json_encode($json);
    }

    public function deleteCache()
    {
        if (!$this->hasPrivilege('admin.config.edit')) {
            return $this->noPrivilege('admin.config.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // file selected
        $file = Converter::stringKey('file', 'post');
        $cachePath = $this->app->getPath('own-cache-file');

        if (isset($file)) {
            $filePath = $cachePath . $file;
            if (!file_exists($filePath)) {
                $json['message'] = Lang::lang('error_file_not_found', [$file]);
                return json_encode($json);
            }
            unlink($filePath);
            $json['result'] = Result::SUCCESS;
            $json['message'] = Lang::lang('cache_deleted');
            return json_encode($json);
        }

        // all files in cache folder
        $files = File::getFiles($cachePath);
        foreach ($files as $file) {
            unlink($cachePath . $file);
        }

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('cache_all_deleted');
        return json_encode($json);
    }

    public function deleteFolder()
    {
        if (!$this->hasPrivilege('admin.media.edit')) {
            return $this->noPrivilege('admin.media.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $id = Converter::intKey('id', 'post');

        if (!isset($id)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        if ($id == 1) {
            $json['message'] = Lang::lang('folder_cannot_delete_root');
            return json_encode($json);
        }

        // check item
        $folder = FolderRepository::loadById($id);

        if (!isset($folder)) {
            $json['message'] = Lang::lang('item_not_found', [Lang::lang('folder'), $id]);
            return json_encode($json);
        }

        // find all children folders
        $folderChildren = FolderRepository::getChildren($id);
        if ($folderChildren) {
            foreach ($folderChildren as $folderChild) {
                FolderRepository::deleteById($folderChild);
                MediaRepository::moveToRoot($folderChild);
            }
        }
        // remove folders
        FolderRepository::deleteById($id);
        MediaRepository::moveToRoot($id);

        Log::log(Code::TRACK, 'folder deleted [' . $folder->getId() . ':' . $folder->getTitle() . ']', __FILE__,
            __LINE__);

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('folder_children_deleted');
        return json_encode($json);
    }

    public function deleteMedia()
    {
        if (!$this->hasPrivilege('admin.media.edit')) {
            return $this->noPrivilege('admin.media.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $mediaId = Converter::intKey('id', 'post', 0);

        // get media
        $media = MediaRepository::loadById($mediaId);
        if (!isset($media)) {
            $json['message'] = Lang::lang('item_not_found', [Lang::lang('media'), $mediaId]);
            return json_encode($json);
        }

        // find all entities which use the medium
        $count = MediaLinkService::getLinkedMedia($mediaId, true);

        if ($count > 0) {
            $json['message'] = Lang::lang('error_media_in_use') . ' ' . $count . ' ' . Lang::lang('items') . '';
            return json_encode($json);
        }

        $result = MediaRepository::deleteById($media->getId());
        if ($result == Result::ERROR) {
            $json['message'] = Lang::lang('error_item_not_deleted', [$media->getTitle()]);
            return json_encode($json);
        }

        File::deleteAllMedia($media->getPath(), $media->getUpload(), true);

        Log::log(Code::TRACK, 'media deleted [' . $media->getId() . ':' . $media->getTitle() . ']', __FILE__, __LINE__);

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('deleted');
        return json_encode($json);
    }

    public function deletePage()
    {
        if (!$this->hasPrivilege('admin.page.edit')) {
            return $this->noPrivilege('admin.page.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $id = Converter::intKey('id', 'post', 0);

        if ($id < Page::FIRST_ID_OF_EDITABLE) {
            $json['message'] = Lang::lang('page_protected');
            return json_encode($json);
        }

        // Check item
        $page = PageRepository::loadById($id);

        if (!isset($page)) {
            $json['message'] = Lang::lang('error_page_invalid', [$id]);
            return json_encode($json);
        }

        // Find all children pages
        $pageChildren = PageRepository::getPagesIdToDelete($id);
        if ($pageChildren) {
            foreach ($pageChildren as $pageChild) {
                PageRepository::deleteById($pageChild);
                GadgetRepository::deleteByPageId($pageChild);
            }
        }

        Log::log(Code::TRACK, 'page deleted [' . $page->getId() . ':' . $page->getTitle() . ']', __FILE__, __LINE__);

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('page_children_deleted');
        return json_encode($json);
    }

    public function getMedia()
    {
        if (!$this->hasPrivilege('admin.media')) {
            return $this->noPrivilege('admin.media');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $id = Converter::intKey('id', 'post', 0);

        $mediaModel = MediaRepository::loadById($id);
        if (!isset($mediaModel)) {
            $json['message'] = Lang::lang('error_media_invalid');
            return json_encode($json);
        }

        $json['result'] = Result::SUCCESS;
        $json['html'] = Media::showFromModel($mediaModel, 512, 512, Ratio::KEEP_MAX);
        return json_encode($json);
    }

    public function imageList()
    {
        if (!$this->hasPrivilege('admin.content.edit')) {
            return $this->noPrivilege('admin.content.edit');
        }

        $mediaList = $this->app->getConfig('admin') . 'js/image-list.js';
        if (file_exists($mediaList)) {
            return file_get_contents($mediaList);
        }
        return [];
    }

    public function listComponent()
    {
        if (!$this->hasPrivilege('admin.cms')) {
            return $this->noPrivilege('admin.cms');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $hashParam = Converter::stringKey('hash', 'post', 'no');

        $hash = explode('/', $hashParam);
        $status = (isset($hash[0]) && $hash[0] != '') ? $hash[0] : 'active';
        $page = (isset($hash[1]) && $hash[1] != '') ? (int)$hash[1] : 1;

        $options = [];
        if ($status == 'active') {
            $options['where'][] = 'component.status IN (0,1)';
        } else {
            $options['where'][] = 'component.status = 2';
        }
        $componentCount = ComponentRepository::count($options);

        // get user settings
        $userSettings = $this->signedUser->getUserSettings();
        $maxByPage = isset($userSettings) ? (int)$userSettings->getPagingValue() : 10;

        $page = Nav::getCurrentPage($page, $componentCount, $maxByPage);

        // add select, join, order and limit
        $options['select'][] = ModuleRepository::getList([], 'component_module');
        $options['join'][] = 'cms_module component_module ON component_module.id = component.module_id';
        $options['order'][] = 'component_module.title, component.title';
        $options['limit'][] = (($page - 1) * $maxByPage) . ', ' . $maxByPage;

        $components = ComponentRepository::loadAll($options);

        $tpl = new Template(Template::MODULE_ADMIN, ['cms', 'component']);
        $tpl->set('items', $components);

        $tplFilter = new Template(Template::MODULE_ADMIN, ['cms', 'component']);
        $tplFilter->set('paging', Nav::renderPaging($componentCount, '#' . $status . '/', $maxByPage, $page));
        $tplFilter->set('itemsPerPage', Nav::renderItemsPerPage($maxByPage));
        $tplFilter->set('status', $status);

        $tplLayout = new Template(Template::ADMIN, ['admin']);
        $tplLayout->set('column1', $tplFilter->render('filter'));
        $tplLayout->set('column2', $tpl->render('table'));

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('list_updated') . ' (' . count($components) . ')';
        $json['html'] = $tplLayout->render('layout-2-row');
        return json_encode($json);
    }

    public function listContent()
    {
        if (!$this->hasPrivilege('admin.content')) {
            return $this->noPrivilege('admin.content');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $hashParam = Converter::stringKey('hash', 'post');

        $hash = explode('/', $hashParam);
        $moduleName = (isset($hash[0]) && $hash[0] != '') ? ucfirst($hash[0]) : '';
        $version = (isset($hash[1]) && $hash[1] != '') ? $hash[1] : 'published';
        $page = (isset($hash[2]) && $hash[2] != '') ? (int)$hash[2] : 1;
        $order = (isset($hash[3]) && $hash[3] != '') ? $hash[3] : 'published_date-desc';

        if ($moduleName == '') {
            $tplMain = new Template(Template::ADMIN, ['admin', 'content']);
            $json['result'] = Result::NO_CHANGE;
            $json['html'] = $tplMain->render('index');
            return json_encode($json);
        }

        $module = ModuleRepository::loadByName($moduleName);
        if (!isset($module)) {
            $tplMain = new Template(Template::ADMIN, ['admin', 'content']);

            $json['result'] = Result::NO_CHANGE;
            $json['html'] = $tplMain->render('index');
            return json_encode($json);
        }

        if (!(in_array($order, [
            'title-asc',
            'published_date-asc',
            'created_date-asc',
            'title-desc',
            'published_date-desc',
            'created_date-desc'
        ]))) {
            $order = 'published_date-desc';
        }

        // check
        $appData = '\Own\Repository\App\\' . $moduleName . 'Repository';

        // get user settings
        $userSettings = $this->signedUser->getUserSettings();
        $maxByPage = isset($userSettings) ? (int)$userSettings->getContentPagingValue() : 10;

        $countItems = $appData::countByVersion($version, false);

        $page = Nav::getCurrentPage($page, $countItems, $maxByPage);

        $options = [];
        $options['limit'][] = (($page - 1) * $maxByPage) . ', ' . $maxByPage;
        $options['order'][] = 'content.' . str_replace('-', ' ', $order);

        $genericModels = $appData::loadByVersion($version, false, $options);

        // view

        // filter
        $tplFilter = new Template(Template::ADMIN, ['admin', 'content']);
        $tplFilter->set('paging',
            Nav::renderPaging($countItems, '#' . $moduleName . '/' . $version . '/', $maxByPage, $page, '/' . $order));
        $tplFilter->set('itemsPerPage', Nav::renderItemsPerPage($maxByPage));
        $tplFilter->set('module', $moduleName);
        $tplFilter->set('version', $version);
        $tplFilter->set('order', $order);

        // content
        $tpl = new Template(Template::MODULE_ADMIN, ['app', Converter::toSnakeCase($moduleName)]);
        $tpl->set('items', $genericModels);
        $tpl->set('version', $version);
        $tpl->set('filter', $module->getHasFilter());
        $tpl->set('workflow', $module->getWorkflow());

        $json['result'] = Result::SUCCESS;
        $json['tabon'] = $version;
        $json['module'] = $moduleName;
        $json['message'] = Lang::lang('list_updated') . ' (' . count($genericModels) . ')';
        $json['html'] = $tplFilter->render('filter') . $tpl->render('admin-app-table');
        return json_encode($json);
    }

    public function listMedia()
    {
        if (!$this->hasPrivilege('admin.media')) {
            return $this->noPrivilege('admin.media');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $hashParam = Converter::stringKey('hash', 'post');

        $hash = explode('/', $hashParam);
        $folderId = (isset($hash[0]) && $hash[0] != '') ? (int)$hash[0] : 1;
        $page = (isset($hash[1]) && $hash[1] != '') ? (int)$hash[1] : 1;
        $type = (isset($hash[2]) && $hash[2] != '') ? $hash[2] : 'all';
        $order = (isset($hash[3]) && $hash[3] != '') ? $hash[3] : 'modified_date-desc';
        $selectable = (isset($hash[4]) && $hash[4] == 0) ? 0 : 1;

        if (!(in_array($type, ['all', 'images', 'videos', 'documents']))) {
            $type = 'all';
        }
        if (!(in_array($order, [
            'title-asc',
            'extension-asc',
            'modified_date-asc',
            'title-desc',
            'extension-desc',
            'modified_date-desc'
        ]))) {
            $order = 'modified_date-desc';
        }

        $options = [];
        $options['where'][] = 'media.status = 1';
        $options['where'][] = ['media.is_selectable = ?', $selectable];
        if ($folderId != 0) {
            $options['where'][] = ['media.folder_id = ?', $folderId];
        }
        if ($type != 'all') {
            switch ($type) {
                case 'images':
                    $options['where'][] = 'media.extension IN ("jpg", "jpeg", "png")';
                    break;
                case 'videos':
                    $options['where'][] = 'media.extension IN ("avi", "mov")';
                    break;
                case 'documents':
                    $options['where'][] = 'media.extension IN ("pdf", "xls", "xlsx", "doc", "docx")';
                    break;
            }
        }
        $mediaCount = MediaRepository::count($options);

        // get user settings
        $userSettings = $this->signedUser->getUserSettings();
        $mediaView = 'grid';
        $maxByPage = 10;
        if (isset($userSettings)) {
            $mediaView = $userSettings->getMediaViewValue();
            $maxByPage = (int)$userSettings->getMediaPagingValue();
        }

        $page = Nav::getCurrentPage($page, $mediaCount, $maxByPage);

        // add paging and order
        $options['order'][] = 'media.' . str_replace('-', ' ', $order);
        $options['limit'][] = (($page - 1) * $maxByPage) . ', ' . $maxByPage;

        $media = MediaRepository::loadAll($options);

        $tpl = new Template(Template::MODULE_ADMIN, ['core', 'media']);
        $tpl->set('items', $media);

        $tplFilter = new Template(Template::MODULE_ADMIN, ['core', 'media']);
        $urlExtension = '/' . $type . '/' . $order . '/' . $selectable;
        $tplFilter->set('paging',
            Nav::renderPaging($mediaCount, '#' . $folderId . '/', $maxByPage, $page, $urlExtension));
        $tplFilter->set('itemsPerPage', Nav::renderItemsPerPage($maxByPage));
        $tplFilter->set('mediaView', $mediaView);
        $tplFilter->set('folderId', $folderId);
        $tplFilter->set('order', $order);
        $tplFilter->set('type', $type);
        $tplFilter->set('selectable', $selectable);

        $tplLayout = new Template(Template::ADMIN, ['admin']);
        $tplLayout->set('column1', $tplFilter->render('filter-full'));
        $tplLayout->set('column2', $tpl->render($mediaView));

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('list_updated') . ' (' . count($media) . ')';
        $json['html'] = $tplLayout->render('layout-2-row');
        return json_encode($json);
    }

    public function listQuickView()
    {
        if (!$this->hasPrivilege('admin.quickview')) {
            return $this->noPrivilege('admin.quickview');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $hashParam = Converter::stringKey('hash', 'post');

        $hash = explode('/', $hashParam);
        $moduleName = isset($hash[0]) ? $hash[0] : '';
        $page = isset($hash[1]) ? (int)$hash[1] : 1;

        if ($moduleName == '') {
            $tplLayout = new Template(Template::ADMIN, ['admin']);
            $tplMain = new Template(Template::ADMIN, ['admin', 'quickview']);
            $tplLayout->set('column1', $tplMain->render('index'));
            $json['result'] = Result::NO_CHANGE;
            $json['html'] = $tplLayout->render('layout-1-col');
            return json_encode($json);
        }

        // check
        $busData = '\Own\Repository\Bus\\' . $moduleName . 'Repository';

        // method check
        if (!method_exists($busData, 'count')) {
            $tplLayout = new Template(Template::ADMIN, ['admin']);
            $tplMain = new Template(Template::ADMIN, ['admin', 'quickview']);
            $tplLayout->set('column1', $tplMain->render('quickview-non-persistent'));
            $json['result'] = Result::NO_CHANGE;
            $json['html'] = $tplLayout->render('layout-1-col');
            return json_encode($json);
        }

        // get user settings
        $userSettings = $this->signedUser->getUserSettings();
        $maxByPage = isset($userSettings) ? (int)$userSettings->getPagingValue() : 10;

        $countItems = $busData::count();

        $page = Nav::getCurrentPage($page, $countItems, $maxByPage);

        $options = [];
        $options['limit'][] = (($page - 1) * $maxByPage) . ', ' . $maxByPage;

        $genericModels = $busData::loadAll($options);

        // view

        // filter
        $tplFilter = new Template(Template::ADMIN, ['admin', 'quickview']);
        $tplFilter->set('paging', Nav::renderPaging($countItems, '#' . $moduleName . '/', $maxByPage, $page));
        $tplFilter->set('itemsPerPage', Nav::renderItemsPerPage($maxByPage));
        $tplFilter->set('entity', $moduleName);

        // content
        $tpl = new Template(Template::MODULE_ADMIN, ['bus', $moduleName]);
        $tpl->set('items', $genericModels);

        $tplLayout = new Template(Template::ADMIN, ['admin']);
        $tplLayout->set('column1', $tplFilter->render('filter'));
        $tplLayout->set('column2', $tpl->render('admin-bus-table'));

        $json['result'] = Result::SUCCESS;
        $json['module'] = $moduleName;
        $json['message'] = Lang::lang('list_updated') . ' (' . count($genericModels) . ')';
        $json['html'] = $tplLayout->render('layout-2-row');
        return json_encode($json);
    }

    public function listUser()
    {
        if (!$this->hasPrivilege('admin.user')) {
            return $this->noPrivilege('admin.user');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $hashParam = Converter::stringKey('hash', 'post');

        $hash = explode('/', $hashParam);
        $status = (isset($hash[0]) && $hash[0] != '') ? $hash[0] : 'active';
        $page = (isset($hash[1]) && $hash[1] != '') ? (int)$hash[1] : 1;
        $order = (isset($hash[2]) && $hash[2] != '') ? $hash[2] : 'email-asc';

        $options = [];
        if ($status == 'active') {
            $options['where'][] = 'user.status IN (0,1)';
        } else {
            $options['where'][] = 'user.status = 2';
        }
        $userCount = UserRepository::count($options);

        if (!(in_array($order, [
            'email-asc',
            'first_name-asc',
            'last_name-asc',
            'created_date-asc',
            'email-desc',
            'first_name-desc',
            'last_name-desc',
            'created_date-desc'
        ]))) {
            $order = 'email-asc';
        }

        // get user settings
        $userSettings = $this->signedUser->getUserSettings();
        $maxByPage = isset($userSettings) ? (int)$userSettings->getPagingValue() : 10;

        $page = Nav::getCurrentPage($page, $userCount, $maxByPage);

        // add paging and order
        $options['limit'][] = (($page - 1) * $maxByPage) . ', ' . $maxByPage;
        $options['order'][] = 'user.' . str_replace('-', ' ', $order);

        $users = UserRepository::loadAll($options);

        $tpl = new Template(Template::MODULE_ADMIN, ['core', 'user']);
        $tpl->set('items', $users);

        $tplFilter = new Template(Template::MODULE_ADMIN, ['core', 'user']);
        $tplFilter->set('paging', Nav::renderPaging($userCount, '#' . $status . '/', $maxByPage, $page));
        $tplFilter->set('itemsPerPage', Nav::renderItemsPerPage($maxByPage));
        $tplFilter->set('status', $status);
        $tplFilter->set('order', $order);

        $tplLayout = new Template(Template::ADMIN, ['admin']);
        $tplLayout->set('column1', $tplFilter->render('filter-full'));
        $tplLayout->set('column2', $tpl->render('table'));

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('list_updated') . ' (' . count($users) . ')';
        $json['html'] = $tplLayout->render('layout-2-row');
        return json_encode($json);
    }

    public function search()
    {
        if (!$this->hasPrivilege('admin')) {
            return $this->noPrivilege('admin');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $search = Converter::stringKey('search', 'post');
        if (!isset($search)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        $searchResults = [];

        // search content
        $options = [];
        $options['clearSelect'] = true;
        $options['select'][] = ModuleRepository::getList(['id', 'title']);
        $options['where'][] = 'module.status = 1';
        $options['where'][] = 'module.has_content = 1';
        $modules = ModuleRepository::loadAll($options);

        $options2 = [];
        $options2['clearSelect'] = true;
        $options2['where'][] = ['LOWER(content.title) LIKE ?', '%' . strtolower($search) . '%'];
        $options2['where'][] = ['content.version IN (?)', [0, 1, 3]];
        $options2['limit'][] = '0, 10';

        foreach ($modules as $module) {
            $appData = '\Own\Repository\App\\' . $module->getName() . 'Repository';

            $options2['select'][] = $appData::getList(['app_id']);
            $options2['select'][] = ContentRepository::getList(['title', 'version']);

            $items = $appData::loadAll($options2);
            if (isset($items) && count($items) > 0) {
                foreach ($items as $item) {
                    $result = new Search();
                    $result->setType($module->getTitle());
                    $result->setTitle($item->getTitle());
                    $result->setStatus($item->getVersion());
                    $result->setStatusValue($item->getVersionValue());
                    $result->setLink('/content/edit/?module=' . $module->getName() . '&id=' . $item->getAppId());
                    $searchResults[] = $result;
                }
            }
        }

        // Search users
        $options = [];
        $options['clearSelect'] = true;
        $options['select'][] = UserRepository::getList(['id', 'email', 'first_name', 'last_name', 'status']);
        $options['where'][] = ['LOWER(user.email) LIKE ?', '%' . strtolower($search) . '%'];
        $users = UserRepository::loadAll($options);
        foreach ($users as $user) {
            $result = new Search();
            $result->setType(Lang::lang('user'));
            $result->setTitle($user->getFullName());
            $result->setStatus($user->getStatus());
            $result->setStatusValue($user->getStatusValue());
            $result->setLink('/user/edit?id=' . $user->getId());
            $searchResults[] = $result;
        }

        // search media
        $options = [];
        $options['clearSelect'] = true;
        $options['select'][] = MediaRepository::getList(['id', 'title', 'status']);
        $options['where'][] = ['LOWER(media.title) LIKE ?', '%' . strtolower($search) . '%'];
        $media = MediaRepository::loadAll($options);
        foreach ($media as $medium) {
            $result = new Search();
            $result->setType(Lang::lang('media'));
            $result->setTitle($medium->getTitle());
            $result->setStatus($medium->getStatus());
            $result->setStatusValue($medium->getStatusValue());
            $result->setLink('/media/edit?id=' . $medium->getId());
            $searchResults[] = $result;
        }

        // view
        $tpl = new Template(Template::ADMIN, ['admin']);
        $tpl->set('results', $searchResults);

        $json['result'] = Result::SUCCESS;
        $json['message'] = $tpl->render('search');
        return json_encode($json);
    }

    public function selectMedia()
    {
        if (!$this->hasPrivilege('admin.content.edit')) {
            return $this->noPrivilege('admin.content.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $field = Converter::stringKey('field', 'post');
        $hashParam = Converter::stringKey('hash', 'post');
        $search = Converter::stringKey('search', 'post');

        if (!isset($field, $hashParam)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        $hash = explode('/', substr($hashParam, 1));

        $folderId = (isset($hash[0]) && $hash[0] != '') ? (int)$hash[0] : 0;
        $page = (isset($hash[1]) && $hash[1] != '') ? (int)$hash[1] : 1;
        $type = (isset($hash[2]) && $hash[2] != '') ? $hash[2] : 'all';
        $order = (isset($hash[3]) && $hash[3] != '') ? $hash[3] : 'modified_date-desc';

        if (!(in_array($type, ['all', 'images', 'videos', 'documents']))) {
            $type = 'all';
        }
        if (!(in_array($order, [
            'title-asc',
            'extension-asc',
            'modified_date-asc',
            'title-desc',
            'extension-desc',
            'modified_date-desc'
        ]))) {
            $order = 'modified_date-desc';
        }

        $options = [];
        $options['where'][] = 'media.status = 1';
        $options['where'][] = 'media.is_selectable = 1';
        if ($folderId != 0) {
            $options['where'][] = ['media.folder_id = ?', $folderId];
        }
        if (isset($search) && $search != '') {
            $options['where'][] = ['media.title LIKE ?', '%' . $search . '%'];
        }
        if ($type != 'all') {
            switch ($type) {
                case 'images':
                    $options['where'][] = 'media.extension IN ("jpg", "jpeg", "png")';
                    break;
                case 'videos':
                    $options['where'][] = 'media.extension IN ("avi", "mov")';
                    break;
                case 'documents':
                    $options['where'][] = 'media.extension IN ("pdf", "xls", "xlsx", "doc", "docx")';
                    break;
            }
        }
        $mediaCount = MediaRepository::count($options);

        // get user settings
        $userSettings = $this->signedUser->getUserSettings();
        $mediaView = 'grid';
        $maxByPage = 10;
        if (isset($userSettings)) {
            $mediaView = $userSettings->getMediaViewValue();
            $maxByPage = (int)$userSettings->getMediaPagingValue();
        }

        $page = Nav::getCurrentPage($page, $mediaCount, $maxByPage);

        $folders = FolderService::renderList();

        // add paging and order
        $options['order'][] = 'media.' . str_replace('-', ' ', $order);
        $options['limit'][] = (($page - 1) * $maxByPage) . ', ' . $maxByPage;

        $media = MediaRepository::loadAll($options);

        $tpl = new Template(Template::MODULE_ADMIN, ['core', 'media']);
        $tpl->set('items', $media);
        $tpl->set('field', $field);

        $tplFilter = new Template(Template::MODULE_ADMIN, ['core', 'media']);
        $tplFilter->set('paging',
            Nav::renderPaging($mediaCount, '#' . $folderId . '/', $maxByPage, $page, '/' . $type . '/' . $order));
        $tplFilter->set('folders', $folders);
        $tplFilter->set('itemsPerPage', Nav::renderItemsPerPage($maxByPage));
        $tplFilter->set('mediaView', $mediaView);
        $tplFilter->set('order', $order);
        $tplFilter->set('type', $type);
        $tplFilter->set('folderId', $folderId);
        $tplFilter->set('hash', '#' . $folderId . '/' . $page . '/' . $type . '/' . $order);
        $tplFilter->set('search', $search);

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('list_updated') . ' (' . count($media) . ')';
        $json['html'] = $tplFilter->render('filter-modal');
        $json['html'] .= $tpl->render($mediaView . '-modal');
        return json_encode($json);
    }

    public function selectGadgetFilter()
    {
        if (!$this->hasPrivilege('admin.page.edit')) {
            return $this->noPrivilege('admin.page.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $id = Converter::intKey('id', 'post', 0);
        $search = Converter::stringKey('search', 'post');

        $gadget = GadgetRepository::loadById($id);
        if (!isset($gadget)) {
            $json['message'] = Lang::lang('item_not_found', [Lang::lang('gadget'), $id]);
            return json_encode($json);
        }

        $results = [];

        if ($gadget->getComponent()->getType() == Component::SINGLE_ELEMENT) {
            $appData = '\Own\Repository\App\\' . $gadget->getComponent()->getModule()->getName() . 'Repository';
            $options = [];
            $options['where'][] = ['content.version IN (?)', [0, 1, 3]];
            if (isset($search) && $search != '') {
                $options['where'][] = ['content.title LIKE ?', '%' . $search . '%'];
            }
            $options['order'][] = 'content.title';
            $items = $appData::loadAll($options, false);
            if (isset($items) && count($items) > 0) {
                foreach ($items as $item) {
                    $result = new FilterInfo();
                    $result->setId($item->getContentGroup());
                    $result->setTitle($item->getTitle());
                    $result->setAppId($item->getAppId());
                    $results[] = $result;
                }
            }
        } else if ($gadget->getComponent()->getType() == Component::FILTERED_CARDS) {
            $options = [];
            $options['where'][] = ['filter.module_id = ?', $gadget->getComponent()->getModuleId()];
            if ($search != '') {
                $options['where'][] = ['filter.title LIKE ?', '%' . $search . '%'];
            }
            $options['order'][] = 'filter.title';
            $filters = FilterRepository::loadAll($options);
            if (isset($filters) && count($filters) > 0) {
                foreach ($filters as $filter) {
                    $result = new FilterInfo();
                    $result->setId($filter->getId());
                    $result->setTitle($filter->getTitle());
                    $result->setAppId($filter->getId());
                    $results[] = $result;
                }
            }
        }

        $tpl = new Template(Template::MODULE_ADMIN, ['cms', 'gadget']);
        $tpl->set('id', $gadget->getId());
        $tpl->set('results', $results);
        $tpl->set('search', $search);
        $json['result'] = Result::SUCCESS;
        $json['html'] = $tpl->render('filter-modal');
        return json_encode($json);
    }

    public function updateGadget()
    {
        if (!$this->hasPrivilege('admin.page.edit')) {
            return $this->noPrivilege('admin.page.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $id = Converter::intKey('id', 'post');
        $property = Converter::stringKey('property', 'post');
        $value = Converter::intKey('value', 'post');

        if (!isset($id, $property, $value)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        // Check item
        $gadget = GadgetRepository::loadById($id);
        if (!isset($gadget)) {
            $json['message'] = Lang::lang('error_gadget_invalid', [$id]);
            return json_encode($json);
        }

        // Save item
        switch ($property) {
            case 'column':
                $gadget->setCol($value);
                break;
            case 'displayOrder':
                $gadget->setDisplayOrder($value);
                break;
            case 'filter':
                $gadget->setFilterId($value);
                break;
        }

        $gadget->save();

        Log::log(Code::TRACK,
            'gagdet updated [page:' . $gadget->getPageId() . ', component:' . $gadget->getComponentId() . ']', __FILE__,
            __LINE__);

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('saved');
        return json_encode($json);
    }

    public function updateStatus()
    {
        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $package = Converter::stringKey('package', 'post');
        $entity = Converter::stringKey('entity', 'post');
        $id = Converter::intKey('id', 'post');
        $id2 = Converter::intKey('id2', 'post');
        $status = Converter::intKey('status', 'post');

        if (!isset($package, $entity, $id, $status)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        if (!$this->checkPrivilegeByEntity($entity)) {
            return $this->noPrivilege($entity);
        }

        // check item
        $namespace = (in_array($package, ['App', 'Bus'])) ? '\Own' : '\Rebond';
        $genericData = $namespace . '\Repository\\' . $package . '\\' . $entity . 'Repository';

        $newStatus = Status::INACTIVE;

        // active
        if ($status == Status::INACTIVE) {
            $newStatus = Status::ACTIVE;
            // inactive or undelete
        } else if (in_array($status, [Status::ACTIVE, Status::DELETED])) {
            $newStatus = Status::INACTIVE;
            // delete
        } else if ($status === Status::TO_DELETE) {
            $newStatus = Status::DELETED;
        }

        // block
        if ($entity == 'User') {
            if ($this->signedUser->getId() == $id) {
                return json_encode([
                    'result' => Result::ERROR,
                    'message' => Lang::lang('error_status_own')
                ]);
            }
            if (!UserService::isEditable($this->signedUser, $id)) {
                return json_encode([
                    'result' => Result::ERROR,
                    'message' => Lang::lang('error_dev_update')
                ]);
            }
        }

        $update = 'saved';

        // update status
        if ($id2 == 0) { // single id table
            if ($newStatus == Status::INACTIVE || $newStatus == Status::ACTIVE) {
                $genericData::updateStatus($id, $newStatus);
            } else if ($newStatus == Status::DELETED) {
                $update = 'deleted';

                switch ($entity) {
                    case 'Feedback':
                    case 'Gadget':
                    case 'Log':
                    case 'MediaLink':
                    case 'User':
                        $genericData::deleteById($id);
                        break;
                    case 'Component':
                        GadgetRepository::deleteByComponentId($id);
                        $genericData::updateStatus($id, $newStatus);
                        break;
                    case 'Filter':
                        ContentRepository::clearFilter($id);
                        $genericData::deleteById($id);
                        break;
                    case 'Layout':
                        $options = [];
                        $options['clearSelect'] = true;
                        $options['select'][] = PageRepository::getList(['id']);
                        $options['join'][] = 'cms_layout layout ON layout.id = page.layout_id';
                        $options['where'][] = ['layout.id = ?', $id];
                        $pages = PageRepository::loadAll($options);
                        if (isset($pages) && count($pages) > 0) {
                            $json['result'] = Result::ERROR;
                            $json['message'] = Lang::lang('error_item_in_use', [
                                Lang::lang('layout'),
                                count($pages),
                                Lang::lang('pages')
                            ]);
                            return json_encode($json);
                        }
                        $genericData::deleteById($id);
                        break;
                    case 'Module':
                        $options = [];
                        $options['clearSelect'] = true;
                        $options['select'][] = ComponentRepository::getList(['id']);
                        $options['where'][] = ['component.module_id = ?', $id];
                        $components = ComponentRepository::loadAll($options);
                        if (count($components) > 0) {
                            foreach ($components as $component) {
                                ComponentRepository::updateStatus($component->getId(), $newStatus);
                                GadgetRepository::deleteByComponentId($component->getId());
                            }
                        }
                        $genericData::updateStatus($id, $newStatus);
                        break;
                    case 'Permission':
                        RolePermissionRepository::deleteByPermissionId($id);
                        $genericData::deleteById($id);
                        break;
                    case 'Role':
                        $userRoles = UserRoleRepository::loadAllByRoleId($id);
                        if (isset($userRoles) && count($userRoles) > 0) {
                            $json['result'] = Result::ERROR;
                            $json['message'] = Lang::lang('error_item_in_use', [
                                Lang::lang('role'),
                                count($userRoles),
                                Lang::lang('users')
                            ]);
                            return json_encode($json);
                        }
                        UserRoleRepository::deleteByRoleId($id);
                        RolePermissionRepository::deleteByRoleId($id);
                        $genericData::deleteById($id);
                        break;
                    case 'Template':
                        $options = [];
                        $options['clearSelect'] = true;
                        $options['select'][] = PageRepository::getList(['id']);
                        $options['join'][] = 'cms_template template ON template.id = page.template_id';
                        $options['where'][] = ['template.id = ?', $id];
                        $pages = PageRepository::loadAll($options);
                        if (isset($pages) && count($pages) > 0) {
                            $json['result'] = Result::ERROR;
                            $json['message'] = Lang::lang('error_item_in_use', [
                                Lang::lang('template'),
                                count($pages),
                                Lang::lang('users')
                            ]);
                            return json_encode($json);
                        }
                        $genericData::deleteById($id);
                        break;
                    default:
                        Log::log(Code::ENTITY_NOT_FOUND, $entity, __FILE__, __LINE__);
                        return json_encode([
                            'result' => Result::ERROR,
                            'message' => Lang::lang('item_not_found', [$entity, $id])
                        ]);
                }
            }
        } else { // double id table
            if ($newStatus == Status::DELETED) {
                $genericData::deleteByIds($id, $id2);
                $update = 'deleted';
            } else {
                $genericData::updateStatus($id, $id2, $newStatus);
            }
        }

        Log::log(Code::TRACK,
            'update status [package:' . $package . ', entity:' . $entity . ', id:' . $id . ',' . $id2 . ', status:' . $status . ']',
            __FILE__, __LINE__);

        return json_encode([
            'result' => Result::SUCCESS,
            'message' => Lang::lang($update)
        ]);
    }

    public function updateUserSettings()
    {
        if (!$this->hasPrivilege(null)) {
            return $this->noPrivilege('admin');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $value = Converter::intKey('value', 'post');
        $type = Converter::stringKey('type', 'post');

        if (!isset($type, $value)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        // Check item
        $userSettings = $this->signedUser->getUserSettings();
        if (!isset($userSettings)) {
            $userSettings = new UserSettings();
            $userSettings->setId($this->signedUser->getId());
        }

        // Save item
        switch ($type) {
            case 'mediaView':
                $userSettings->setMediaView($value);
                break;
            case 'mediaPaging':
                $userSettings->setMediaPaging($value);
                break;
            case 'contentPaging':
                $userSettings->setContentPaging($value);
                break;
            case 'paging':
                $userSettings->setPaging($value);
                break;
        }
        $userSettings->save();

        $json['result'] = Result::SUCCESS;
        $json['message'] = Lang::lang('saved');
        return json_encode($json);
    }

    public function updateVersion()
    {
        if (!$this->hasPrivilege('admin.content.edit')) {
            return $this->noPrivilege('admin.content.edit');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        // check
        $entity = Converter::stringKey('entity', 'post');
        $appId = Converter::intKey('appId', 'post');
        $version = Converter::intKey('version', 'post');

        if (!isset($entity, $appId, $version)) {
            $json['message'] = Lang::lang('error_parameters_invalid');
            return json_encode($json);
        }

        // load model
        $appData = '\Own\Repository\App\\' . $entity . 'Repository';
        $model = $appData::loadById($appId);

        if (!isset($model)) {
            $json['message'] = Lang::lang('item_not_found', [$entity, $appId]);
            return json_encode($json);
        }

        $json['value'] = $model->getVersion();
        $appData::updateVersion($model, $version);

        $json['result'] = Result::SUCCESS;
        $json['entity'] = $entity;
        $json['message'] = $version == Version::DELETED
            ? Lang::lang('deleted')
            : Lang::lang('version_updated');
        return json_encode($json);
    }

    public function upload()
    {
        if (!$this->hasPrivilege('admin.media.upload')) {
            return $this->noPrivilege('admin.media.upload');
        }

        $json = [];
        $json['result'] = Result::ERROR;

        $folderId = Converter::intKey('folderId', 'post');
        $replaceId = Converter::intKey('replaceId', 'post');

        $resultUpload = Media::upload('file', true, $folderId, $replaceId);

        if ($resultUpload['result'] == Result::ERROR) {
            Log::log(Code::MEDIA_NOT_SAVED, $resultUpload['message'], __FILE__, __LINE__);
            $json['message'] = $resultUpload['message'];
            return json_encode($json);
        }

        $json['result'] = Result::SUCCESS;
        $json['id'] = $resultUpload['mediaId'];

        $text = (isset($folderId)) ? 'media_uploaded' : 'medium_replaced';
        $json['message'] = Lang::lang($text, [$resultUpload['filename']]);

        return json_encode($json);
    }

    /**
     * @param string $entity
     * @throws bool
     */
    private function checkPrivilegeByEntity($entity)
    {
        $map = [
            'Component' => 'admin.cms.edit',
            'Feedback' => 'admin.dev',
            'Content' => 'admin.dev',
            'Filter' => 'admin.content.filter',
            'Folder' => 'admin.media.edit',
            'Gadget' => 'admin.page.edit',
            'Layout' => 'admin.cms.edit',
            'Log' => 'admin.tools.edit',
            'Media' => 'admin.media.edit',
            'Module' => 'media.cms.edit',
            'MediaLink' => 'media.config.edit',
            'Page' => 'admin.page.edit',
            'Permission' => 'admin.config.edit',
            'Role' => 'admin.config.edit',
            'RolePermission' => 'admin.config.edit',
            'Site' => 'admin.config.edit',
            'Template' => 'admin.cms.edit',
            'User' => 'admin.user.edit',
            'UserRole' => 'admin.user.edit',
            'UserSecurity' => 'admin.user.security',
            'UserSettings' => 'admin.dev',
        ];
        if (!array_key_exists($entity, $map)) {
            return false;
        }
        return self::hasPrivilege($map[$entity]);
    }

    /**
     * @param string $permission
     * @return bool
     */
    private function hasPrivilege($permission)
    {
        return Auth::isAdminAuthorized($this->signedUser, $permission);
    }

    /**
     * @param string $permission
     * @return string
     */
    private function noPrivilege($permission)
    {
        Log::log(
            Code::NOT_ENOUGH_PRIVILEGE,
            'permission: ' . $permission . ', user: ' . $this->signedUser->getFullName(),
            __FILE__,
            __LINE__
        );
        return json_encode(
            [
                'result' => Result::ERROR,
                'message' => Lang::lang('access_non_authorized')
            ]
        );
    }
}


text:
<?php
namespace Avatar;

use MediaWiki\MediaWikiServices;

class SpecialUpload extends \SpecialPage {

	public function __construct() {
		parent::__construct('UploadAvatar');
	}

	public function execute($par) {
		$this->requireLogin('prefsnologintext2');

		$this->setHeaders();
		$this->outputHeader();
		$request = $this->getRequest();

		if ($this->getUser()->getBlock()) {
			throw new \UserBlockedError($this->getUser()->getBlock());
		}

		if (!MediaWikiServices::getInstance()->getPermissionManager()->userHasRight($this->getUser(), 'avatarupload')) {
			throw new \PermissionsError('avatarupload');
		}

		global $wgMaxAvatarResolution;
		$this->getOutput()->addJsConfigVars('wgMaxAvatarResolution', $wgMaxAvatarResolution);
		$this->getOutput()->addModules('ext.avatar.upload');

		if ($request->wasPosted()) {
			if ($this->processUpload()) {
				$this->getOutput()->redirect(\SpecialPage::getTitleFor('Preferences')->getLinkURL());
			}
		} else {
			$this->displayMessage('');
		}
		$this->displayForm();
	}

	private function displayMessage($msg) {
		$this->getOutput()->addHTML(\Html::rawElement('div', array('class' => 'error', 'id' => 'errorMsg'), $msg));
	}

	private function processUpload() {
		$request = $this->getRequest();
		$dataurl = $request->getVal('avatar');
		if (!$dataurl || parse_url($dataurl, PHP_URL_SCHEME) !== 'data') {
			$this->displayMessage($this->msg('avatar-notuploaded'));
			return false;
		}

		$img = Thumbnail::open($dataurl);

		global $wgMaxAvatarResolution;

		switch ($img->type) {
		case IMAGETYPE_GIF:
		case IMAGETYPE_PNG:
		case IMAGETYPE_JPEG:
			break;
		default:
			$this->displayMessage($this->msg('avatar-invalid'));
			return false;
		}

		// Must be square
		if ($img->width !== $img->height) {
			$this->displayMessage($this->msg('avatar-notsquare'));
			return false;
		}

		// Check if image is too small
		if ($img->width < 32 || $img->height < 32) {
			$this->displayMessage($this->msg('avatar-toosmall'));
			return false;
		}

		// Check if image is too big
		if ($img->width > $wgMaxAvatarResolution || $img->height > $wgMaxAvatarResolution) {
			$this->displayMessage($this->msg('avatar-toolarge'));
			return false;
		}

		$user = $this->getUser();
		Avatars::deleteAvatar($user);

		// Avatar directories
		global $wgAvatarUploadDirectory;
		$uploadDir = $wgAvatarUploadDirectory . '/' . $this->getUser()->getId() . '/';
		@mkdir($uploadDir, 0755, true);

		// We do this to convert format to png
		$img->createThumbnail($wgMaxAvatarResolution, $uploadDir . 'original.png');

		// We only create thumbnail with default resolution here. Others are generated on demand
		global $wgDefaultAvatarRes;
		$img->createThumbnail($wgDefaultAvatarRes, $uploadDir . $wgDefaultAvatarRes . '.png');

		$img->cleanup();

		$this->displayMessage($this->msg('avatar-saved'));

		global $wgAvatarLogInRC;

		$logEntry = new \ManualLogEntry('avatar', 'upload');
		$logEntry->setPerformer($this->getUser());
		$logEntry->setTarget($this->getUser()->getUserPage());
		$logId = $logEntry->insert();
		$logEntry->publish($logId, $wgAvatarLogInRC ? 'rcandudp' : 'udp');

		return true;
	}

	public function displayForm() {
		$html = '

';
		$html .= \Html::hidden('avatar', '');

		$html .= \Xml::element('button', array('id' => 'pickfile'), $this->msg('uploadavatar-selectfile'));

		$html .= ' ';

		// Submit button
		$html .= \Xml::submitButton($this->msg('uploadavatar-submit')->text());

		// Wrap with a form
		$html = \Xml::tags('form', array('action' => $this->getPageTitle()->getLinkURL(), 'method' => 'post'), $html);

		$this->getOutput()->addWikiMsg('uploadavatar-notice');
		$this->getOutput()->addHTML($html);
	}

	public function isListed() {
		return false;
	}
}


text:
+++
date = "2020-02-05T15:12:36Z"
title = "lowRISC project ideas for GSoC 2020"
+++

lowRISC has been accepted as a mentoring organisation for the [2020 Google
Summer of Code](https://summerofcode.withgoogle.com/). See the [full program
timeline](https://summerofcode.withgoogle.com/how-it-works/#timeline) for a
run-down of key dates.

Before submitting your application, please get in contact with us on [our
Zulip group chat](https://lowrisc.zulipchat.com) or send an email to potential
mentors. We are keen to start discussing potential projects with you.

For guidance on how to write the application, please check out the [GSoC
student guide]
(https://google.github.io/gsocguides/student/writing-a-proposal#the-basics).

# Project ideas (in no particular order)

## Your project here

If you have a project idea relevant to lowRISC, don't worry that it's not
listed here. For a good student with an interesting project we'll almost
definitely have an appropriate mentor. You are strongly recommended to get in
touch to discuss the idea though. Some projects might be better handled under
a different mentoring organisation, e.g. a PyPy port to RISC-V would make more
sense under the Python Software Foundation.

## A template project for Ibex custom instruction set extensions

**Summary:** Create a starting point for
[Ibex](https://github.com/lowRISC/ibex) implementers who wish to add custom
instruction set extensions.

One part of this project is to demonstrate a methodology for doing this, which
may involve making suggestions for refactorings to make this an easier task.
The project would ideally involve addressing the challenge of keeping the
example/template project functional.

Mentors: [Alex](mailto:asb@lowrisc.org), [Greg](mailto:gac@lowrisc.org),
[Pirmin](mailto:vogelpi@lowrisc.org)

## Custom compressed instruction set generation

**Summary:** Create a flow that can generate a custom compressed instruction
set tuned for a given firmware image.

This project would involve creating a tool that would analyse a firmware
image, and generate a custom compressed instruction set (or alternatively,
additions to the standard compressed instruction set) that would minimise code
size. The tool would generate the necessary instruction descriptions for LLVM
as well as the decode logic for the Ibex CPU core. There is a wealth of
additional research ideas on further reducing code size that may also be
interesting to explore in the context of this project.

Mentors: [Alex](mailto:asb@lowrisc.org), [Luís]
(mailto:luismarques@lowrisc.org), [Sam](mailto:selliott@lowrisc.org),
[Silvestrs](mailto:silvestrst@lowrisc.org)

## OpenTitan SoC tooling work

**Summary:** Improve the Python tooling in the OpenTitan project for register
description generation, documentation generation, etc.

[OpenTitan](https://opentitan.org/) contains a [range of
tools](https://docs.opentitan.org/doc/rm/), implemented in Python to help
build custom SoCs. e.g. topgen.py, regtool.py, tlgen.py. In general, these
could all benefit from further software engineering input - e.g. adding a
proper test suite, working with digital designers / design verification
engineers to implement new features. e.g. it may be interesting to extend the
vendor tool to allow the extraction of a specific piece of IP from the
OpenTitan repository and its dependencies.

Mentors: [Sam](mailto:selliott@lowrisc.org), [Silvestrs]
(mailto:silvestrst@lowrisc.org)

## Create an Ibex-based SoC platform for iCE40 UltraPlus FPGA devices

**Summary:** Create an Ibex-based demonstration platform using [IceStorm]
(http://www.clifford.at/icestorm/), the fully open source
Verilog-to-bitstream flow for iCE40 FPGAs .

This project necessarily involves porting the [Ibex]
(https://github.com/lowRISC/ibex) core to the IceStorm flow, making sure it
fits and reasonably maps to iCE40 FPGAs. Then adding memory, timer, UART,
SPI (leveraging + adapting existing IP). Finally, creation of the SoC
infrastructure: toolchain, linker script, software libs.

Mentors: [Greg](mailto:gac@lowrisc.org), [Pirmin](mailto:vogelpi@lowrisc.org)

## Open source logic analyser IP for FPGA

**Summary:** Build a [sigrok](https://sigrok.org/) compatible logic analyser
that can be used in FPGA.

FPGA vendors such as Altera and Xilinx have proprietary logic analyser
generators that can be used for FPGA debug. They allow configuration of a wide
number of parameters, such as signal widths, depth of buffering and possible
triggering modes (from a simple edge trigger to more complex conditions
involving multiple signals over several cycles).

Sigrok is an open source software suite for signal analysis, it supports a wide
range of devices. This project would build an open source logic analyser
generator with similar capabilities to existing proprietary solutions that is
compatible with Sigrok. The focus would be on use for FPGA debug but it could
also be used with external IO to produce a 'traditional' logic analyser or be
embedded in an ASIC for post-silicon debug.

By combining the generator with an existing verilog parsing framework a user
friendly front end could be created. This would allow a designer to select the
signals they want to capture and the necessary logic analyser would be
generated with all the required wiring to feed to signals into the analyser.

Mentors: [Greg](mailto:gac@lowrisc.org), [Pirmin](mailto:vogelpi@lowrisc.org),
[Luís](mailto:luismarques@lowrisc.org)

## Proof-of-concept integration of pointer authentication support in Ibex

**Summary:** Extend the processor pipeline of [Ibex]
(https://github.com/lowrisc/ibex) with instructions to generate and
check pointer authentication codes.

[Pointer Authentication]
(https://www.usenix.org/system/files/sec19fall_liljestrand_prepub.pdf) uses
cryptographic message authentication codes (MACs) both generated and
authenticated at runtime to protect the integrity of
pointers in order to aggravate attacks targeting arbitrary code execution
through malicious manipulation of code and data pointers. This project aims
at doing a proof-of-concept integration of pointer authentication
into Ibex.

For this project, the actual MAC is considered a black box of configurable
latency. The focus lies on integrating pointer authentication into the
processor pipeline. To this end, new custom instructions need to be added to
generate and authenticate pointers based on the value of the PC, SP and a
secret key (including exception handling if authentication fails).

Mentors: [Pirmin](mailto:vogelpi@lowrisc.org), [Sam]
(mailto:selliott@lowrisc.org), [Luís](mailto:luismarques@lowrisc.org)

## "Simulated" memory controller

**Summary:** Provide a way to produce realistic performance numbers from FPGA.

It is a common pitfall to misinterpret or incorrectly scale performance
numbers derived from benchmarks run on an FPGA-based SoC design. The problem
is that your external memory interface is running at a very high speed
compared to the core CPU (e.g. a 25MHz core clock speed but external memory
running a several hundred MHz). This can be misleading when trying to consider
what the performance would be on an ASIC, as the CPU clock speed could be many
times higher but the memory frequency be the same or increase by a much
smaller amount. The solution is to have a simulation-ready memory controller
that will produce delays much closer to a system where the memory interface is
running at a much slower speed.

Mentors: [Alex](mailto:asb@lowrisc.org), [Pirmin](mailto:vogelpi@lowrisc.org)