text:
import sys, os, io, yaml, re, functools

# all open() calls have an implied encoding parameter, UTF-8 by default
open = functools.partial(__builtins__.open,
    encoding=os.environ.get("SOURCE_ENCODING", "utf8"))

# some constants to make our lives easier
TAB = "\t"
EOL = "\n"

# regular expression for matching dedent specifier: 1 or 2 digits
DIGITS = re.compile("[0-9][0-9]?")

# returns cached contents of a file if it exists, or reads it into the cache and
# returns it if not.  cache is stored as a default parameter value.
#
# the cache is used only when there are duplicate snippets in two or more source files.
# only one copy of the file is ever cached (the first one that was found) so this shouldn't
# run up memory too much if you don't have many duplicate snippets.
def cached(path, cache={}):
    if path not in cache:
        with open(path) as infile:
            cache[path] = infile.read().rstrip()
    return cache[path]

# a file-like object used to avoid writing duplicate snippets we've already extracted
# in situations where this is not an error
class DummyFile:
    def __init__(self, *args, **kwargs):
        pass
    def write(self, text):
        pass
    def close(self):
        pass

# auto-vivifying dict (like DefaultDict but we don't need to import it)
class AutoDict(dict):
    def __init__(self, T):
        self.T = T
    def __missing__(self, key):
        self[key] = self.T()
        return self[key]

# the class that does the snippet extraction. instantiate it passing the directory to
# which snippets should be extracted.  call the instance with each source file.
class Snipper:

    # initialize Snipper
    def __init__(self, snippetdir):
        self.dir        = snippetdir        # directory where snippets will be extracted
        self.source     = {}                # source file of each snippet
        self.count      = 0                 # number of snippets extracted
        self.errors     = 0                 # processing errors
        self.issues     = AutoDict(set)     # files with issues
        self.index      = AutoDict(list)    # index of snippets to files (this should probably be merged with self.source)
        self.log        = io.StringIO()

    # if used as context manager, we capture the log instead of printing it as we go
    # by switching print() to print to a StringIO object
    def __enter__(self):
        global print
        print = functools.partial(__builtins__.print, file=self.log)
        return self

    def __exit__(self, *args):
        global print
        print = __builtins__.print

    # extract snippets from a single file
    def __call__(self, path, markers):
        print(path)
        self.started    = set()         # snippets we've started in this source file
        self.duplicates = set()         # snippets we've determined are duplicates so we won't append/echo
        tag = re.compile(f" *({'|'.join(markers)}) ?snippet-") # e.g. if ext is "// #" end up with regex: " *(#|//) ?snippet-"
        self.files  = {}                # files currently open to write snippets
        self.dedent = {}                # amount of whitespace to strip from each line of snippet
        self.path = path                # source file we are working with (store it on instance so we can use it in error messages)
        self.markers = markers
        try:
            with open(path) as infile:      # read source file entirely into memory
                self.text = infile.read().rstrip()
        except IOError as ex:
            print("ERROR reading file", ex)
            self.errors += 1
            return
        if TAB in self.text and "snippet-start" in self.text:
            print("    WARNING tab(s) found in %s may cause formatting problems in docs" % path)
        # process each line in source file. self.i is the line we're on (for error messages)
        for self.i, self.line in enumerate(self.text.splitlines(keepends=False), start=1):
            line = self.line            # use a local variable for a bit more performance
            if tag.match(line):         # line is a snippet directive, parse and process it
                self.directive = line.split("snippet-")[1].split(":")[0].rstrip()   # get e.g. append fron snippet-append
                self.arg = line.split("[")[1].split("]")[0].rstrip()                # get e.g. snippet-name from [snippet-name]
                func = getattr(self, self.directive.lstrip("_"), None)
                if func and callable(func):
                    func(self.arg)      # call our method named same as directive (e.g. start(..) for snippet-start)
                else:
                    print("    ERROR invalid directive snippet-%s at %s in %s" % (self.directive, self.i, self.path))
                    self.errors += 1
                    self.issues[path].add("invalid directive snippet-%s" % self.directive)
            else:                       # line is NOT a snippet directive. write it to any open snippet files
                for snip, file in self.files.items():           # for each snippet file we're writing, write the line
                    dedent = self.dedent[snip]
                    if dedent and line[:dedent].strip():        # is the text we want to strip to dedent all whitespace? error if not
                        print(("    ERROR unable to dedent %s space(s) " % dedent) +
                            ("in snippet %s at line %s in %s " % self._where) +
                            f"(only indented {len(line) - len(line.lstrip())} spaces)")
                        self.errors += 1
                    file.write(line[dedent:].rstrip() + EOL)    # write it (strip whitespace at end just to be neat)
        # done processing this file. make sure all snippets had snippet-end tags
        for snip, file in self.files.items():
            print("    ERROR snippet-end tag for %s missing in %s, extracted to end of file" % (snip, path))
            file.close()
            self.issues[path].add("snippet-end tag for %s missing" % snip)
            self.errors += 1

    # directive: beginning of snippet
    def start(self, arg):
        path = os.path.join(self.dir, f"{arg}.txt")
        indicator = "EXTRACT"
        opener = open
        printer = print
        if arg in self.files:
            printer = lambda *a: print("    ERROR snippet %s already open at line %s in %s" % self._where)
            self.issues[self.path].add("snippet %s opened multiple times")
            self.errors += 1
        elif os.path.isfile(path):
            # if snippet output already exists, this is OK only if it source file has the same name and identical content
            if self.path != self.source[arg] and self.path.rpartition("/")[2] == self.source[arg].rpartition("/")[2] and self.text == cached(self.source[arg]):
                printer = lambda *a: print("WARNING redundant snippet %s at line %s in %s" % self._where)
                self.duplicates.add(arg)
            else:
                printer = lambda *a: print("    ERROR duplicate snippet %s at line %s in %s" % self._where,
                    "(also in %s)" % self.source[arg])
                pfxlen = len(os.path.commonprefix([self.path, self.source[arg]]))
                path1 = self.source[arg][pfxlen:]
                if "/" not in path1: path1 = self.source[arg]
                path2 = self.path[pfxlen:]
                if "/" not in path2: path2 = self.path
                self.issues[self.path].add("%s also declared in %s" % (arg, path1))
                self.issues[self.source[arg]].add("%s also declared in %s" % (arg, path2))
                self.errors += 1
            opener = DummyFile      # don't write to the file, but still track it so we can detect missing snippet-end
        else:
            self.count += 1
        # parse number at end of line as dedent value
        self.dedent[arg] = int(DIGITS.search(self.line.rpartition("]")[2] + " 0").group(0))
        self.files[arg] = opener(path, "w")     # open real file or dummy
        self.index[arg].append(self.path)
        self.started.add(arg)       # record that we started this snippet in this source file
        if arg not in self.source:  # record that we *first* saw this snippet in this source file
            self.source[arg] = self.path
        printer("   ", indicator, arg)

    # directive: append to given file (for extracting multiple chunks of code to a single snippet)
    def append(self, arg):
        if arg in self.files:           # is the file already open?
            print("    ERROR snippet %s already open at line %s in %s" % self._where)
            self.issues[self,path].add("snippet %s opened multiple times" % arg)
            self.errors += 1
            return
        if arg not in self.started:     # did we start this snippet in current source file?
            print("    ERROR snippet file %s not found at line %s in %s" % self._where)
            self.issues[self.path].add("snippet %s doesn't exist" % arg)
            self.errors += 1
            return
        self.files[arg] = DummyFile() if arg in self.duplicates else open(os.path.join(self.dir, arg) + ".txt", "a")
        print("    APPEND", arg)

    # directive: end of snippet
    def end(self, arg):
        if arg in self.files:
            self.files[arg].close()
            del self.files[arg]
        else:
            print("    ERROR snippet file %s not open at %s in %s" % self._where)
            self.issues[self.path].add("snippet-end tag for %s which is not open" % arg)
            self.errors += 1

    # directive: insert arg verbatim as a line into all currently open snippets
    # useful for e.g. adding closing brackets to partial code block (could also use append for that)
    def echo(self, arg):
        arg = arg.rstrip() + EOL
        if self.files:
            for file in self.files.values():
                file.write(arg)
        else:
            print("    ERROR echo '%s' outside snippet at %s in %s" % self._where)
            self.issues[self.path].add("echo outside snippet")
            self.errors += 1

    # do-nothing handler used for directives that we ignore
    def _nop(self, arg): return

    # the aforementioned ignored directives
    service = comment = keyword = sourceauthor = sourcedate = sourcedescription = sourcetype = sourcesyntax = _nop

    # convenience property for returning error location tuple (used in error messages)
    @property
    def _where(self):
        return self.arg, self.i, self.path

def err_exit(msg):
    print("ERROR", msg)
    sys.exit(1)

# ----------------------------------------------------------------------------

if __name__ == "__main__":

    # read list of filenames from stdin first, so we don't get broken pipe if we error out
    stdin_lines = []
    if not sys.stdin.isatty():
        stdin_lines = sys.stdin.readlines()

    # get output directory from command line, or error
    if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
        snippetdir = sys.argv[1]
    else:
        err_exit("snippet output directory not passed or does not exist")

    # get filename of extersions list from command line, or use default, then load it
    if len(sys.argv) > 2:
        commentfile = sys.argv[2]
    else:
        commentfile = "snippet-extensions.yml"

    # reports to be printed can be passed in via environment variable REPORTS
    # if this value is not set, print all reports
    reports = os.environ.get("REPORTS", "log issues index").lower().split()

    # if no directory specified, file is in same directory as script
    if "/" not in commentfile and "\\" not in commentfile:
        commentfile = os.path.join(os.path.dirname(__file__), commentfile)
    if not os.path.isfile(commentfile):
        err_exit("source file extension map %s not found" % commentfile)
    with open(commentfile) as comments:
        MAP_EXT_MARKER = yaml.safe_load(comments)
        if not isinstance(MAP_EXT_MARKER, dict):
            err_exit("source map is not a key-value store (dictionary)")
        for k, v in MAP_EXT_MARKER.items():
            if isinstance(k, str) and isinstance(v, str):
                MAP_EXT_MARKER[k] = v.split()
            else:
                err_exit("key, value must both be strings; got %s, %s (%s, %s)" %
                    (k, v, type(k).__name__, type(v).__name__))

    print("==== extracting snippets in source files",
        " ".join(ex for ex in MAP_EXT_MARKER if ex and MAP_EXT_MARKER[ex]), "\n")
    print("reports:", " ".join(reports).upper(), end="\n\n")

    # initialize snipper instance and our counters
    with Snipper(snippetdir) as snipper:
        seen = processed = 0

        # main loop: for each file named on stdin, check to see if we should process it, and if so, do so
        for path in sorted(stdin_lines):
            path = path.strip()
            if not path:                                    # skip blank lines in input
                continue
            # make sure relative path starts with ./ so that e.g. /Makefile in the extensions map
            # can be used to match an entire filename.
            if not (path.startswith(("./", "/", "\\")) or   # already relative or Linux/Mac absolute path or UNC path
                (path[0].isalpha() and path[1] == ":")):    # already Windows absolute path
                    path = "./" + path
            if "/." in path or "\\." in path:               # skip hidden file or directory
                continue
            seen += 1                                       # count files seen (not hidden)
            # find first extension from extension map that matches current file
            # replace backslashes with forward slashes for purposes of matching so it works with Windows or UNC paths
            ext = next((ext for ext in MAP_EXT_MARKER if path.replace("\\", "/").endswith(ext)), None)
            markers = MAP_EXT_MARKER.get(ext, ())
            if markers:                                     # process it if we know its comment markers
                snipper(path, markers)
                processed += 1

    # files with issues report (files with most issues first)
    if "issues" in reports:
        if snipper.issues:
            print("====", len(snipper.issues), "file(s) with issues:", end="\n\n")
            for issue, details in sorted(snipper.issues.items(), key=lambda item: -len(item[1])):
                print(issue, end="\n     ")
                print(*sorted(details), sep="\n     ", end="\n\n")
        else:
            print("---- no issues found\n")

    # snippet index report (snippets that appear in the most files first)
    if "index" in reports:
        if snipper.index:
            print("====", len(snipper.index), "snippet(s) extracted from", processed, "files:", end="\n\n")
            for snippet, files in sorted(snipper.index.items(), key=lambda item: -len(item[1])):
                print(snippet, "declared in:", end="\n     ")
                print(*sorted(files), sep="\n     ", end="\n\n")
        else:
            print("--- no snippets were extracted\n")

    # print log
    if "log" in reports:
        print("==== Complete processing log\n")
        if processed:
            print(snipper.log.getvalue(), end="\n\n")
        else:
            print("No files were processed\n")

    # print summary
    print("====", snipper.count, "snippet(s) extracted from", processed,
        "source file(s) processed of", seen, "candidate(s) with", snipper.errors,
        "error(s) in", len(snipper.issues), "file(s)\n")

    # exit with nonzero status if we found any errors, so caller won't commit the snippets
    sys.exit(snipper.errors > 0)


text:
class Brain
{
  public:
    // TK Support for soft serials. A more generic "Serial" type to inherit from would be great.
    // More info on passing Serial objects: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1264179436
    Brain(HardwareSerial &_brainSerial);

    // Run this in the main loop.
    boolean update();

    // String with most recent error.
    char* readErrors();

    // Returns comme-delimited string of all available brain data.
    // Sequence is as below.
    char* readCSV();

    // Individual pieces of brain data.
    byte readSignalQuality();
    byte readAttention();
    byte readMeditation();
    unsigned long* readPowerArray();
    unsigned long readDelta();
    unsigned long readTheta();
    unsigned long readLowAlpha();
    unsigned long readHighAlpha();
    unsigned long readLowBeta();
    unsigned long readHighBeta();
    unsigned long readLowGamma();
    unsigned long readMidGamma();

  private:
    HardwareSerial* brainSerial;
    byte packetData[MAX_PACKET_LENGTH];
    boolean inPacket;
    byte latestByte;
    byte lastByte;
    byte packetIndex;
    byte packetLength;
    byte checksum;
    byte checksumAccumulator;
    byte eegPowerLength;
    boolean hasPower;
    void clearPacket();
    void clearEegPower();
    boolean parsePacket();
    void printPacket();
    void init();
    void printCSV(); // maybe should be public?
    void printDebug();

    // With current hardware, at most we would have...
    // 3 x 3 char bytes
    // 8 x 10 char ulongs
    // 10 x 1 char commas
    // 1 x 1 char 0 (string termination)
    // -------------------------
    // 100 characters
    char csvBuffer[100];

    // Longest error is
    // 22 x 1 char bytes
    // 1 x 1 char 0 (string termination)
    char latestError[23];

    byte signalQuality;
    byte attention;
    byte meditation;

    boolean freshPacket;

    // Lighter to just make this public, instead of using the getter?
    unsigned long eegPower[EEG_POWER_BANDS];
};

#endif

redpajama_set_name: RedPajamaGithub


text:
using namespace muduo;
using namespace muduo::net;

DiscardServer::DiscardServer(EventLoop* loop,
                             const InetAddress& listenAddr)
  : server_(loop, listenAddr, "DiscardServer")
{
  server_.setConnectionCallback(
      boost::bind(&DiscardServer::onConnection, this, _1));
  server_.setMessageCallback(
      boost::bind(&DiscardServer::onMessage, this, _1, _2, _3));
}

void DiscardServer::start()
{
  server_.start();
}

void DiscardServer::onConnection(const TcpConnectionPtr& conn)
{
  LOG_INFO << "DiscardServer - " << conn->peerAddress().toIpPort() << " -> "
           << conn->localAddress().toIpPort() << " is "
           << (conn->connected() ? "UP" : "DOWN");
}

void DiscardServer::onMessage(const TcpConnectionPtr& conn,
                              Buffer* buf,
                              Timestamp time)
{
  string msg(buf->retrieveAllAsString());
  LOG_INFO << conn->name() << " discards " << msg.size()
           << " bytes received at " << time.toString();
}


text:
<?php
/**
 * Load User data for demo purpose
 * @authors Leonard LEPADATU (lepadatu.leonard-ext@groupehn.com)
 * @date    2015-06-03 09:46:33
 * @version $Id$
 */

namespace Mark\LoginBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Mark\LoginBundle\Entity\Users;

class LoadUsersData implements FixtureInterface
{
	/**
	 * {@inheritDoc}
	 * 0_ROLE_USER; 1_ROLE_ADMIN; 2_ROLE_SUPER_ADMIN
	 */
	public function load(ObjectManager $em)
	{

		// Leonard
		$user = new Users;
		$user->setFirstname('Leonard');
		$user->setLastname('Lepadatu');
		$user->setUsername('leo');
		$user->setEmail('leonardlepadatu@yahoo.com');
		$user->setPassword('leo');
		$user->setIsActive(1);
		$user->setUserRole(2); //
		$user->setLocale("ro");
		$user->setUserParam("");

		$em->persist($user);

	// Tiberiu
		$user = new Users;
		$user->setFirstname('Tiberiu');
		$user->setLastname('Lepadatu');
		$user->setUsername('tibi');
		$user->setEmail('tiberiulepadatu@yahoo.com');
		$user->setPassword('tibi');
		$user->setIsActive(1);
		$user->setUserRole(1); //
		$user->setLocale("en");
		$user->setUserParam("");

		$em->persist($user);

	// Luca
		$user = new Users;
		$user->setFirstname('Luca');
		$user->setLastname('Lepadatu');
		$user->setUsername('luca');
		$user->setEmail('lucalepadatu@yahoo.com');
		$user->setPassword('luca');
		$user->setIsActive(1);
		$user->setUserRole(0); //
		$user->setLocale("fr");
		$user->setUserParam("");

		$em->persist($user);

		$em->flush();
		$em->clear();
	}

}


text:
package org.apache.kafka.connect.health;

import java.util.Objects;

/**
 * Describes the state, IDs, and any errors of a connector task.
 */
public class TaskState extends AbstractState {

    private final int taskId;

    /**
     * Provides an instance of {@link TaskState}.
     *
     * @param taskId   the id associated with the connector task
     * @param state    the status of the task, may not be {@code null} or empty
     * @param workerId id of the worker the task is associated with, may not be {@code null} or empty
     * @param trace    error message if that task had failed or errored out, may be {@code null} or empty
     */
    public TaskState(int taskId, String state, String workerId, String trace) {
        super(state, workerId, trace);
        this.taskId = taskId;
    }

    /**
     * Provides the ID of the task.
     *
     * @return the task ID
     */
    public int taskId() {
        return taskId;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;
        if (!super.equals(o))
            return false;
        TaskState taskState = (TaskState) o;
        return taskId == taskState.taskId;
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), taskId);
    }

    @Override
    public String toString() {
        return "TaskState{"
            + "taskId='" + taskId + '\''
            + "state='" + state() + '\''
            + ", traceMessage='" + traceMessage() + '\''
            + ", workerId='" + workerId() + '\''
            + '}';
    }
}


text:
<?php

if ( ! defined('BASEPATH'))
	exit('No direct script access allowed');

/**
 * Miscelaneous file functions.
 *
 * @package CarbonCopy
 * @subpackage file
 * @author porquero
 *
 * @deprecated All these function are helper now! Please see cc_helper.php
 */
class misc extends MX_Controller {

	/**
	 * Return path with final slash, if hasn't
	 *
	 * @param string $context
	 * @return string
	 */
	public function final_slash($context)
	{
		return preg_match("/\/$/", $context) ? $context : $context . '/';
	}

	/**
	 * Slug path for use url string
	 *
	 * @param string $context
	 * @return string
	 *
	 * @deprecated Replaced with helper slug_path!
	 */
	public function slug_path($context)
	{
		return preg_replace('/\//', '_', $context);
	}

	/**
	 * Unslug path converting in file system.
	 *
	 * @param type $context
	 * @return type
	 */
	public function unslug($context)
	{
		return preg_replace('/\_/', '/', $context);
	}

	/**
	 * Unslug path for use in timeline
	 *
	 * @param type $context
	 * @return type
	 */
	public function unslug_for_timeline($context)
	{
		return '[' . preg_replace('/\_/', '][', $context) . ']';
	}

}


text:
package nl.rakis.fs.auth;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class PasswordFile extends SecurityFile {

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

    public static final int NUM_FIELDS = 7;
    public static final String FLDNAME_USERNAME = "Username";
    public static final int FLD_USERNAME = 0;
    public static final String FLDNAME_PASSWORD = "Password";
    public static final int FLD_PASSWORD = 1;
    public static final String FLDNAME_USERID = "User ID";
    public static final int FLD_USERID = 2;
    public static final String FLDNAME_GROUPID = "Group ID";
    public static final int FLD_GROUPID = 3;
    public static final String FLDNAME_REALNAME = "Real name";
    public static final int FLD_REALNAME = 4;
    public static final String FLDNAME_HOME = "Home directory";
    public static final int FLD_HOME = 5;
    public static final String FLDNAME_SHELL = "Shell";
    public static final int FLD_SHELL = 6;

    private File path;
    private HashMap<String,User> users = new HashMap<>();

    public PasswordFile(String path)
    {
        log.debug("PasswordFile(\"" + path + "\")");

        this.path = new File(path);
    }

    public PasswordFile(File path)
    {
        log.debug("PasswordFile(\"" + path.getAbsolutePath() + ")");

        this.path = path;
    }

    private void load() {
        if (log.isDebugEnabled()) {
            log.debug("load()");
        }

        load(path, (String line) -> {
            boolean result = false;

            try {
                String[] pwdFields = line.split(":");
                if (pwdFields.length != NUM_FIELDS) {
                        throw new IOException("Bad passwd format: \"" + line + "\"");
                }
                User user = new User();

                checkNonEmpty(FLDNAME_USERNAME, pwdFields [FLD_USERNAME]);
                user.userName = pwdFields [FLD_USERNAME];
                checkEmpty(FLDNAME_PASSWORD, pwdFields [FLD_PASSWORD]);
                checkEmpty(FLDNAME_USERID, pwdFields [FLD_USERID]);
                checkEmpty(FLDNAME_GROUPID, pwdFields [FLD_GROUPID]);
                checkNonEmpty(FLDNAME_REALNAME, pwdFields [FLD_REALNAME]);
                user.longName = pwdFields [FLD_REALNAME];
                checkNonEmpty(FLDNAME_HOME, pwdFields [FLD_HOME]);
                user.defaultSession = pwdFields [FLD_HOME];
                checkEmpty(FLDNAME_SHELL, pwdFields [FLD_SHELL]);

                if (log.isDebugEnabled()) {
                    log.debug("load(): Adding user \"" + user.userName + "\"");
                }
                users.put(user.userName, user);
            }
            catch (IOException e) {
                log.error("load(): Exception while loading \"" + path + "\"", e);
                result = true;
                users.clear();
            }
            return result;
        });
        if (log.isDebugEnabled()) {
            log.debug("load(): " + users.size() + " user(s) read");
        }
    }

    private boolean store() {
        return store("users", path, (PrintWriter pr) -> {
            for (User user: users.values()) {
                pr.print(user.userName);
                pr.print(":x:x:x:");
                pr.print(user.longName);
                pr.print(":");
                pr.print(user.defaultSession);
                pr.println(":x");
            }
        });
    }

    public Map<String,User> getUsers() {
        load();
        return users;
    }

    public User getUser(String userId) {
        return getUsers().containsKey(userId) ? users.get(userId) : null;
    }

    public boolean addUser(String userName, String longName, String defaultSession) {
        if (log.isInfoEnabled()) {
            log.info("addUser(): Adding user \"" + userName + "\", real name \"" + longName + "\", default session \"" + defaultSession + "\"");
        }

        boolean result = false;

        if (getUser(userName) != null) {
            log.error("addUser(): Tried to add an existing user \"" + userName + "\"");
        }
        else {
            User user = new User(userName, longName, defaultSession);
            users.put(userName, user);
            result = store();
        }
        if (log.isInfoEnabled()) {
            log.info("addUser(): " + (result ? "Success" : "Failed"));
        }
        return result;
    }

    public boolean removeUser(String userName) {
        if (log.isInfoEnabled()) {
            log.info("removeUser(): Removing user \"" + userName + "\"");
        }

        boolean result = false;

        if (getUser(userName) == null) {
            log.error("removeUser(): Tried to remove a non-existing user \"" + userName + "\"");
        }
        else {
            users.remove(userName);
            result = store();
        }
        if (log.isInfoEnabled()) {
            log.info("removeUser(): " + (result ? "Success" : "Failed"));
        }
        return result;
    }
}


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

/**
 * @fileoverview The current spec of the Media Session API.
 * @see https://wicg.github.io/mediasession/
 * @externs
 */

/**
 * @see https://wicg.github.io/mediasession/#the-mediaimage-dictionary
 * @record
 * @struct
 */
function MediaImage() {}

/** @type {string} */
MediaImage.prototype.src;

/** @type {(string|undefined)} */
MediaImage.prototype.sizes;

/** @type {(string|undefined)} */
MediaImage.prototype.type;

/**
 * A MediaMetadata object is a representation of the metadata associated with a
 * MediaSession that can be used by user agents to provide customized user
 * interface.
 * @see https://wicg.github.io/mediasession/#the-mediametadata-interface
 * @constructor
 * @param {?MediaMetadataInit} init
 */
function MediaMetadata(init) {}

/** @type {string} */
MediaMetadata.prototype.album;

/** @type {string} */
MediaMetadata.prototype.artist;

/** @type {!Array<!MediaImage>} */
MediaMetadata.prototype.artwork;

/** @type {string} */
MediaMetadata.prototype.title;

/**
 * @see https://wicg.github.io/mediasession/#the-mediametadata-interface
 * @record
 * @struct
 */
function MediaMetadataInit() {}

/** @type {(string|undefined)} */
MediaMetadataInit.prototype.album;

/** @type {(string|undefined)} */
MediaMetadataInit.prototype.artist;

/** @type {(!Array<!MediaImage>|undefined)} */
MediaMetadataInit.prototype.artwork;

/** @type {(string|undefined)} */
MediaMetadataInit.prototype.title;

/**
 * A MediaSession objects represents a media session for a given document and
 * allows a document to communicate to the user agent some information about the
 * playback and how to handle it.
 * @see https://wicg.github.io/mediasession/#the-mediasession-interface
 * @interface
 * @struct
 */
function MediaSession() {}

/** @type {?MediaMetadata} */
MediaSession.prototype.metadata;

/** @type {string} */
MediaSession.prototype.playbackState;

/** @type {function(string, ?function())} */
MediaSession.prototype.setActionHandler;

/** @type {?MediaSession} */
Navigator.prototype.mediaSession;


text:
using Cake.Common.Build.Jenkins;
using Cake.Core;
using NSubstitute;

namespace Cake.Common.Tests.Fixtures.Build
{
    internal sealed class JenkinsFixture
    {
        public ICakeEnvironment Environment { get; set; }

        public JenkinsFixture()
        {
            Environment = Substitute.For<ICakeEnvironment>();
            Environment.WorkingDirectory.Returns("C:\\build\\CAKE-CAKE-JOB1");
        }

        public void IsRunningOnJenkins()
        {
            Environment.GetEnvironmentVariable("JENKINS_URL").Returns("http://localhost:8080/view/All/builds");
        }

        public JenkinsProvider CreateJenkinsProvider()
        {
            return new JenkinsProvider(Environment);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  #%L
  kylo-service-app
  %%
  Copyright (C) 2017 ThinkBig Analytics
  %%
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  #L%
  -->

<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.4.xsd">

  <include file="kylo_alert_add_audit_columns.xml" relativeToChangelogFile="true"/>
  <include file="sla-email-templates.xml" relativeToChangelogFile="true"/>
  <include file="nifi-feed-processor-stats-drop-min-event-time-millis-column.xml" relativeToChangelogFile="true"/>
  <include file="nifi-feed-processor-stats-remove-constraints.xml" relativeToChangelogFile="true"/>
  <!--  procedure to compact the stats -->
  <include file="mysql_nifi_feed_processor_stats_compact.xml" relativeToChangelogFile="true" />
  <include file="postgres_nifi_feed_processor_stats_compact.xml" relativeToChangelogFile="true" />
  <include file="mssql_nifi_feed_processor_stats_compact.xml" relativeToChangelogFile="true"/>

  <include file="update_batch_nifi_job_indexes.xml" relativeToChangelogFile="true"/>
  <include file="ensure_nifi_feed_stats_data.xml" relativeToChangelogFile="true"/>

  <!-- mssql needs alerts content as varchar(max) not text -->
  <include file="mssql_alter_kylo_alerts_data_type.xml" relativeToChangelogFile="true"/>

</databaseChangeLog>


text:
import LFPy
import numpy as np
import matplotlib.pylab as pl
import sys
import os
import random as random

#setting a random seed to get the same result all the time
np.random.seed(1988)
#what this program need fro running
#where is and will be the data
f2 = open('cellname', 'r')
celln = [line.strip() for line in f2]
cellname = celln[0]
f2.close()
os.chdir(cellname)
#morphology
#sigma
#electrode coordinates
#morphology
f3 = open('morphology.txt', 'r')
morph = [line.strip() for line in f3]
morpho = morph[0]
f3.close()
#active channel description
f4 = open('active.txt', 'r')
actw = [line.strip() for line in f4]
activewhere = actw[0]
f4.close()

#electrode coordinates
felec = open('elcoord_x_y_z', 'r')
elec = [line.strip() for line in felec]
felec.close()
elc=np.hstack((elec))
elcor=elc.reshape(3,-1)
#tissue properties
f1 = open('elprop', 'r')
elp = [line.strip() for line in f1]
sigma =float(elp[1])
f1.close()
######################x
#synaptic inputs

def stationary_poisson(nsyn,lambd,tstart,tstop):
    ''' Generates nsyn stationary possion processes with rate lambda between tstart and tstop'''
    interval_s = (tstop-tstart)*.001
    spiketimes = []
    for i in xrange(nsyn):
        spikecount = np.random.poisson(interval_s*lambd)
        spikevec = np.empty(spikecount)
        if spikecount==0:
            spiketimes.append(spikevec)
        else:
            spikevec = tstart + (tstop-tstart)*np.random.random(spikecount)
            spiketimes.append(np.sort(spikevec)) #sort them too!

    return spiketimes

###############
cell_parameters = {

	'morphology' : morpho ,
	'Ra': 123,
        'tstartms' : 0.,                 # start time of simulation, recorders start at t=0
        'tstopms' : 70.,                   # stop simulation at 200 ms.
	'passive' : True,
    	'v_init' : -65,             # initial crossmembrane potential
    	'e_pas' : -65,              # reversal potential passive mechs
	'nsegs_method' :  'fixed_length',
	'max_nsegs_length':10,
#	'lambda_f' : 1000,           # segments are isopotential at this frequency
    'custom_code'  : [activewhere], # will run this file
}

#electrode coordinates
x=elcor[0,]
x= x.astype('Float64')
y=elcor[1,]
y= y.astype('Float64')
z=elcor[2,]
z= z.astype('Float64')

#	y = pl.zeros(X.size)

#define parameters for extracellular recording electrode, using optional method
electrodeParameters = {
    'sigma' : sigma,              # extracellular conductivity
    'x' : x,        # x,y,z-coordinates of contact points
    'y' : y,
    'z' : z,
#     'method' : 'som_as_point',  #treat soma segment as sphere source
#     'method' : 'pointsource'
     'method' : 'linesource'
}

#pointprocess= {
#        'idx' : 40,
#        'record_current' : True,
#        'pptype' : 'IClamp',
#        'amp' : 0.05,
#        #'amp' : 0.2,
#        'dur' : 30,
#        'delay' : 15
#    }

##create extracellular electrode object
electrode = LFPy.RecExtElectrode(**electrodeParameters)

simulationParameters = {
	'electrode' : electrode,
	'rec_imem' : True,  # Record Membrane currents during simulation
	'rec_isyn' : True,  # Record synaptic currents
}

#Initialize cell instance, using the LFPy.Cell class
cell = LFPy.Cell(**cell_parameters)

#rotating the cell
#rotation = {'x' : np.pi/2, 'y' : 0, 'z' : 0}
#cell.set_rotation(**rotation)

#set the position of midpoint in soma to Origo (not needed, this is the default)
#Why I am doing this? #That might modifies the plots and the setups!!!!!!!!!!!!!!44
cell.set_pos(xpos = LFPy.cell.neuron.h.x3d(0) , ypos = LFPy.cell.neuron.h.y3d(0) , zpos = LFPy.cell.neuron.h.z3d(0))
#cell.set_pos(xpos = xpontok[1], ypos = ypontok[1], zpos = zpontok[1])

#Synaptic inputs

	    # Define synapse parameters
synapse_parameters = {
      'idx' : cell.get_closest_idx(x=100., y=0., z=500.), #100 0.00 500
      'e' : 0.,                   # reversal potential
      'syntype' : 'ExpSyn',       # synapse type
      #'tau' : 10.,                # syn. time constant
	'tau' : 2.,
#      'weight' : .001,            # syn. weight
      'weight' : .04,            # syn. weight
      'record_current' : True,
}

synapse_parameters2 = {
  'idx' : cell.get_closest_idx(x=-100., y=0., z=400.), #100 0.00 500
      'e' : 0.,                   # reversal potential
      'syntype' : 'ExpSyn',       # synapse type
      #'tau' : 10.,                # syn. time constant
	'tau' : 2.,
#      'weight' : .001,            # syn. weight
      'weight' : .03,            # syn. weight
      'record_current' : True,
}

synapse_parameters3 = {
      'idx' : cell.get_closest_idx(x=40., y=0., z=200.), #100 0.00 500
      'e' : 0.,                   # reversal potential
      'syntype' : 'ExpSyn',       # synapse type
      #'tau' : 10.,                # syn. time constant
	'tau' : 2.,
#      'weight' : .001,            # syn. weight
      'weight' : .04,            # syn. weight
      'record_current' : True,
}

############################################x
# Define synapse parameters
synapse_parameters_random = {
    'idx' : 0, # to be set later
    'e' : 0.,                   # reversal potential
    'syntype' : 'ExpSyn',       # synapse type
    'tau' : 2.,                 # syn. time constant
    'weight' : .01,            # syn. weight
    'record_current' : True,
}

#synaptic spike times
n_pre_syn = 1000
pre_syn_sptimes = stationary_poisson(nsyn=n_pre_syn, lambd=2, tstart=0, tstop=70)#70)

#assign spike times to different units
n_synapses = 100

# Create synapse and set time of synaptic input
pre_syn_pick = np.random.permutation(np.arange(n_pre_syn))[0:n_synapses]

for i_syn in xrange(n_synapses):
    syn_idx = int(cell.get_rand_idx_area_norm())
    synapse_parameters_random.update({'idx' : syn_idx})
    synapse = LFPy.Synapse(cell, **synapse_parameters_random)
    synapse.set_spike_times(pre_syn_sptimes[pre_syn_pick[i_syn]])
##############################################################

# Create synapse and set time of synaptic input
#synapse = LFPy.Synapse(cell, **synapse_parameters)
#synapse2 = LFPy.Synapse(cell, **synapse_parameters2)
#synapse3 = LFPy.Synapse(cell, **synapse_parameters3)
#insert_synapses(synapse_parameters_2, **insert_synapses_2)
#synapse.set_spike_times(np.array([5.,25., 44.]))
#synapse2.set_spike_times(np.array([15.,20., 40.]))
#synapse3.set_spike_times(np.array([10.,33.]))

#stimulus = LFPy.StimIntElectrode(cell, **pointprocess)

#perform NEURON simulation, results saved as attributes in the cell instance
cell.simulate(**simulationParameters)

np.savetxt( 'membcurr',cell.imem)
np.savetxt( 'myLFP', electrode.LFP)

np.savetxt( 'somav.txt', cell.somav)

coords = np.hstack(
	(cell.xmid, cell.ymid, cell.zmid)
)

np.savetxt( 'coordsmid_x_y_z',coords)

#coordinates of the segment's beginning
coordsstart = np.hstack(
	(cell.xstart, cell.ystart, cell.zstart)
)

np.savetxt( 'coordsstart_x_y_z',coordsstart)

#coordinates of the segment's end
coordsend = np.hstack(
	(cell.xend, cell.yend, cell.zend)
)

np.savetxt( 'coordsend_x_y_z',coordsend)

#sdiameter of the segments
segdiam = np.hstack(
	(cell.diam)
)

np.savetxt( 'segdiam_x_y_z',segdiam)

##########x
#elec = np.hstack(
#	(electrode.x, electrode.y, electrode.z)
#)

#np.savetxt(outname,' + 'elcoord_x_y_z',elec)

#length of segments
np.savetxt( 'seglength',cell.length)
#time in the simulation
np.savetxt( 'time',cell.tvec)

#lets write to file the simulation locations

np.savetxt( 'synapse_locations',pre_syn_pick)

#elprop=np.hstack((d,electrode.sigma))
#np.savetxt( 'elprop',electrode.sigma)
# Plotting of simulation results:

################################x

#LFPy.cell.neuron.h...
#h = LFPy.cell.neuron.h
#hossz=len(cell.allsecnames)
#f4 = open(outname,' + '/segcoords/branchnum', 'w')
#f4.write(str(hossz))
#f4.close()
#b=0
#for x in cell.allseclist:
#	b=b+1
#	xc=list()
#	yc=list()
#	zc=list()
#	for i in range(int(h.n3d())):
 #               #print h.x3d(i)
#		xc.append(h.x3d(i))
#		yc.append(h.y3d(i))
#		zc.append(h.z3d(i))
#	np.savetxt(outname,' + '/segcoords/segcord'+str(b),np.hstack((xc,yc,zc)))


text:
package org.jboss.weld.tests.interceptors.tb;

import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;

/**
 * @author Ales Justin
 */
@Dependent
public class Filter {
    private CDAO cdao;

    public void save(Client c) {
        cdao.save(c);
    }

    public Client verify() {
        return cdao.find(123L);
    }

    public Client check() {
        return cdao.checkClient(123L);
    }

    @Inject
    public void setCdao(CDAO cdao) {
        this.cdao = cdao;
    }
}


text:
module SchemaToYaml
  module Settings
    class Config
      class << self
        def configure
          yield self
        end

        def settings_file
          @settings_file ||= :schema_to_yaml
        end
        attr_writer :settings_file
      end
    end
  end
end


text:
Design Document

Project Definition

The scope of this project is to create an application to help with the
grading and testing of the 100 level classes at Western Washington University.
Features will include running student programs against a script, checking for
differences. It will also check for coding style, among other optional
parameters.

Why?

The 100 level classes are much larger than classes further in the major and
thus get backed up with returning homework and tests because of the lack of
time available by graders and teachers to spend on grading and testing student
code.

The Problem

This application would address the problem of slow grading, and also give
students a clearer understanding of what their code needs to do, and why.

Project Goals

Our goals are to provide a web application that will drastically cut down the
time needed for grading programs and give the students test scripts to give
them peace of mind when turning an assignment in, and provide a clear outline
of what's expected of them.

Requirements

Important

Saveable template per assignment

Upload input script to feed student's program

Upload output (key) script to test against student's program's output

Upload instructor's compilation files

Diff student's code with professor's

Show program's output

Option to type additional input in

Compilation errors/notes

Optionally check for indentation

Would Be Nice

Source code highlighting

Resizable frames in window

Student view (different permissions)

Stored on web server

Be able to grade all students simultaneously

Not Important

Accommodating higher level classes

Checking for comments in code

Test for function return value

Checking whether variable names are descriptive

Use Cases

Input Program Parameters / Specifications

Actor: Instructor

Description: Create a template to specify what to look for in the student's
    program. Upload scripts to run, files to compile with, etc.

Test Program

Actors: Grader and/or Student

Description: Compile and run program, generating output in the program's view.
    Also allow for additional input by the user to run the program step-by-step if
    necessary. Output includes compilation errors and warnings, program output, and
    code review.

Possible Solutions

Identify any existing software that may exist to solve these problems, and the
benefits and disadvantages of each. There exists plenty of opportunity to use
tools that have already been written, such as the ability to compile student
programs from our program, syntax highlighting, and diffing tools.

Plan

Development and Implementation Deadlines

Design deadline: Spring 2013 --> DEADLINE MET

Implementation deadline: Fall 2013 --> ONGOING

Design

The mockups are now obsolete as the design has changed significantly. The web
app is based on the mockups but very loosely.

Development

Track development decisions and milestones.

Chose "difflib" as our diffing library. It is built into Python.

Chose to make this a web app using a JavaScript-heavy frontend and a Python backend.

Integration and Testing

Document usability testing methods and results.

Assumptions

        Students will be using one of the following languages:

Python

Java

C

C++

Use for 100-level classes only

All required files are in the same directory


text:
using System;

namespace RESTyard.AspNetCore.WebApi.AttributedRoutes
{
    public class HttpPostHypermediaAction : HttpMethodHypermediaAction
    {
        /// <inheritdoc />
        public HttpPostHypermediaAction(Type routeType, Type routeKeyProducerType = null) : base(
            new[] {Microsoft.AspNetCore.Http.HttpMethods.Post}, routeType, routeKeyProducerType)
        {
        }

        /// <inheritdoc />
        public HttpPostHypermediaAction(string template, Type routeType, Type routeKeyProducerType = null) : base(
            new[] {Microsoft.AspNetCore.Http.HttpMethods.Post}, template, routeType, routeKeyProducerType)
        {
        }
    }
}


text:
package fi.csc.microarray.client.visualisation.methods.gbrowser.gui;

import java.net.URL;

public class GenomeInfo {

	private String species;
	private String version;
	private URL ensemblBrowserUrl;
	private URL ucscBrowserUrl;
	private String sortId;

	public String getSpecies() {
		return species;
	}

	public void setSpecies(String species) {
		this.species = species;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public URL getEnsembl() {
		return ensemblBrowserUrl;
	}

	public void setEnsemblBrowserUrl(URL ensemblBrowserUrl) {
		this.ensemblBrowserUrl = ensemblBrowserUrl;
	}

	public URL getBrowserUrl() {
		return ucscBrowserUrl;
	}

	public void setUcscBrowserUrl(URL ucscBrowserUrl) {
		this.ucscBrowserUrl = ucscBrowserUrl;
	}

	public String getSortId() {
		return sortId;
	}

	public void setSortId(String sortId) {
		this.sortId = sortId;
	}
}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Auth extends Controller_Admin_Template
{
    public function action_auth()
    {
        $this->template->content_only = true;
        $this->template->content = View::factory("{$this->folder}/{$this->layout}/auth");
    }

    public function action_login()
    {
        $user = $this->request->post();

        if (Auth::instance()->login($user["login"], $user["password"])) {
            Session::instance()->delete('error');
            return $this->redirectToMain();
        }
        Session::instance()->set('error', 'Auth failed');
        return $this->redirectToAuth();
    }

    public function action_logout()
    {
        if (Auth::instance()->logout()) {
            return $this->redirectToAuth();
        }
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>perfect-scrollbar example</title>
    <link href="../dist/css/perfect-scrollbar.css" rel="stylesheet">

Default; wheelSpeed:1

Fast: wheelSpeed:10

Slow: wheelSpeed:0.1


text:
#include "imap-common.h"
#include "imap-search.h"
#include "imap-commands.h"

static bool client_search_update_cancel(struct client *client, const char *tag)
{
	struct imap_search_update *update;
	unsigned int idx;

	update = client_search_update_lookup(client, tag, &idx);
	if (update == NULL)
		return FALSE;

	imap_search_update_free(update);
	array_delete(&client->search_updates, idx, 1);
	return TRUE;
}

bool cmd_cancelupdate(struct client_command_context *cmd)
{
	const struct imap_arg *args;
	const char *tag;
	unsigned int i;

	if (!client_read_args(cmd, 0, 0, &args))
		return FALSE;

	for (i = 0; args[i].type == IMAP_ARG_STRING; i++) ;
	if (!IMAP_ARG_IS_EOL(&args[i]) || i == 0) {
		client_send_command_error(cmd, "Invalid parameters.");
		return TRUE;
	}

	while (imap_arg_get_quoted(args, &tag)) {
		if (!client_search_update_cancel(cmd->client, tag)) {
			client_send_tagline(cmd, "NO Unknown tag.");
			return TRUE;
		}
		args++;
	}
	client_send_tagline(cmd, "OK Updates cancelled.");
	return TRUE;
}


text:
import uuid
import os

class TempImage:
	def __init__(self, basePath="./", ext=".jpg"):
		# construct the file path
		self.path = "{base_path}/{rand}{ext}".format(base_path=basePath,
			rand=str(uuid.uuid4()), ext=ext)

	def cleanup(self):
		# remove the file
		os.remove(self.path)


text:
package wiki.chenxun.ace.core.base.annotations;

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

/**
 * @Description: Created by chenxun on 2017/4/8.
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Put {
}