text:
layout: post
title: Stars, Bars, and Names
---

TLDR: I learned about the stars and bars technique from combinatorics and used it to get an
estimate of the number of unique names that are possible in CCNx. In short, it's an astronomically
huge number. A fixed packet length therefore imposes no practical restriction on the number of possible
names that can be formed.

# Introduction

In one of my ongoing research projects we needed to compute a rough estimate of the
number of unique CCNx names.
On the wire, a name is TLV representing a URI with an arbitrarily sized list of segments. Each
segment is yet another TLV. In most cases, the type of a segment is T_NAMESEGMENT, which means
that the value is just a generic name segment (i.e., a flat, opaque string). Other segment
types include T_IPID (interest payload ID), T_CHUNK (chunk number), and T_VERSION (version number).

The name is nested several layers deep within a CCNx packet. The diagram below shows the TLV
packet format up to the name field.

~~~
                     1                   2                   3
   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +---------------+---------------+---------------+---------------+
   |    Version    |  PacketType   |         PacketLength          |
   +---------------+---------------+---------------+---------------+
   |           PacketType specific fields          | HeaderLength  |
   +---------------+---------------+---------------+---------------+
   / Optional Hop-by-hop header TLVs                               /
   +---------------+---------------+---------------+---------------+
   |         MessageType           |         MessageLength         |
   +---------------+---------------+---------------+---------------+
   | Name TLV       (Type = T_NAME)                                |
   +---------------+---------------+---------------+---------------+
   /                   REST OF THE PACKET HERE                     /
   +---------------+---------------+---------------+---------------+
~~~

Beyond the Name TLV, there are two other important fields in this packet snippet:
PacketLength and HeaderLength. The PacketLength is the length of the entire packet
(including the header), bounded by 64KB, and the HeaderLength is the length of the
header up to the Message TLV (i.e., the MessageType and MessageLength fields).
This means that the name has a fixed length. Thus, we are at least able to compute
the total number of unique names. But how?

# First Attempt

Assume we know the fixed byte length $B$ for our name. One way to compute the number of unique
names is to do the following:

1. For each byte length $b = 1$ to $B$ generate all possible random strings of length b.
2. For each random string, compute the number of ways to partition the string into
non-empty ordered sets. For example, let $L = [e_1, e_2, \dots, e_b]$ be one random string
of length $b$. Moreover, let $k \geq 2$ be the number of partitions we seek for this list.
One valid partition for $k = 2$ would be $L_1 = [e_1]$ and $L_2 = [e_2,\dots,e_b]$. We would
need to consider all possible values of $k$ from $1$ to $b - 1$.
3. Compute the total number of all names generated from steps 1 and 2.

The number of unique byte strings of length $b$ is simply $2^{8b}$.
For step 2, given a random string represented as a list $L$, there are $b - 1$ possible
values for $k$. All that remains is to compute the number of possible partitions given
the list $L$ and integer $k$. The following Python function does this accurately.

{% gist 9202048b72ce8e2188d2112b71ec8af8 %}

Given this approach, we can compute the total number of CCNx names with the following bit of code.

{% gist f37b1061ed974d76d8ee18e6ce726117 %}

# Stars and Bars

While the above technique works, I find it messy. I would prefer a less verbose alternative to
the computation rather than this algorithmic description. During my search for a cleaner
way to compute this value I was pointed to the stars and bars technique [1] --
a useful combinatorics result that helps in counting many things.
Using the stars and bars method, it can be shown that the number ways to insert $k - 1$
separators into the $n - 1$ gaps in a list $L$ is $\binom {n - 1} {k - 1}$.
This is identical to finding the number of ways to split a list $L$ of $n$ elements
$k$ partitions. So using this fact we can replace the above computation with the following
simple expression.

$$
\begin{align}
\sum_{b=1}^B 2^{8b}\left(1 + \sum_{k=1}^{b - 1} \binom {b - 1} {k - 1}\right)
\end{align}
$$

The following program implements this computation in addition to the one previously listed.
You can run it to check that the outputs are the same. Bear in mind, though, that the number
of names is *huge* due to the ability to allow for arbitrarily many segments
in a name. To give you an estimate, if we consider names with an upper bound of
8 bytes, there are roughly $2.3 \times 10^{21}$ different names. Now imagine that number
when you consider that names are really capped at just under 64KB in length.
I think it's safe to say that we won't suffer from namespace saturation any time soon.

{% gist 26216ecc97bc624b08bded6d31db4253 %}

# References

- [1] https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)


text:
for k, fil in pairs(file.Find("lua/menu_plugins/default/*.lua", "GAME")) do
	menup.include("default/"..fil)
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SIS.HTTP.Enums;
using SIS.HTTP.Requests;
using SIS.HTTP.Responses;
using SIS.MvcFramework.Attributes;
using SIS.MvcFramework.Attributes.Action;
using SIS.MvcFramework.Attributes.Security;
using SIS.MvcFramework.DependencyContainer;
using SIS.MvcFramework.Logging;
using SIS.MvcFramework.Result;
using SIS.MvcFramework.Routing;
using SIS.MvcFramework.Sessions;
using IServiceProvider = SIS.MvcFramework.DependencyContainer.IServiceProvider;

namespace SIS.MvcFramework
{
    public static class WebHost
    {
        public static void Start(IMvcApplication application)
        {
            IServerRoutingTable serverRoutingTable = new ServerRoutingTable();
            IHttpSessionStorage httpSessionStorage = new HttpSessionStorage();
            IServiceProvider serviceProvider = new ServiceProvider();
            serviceProvider.Add<ILogger, ConsoleLogger>();

            application.ConfigureServices(serviceProvider);

            AutoRegisterRoutes(application, serverRoutingTable, serviceProvider);
            application.Configure(serverRoutingTable);
            var server = new Server(8000, serverRoutingTable, httpSessionStorage);
            server.Run();
        }

        private static void AutoRegisterRoutes(
            IMvcApplication application,
            IServerRoutingTable serverRoutingTable,
            IServiceProvider serviceProvider)
        {
            var controllers = application.GetType().Assembly.GetTypes()
                .Where(type => type.IsClass && !type.IsAbstract
                    && typeof(Controller).IsAssignableFrom(type));
            foreach (var controllerType in controllers)
            {
                var actions = controllerType
                    .GetMethods(BindingFlags.DeclaredOnly
                    | BindingFlags.Public
                    | BindingFlags.Instance)
                    .Where(x => !x.IsSpecialName && x.DeclaringType == controllerType)
                    .Where(x => x.GetCustomAttributes().All(a => a.GetType() != typeof(NonActionAttribute)));

                foreach (var action in actions)
                {
                    var path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{action.Name}";
                    var attribute = action.GetCustomAttributes().Where(
                        x => x.GetType().IsSubclassOf(typeof(BaseHttpAttribute))).LastOrDefault() as BaseHttpAttribute;
                    var httpMethod = HttpRequestMethod.Get;
                    if (attribute != null)
                    {
                        httpMethod = attribute.Method;
                    }

                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controllerType.Name.Replace("Controller", string.Empty)}/{attribute.ActionName}";
                    }

                    serverRoutingTable.Add(httpMethod, path,
                        (request) => ProcessRequest(serviceProvider, controllerType, action, request));

                    System.Console.WriteLine(httpMethod + " " + path);
                }
            }
        }

        private static IHttpResponse ProcessRequest(
            IServiceProvider serviceProvider,
            System.Type controllerType,
            MethodInfo action,
            IHttpRequest request)
        {
            var controllerInstance = serviceProvider.CreateInstance(controllerType) as Controller;
            controllerInstance.Request = request;

            // Security Authorization - TODO: Refactor this
            var controllerPrincipal = controllerInstance.User;
            var authorizeAttribute = action.GetCustomAttributes()
                .LastOrDefault(a => a.GetType() == typeof(AuthorizeAttribute)) as AuthorizeAttribute;

            if (authorizeAttribute != null && !authorizeAttribute.IsInAuthority(controllerPrincipal))
            {
                // TODO: Redirect to configured URL
                return new HttpResponse(HttpResponseStatusCode.Forbidden);
            }

            var parameters = action.GetParameters();
            var parameterValues = new List<object>();

            foreach (var parameter in parameters)
            {
                ISet<string> httpDataValue = TryGetHttpParameter(request, parameter.Name);

                if (parameter.ParameterType.GetInterfaces().Any(
                    i => i.IsGenericType &&
                    i.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                    && parameter.ParameterType != typeof(string))
                {

                    var collection = httpDataValue.Select(x => System.Convert.ChangeType(x,
                        parameter.ParameterType.GenericTypeArguments.First()));
                    parameterValues.Add(collection);
                    continue;
                }

                try
                {
                    string httpStringValue = httpDataValue.FirstOrDefault();
                    var parameterValue = System.Convert.ChangeType(httpStringValue, parameter.ParameterType);
                    parameterValues.Add(parameterValue);
                }
                catch
                {
                    var paramaterValue = System.Activator.CreateInstance(parameter.ParameterType);
                    var properties = parameter.ParameterType.GetProperties();

                    foreach (var property in properties)
                    {
                        ISet<string> propertyHttpDataValue = TryGetHttpParameter(request, property.Name);

                        if (property.PropertyType.GetInterfaces().Any(
                            i => i.IsGenericType &&
                                 i.GetGenericTypeDefinition() == typeof(IEnumerable<>)) &&
                            property.PropertyType != typeof(string))
                        {
                            var propertyValue = (IList) Activator.CreateInstance(property.PropertyType);

                            foreach (var parameterElement in propertyHttpDataValue)
                            {
                                propertyValue.Add(parameterElement);
                            }

                            property.SetMethod.Invoke(paramaterValue, new object[] { propertyValue });
                        }
                        else
                        {
                            var firstValue = propertyHttpDataValue.FirstOrDefault();
                            var propertyValue = System.Convert.ChangeType(firstValue, property.PropertyType);
                            property.SetMethod.Invoke(paramaterValue, new object[] {propertyValue});
                        }
                    }

                    parameterValues.Add(paramaterValue);
                }
            }

            var response = action.Invoke(controllerInstance, parameterValues.ToArray()) as ActionResult;
            return response;
        }

        private static ISet<string> TryGetHttpParameter(IHttpRequest request, string parameterName)
        {
            parameterName = parameterName.ToLower();
            ISet<string> httpDataValue = null;
            if (request.QueryData.Any(x => x.Key.ToLower() == parameterName))
            {
                httpDataValue = request.QueryData.FirstOrDefault(
                    x => x.Key.ToLower() == parameterName).Value;
            }
            else if (request.FormData.Any(x => x.Key.ToLower() == parameterName))
            {
                httpDataValue = request.FormData.FirstOrDefault(
                    x => x.Key.ToLower() == parameterName).Value;
            }

            return httpDataValue;
        }
    }
}


text:
@echo off
echo.
echo Running all -?.x test cases:
echo.

setlocal
if _%lua%_==__ set lua=lua

for %%i in (*-?.*.lua) do call :runtest %%i

echo.
echo -----------------------
echo DONE!
echo.
echo (To point at a specific lua.exe, use "set lua=c:\path\to\lua.exe" prior to executing %0)
echo.
pause
goto :eof

:runtest
echo ----- Running %1:
%lua% %1
goto :eof


text:
\documentclass[
  pepbrief,
  fontsize=12pt,
  paper=a4,
  DIV=14,
  parskip=half,
  backaddress=false,
]{scrlttr2}

\usepackage{fontspec}
\usepackage{polyglossia}
\setmainlanguage{german}

\usepackage{microtype}
\usepackage{graphicx}

\usepackage{xcolor}
\usepackage[colorlinks=true,urlcolor=blue!50!black]{hyperref}

\author{Henning Moldenhauer}
\setkomavar{subject}{Bewerbung zum Going Abroad - Purdue}

\begin{document}
\begin{letter}{%
  Max Mustermann\\
  Musterstraße 1\\
  44227 Dortmund%
}
% ANREDE
\opening{Lieber Max,}
% BRIEFTEXT

leider kannst du an unserem Going Abroad Programm nicht teilnehmen.

Wir wünschen dir trotzdem weiterhin alles Gute.

% BRIEFSCHLUSS
\closing{Mit freundlichen Grüßen}

% ANHANG
\end{letter}
\end{document}


text:
title: maxwell
excerpt: maxwell effort estimation
layout: repo-dataset
author: Li Yanfu
---

# URL

  * [Data Link (DOI)](https://doi.org/10.5281/zenodo.268461)

# Change Log

When | What
---- | ----
   March 21, 2009 | Donated by [Li Yanfu](/repo/people/data-donors/promise3.html)

Source: Finish banking data

# Reference

1 K. D. Maxwell. 2002. Applied Statistics for Software Managers. Englewood Cliffs, NJ. Prentice-Hall.

2 P. Sentas, L. Angelis, I. Stamelos, G. Bleris. 2005. Software productivity and effort prediction with ordinal regression. Information and Software Technology, 47, 17-29.

3 Y.F. Li, M. Xie, T.N. Goh. 2009. A Study of Mutual Information Based Feature Selection for Case Based Reasoning in Software Cost Estimation. Expert Systems with Applications. 36(3), 5921-5931.

4 Y.F. Li, M. Xie, T.N. Goh. 2009. A Study on the Non-linear Adjustment for Analogy Based Software Cost Estimation. Empirical Software Engineering. In press.


text:
CPU Spy
==========

master: [![Build Status](https://travis-ci.org/Fluci/CPU-Spy.svg?branch=master)](https://travis-ci.org/Fluci/CPU-Spy)

dev: [![Build Status](https://travis-ci.org/Fluci/CPU-Spy.svg?branch=dev)](https://travis-ci.org/Fluci/CPU-Spy)

A light weighted activity monitor.

While studying, I tend to use my computer a lot running on battery.
Sometimes there are applications in the background suddenly using a lot of CPU power draining my battery faster.

That mustn't happen! I've looked for some alternatives to Apple's Activity Monitor, but since I couldn't find a good one, I've written an application myself. And this is the result! CPU Spy is a very simple application, all it has to do, is to give you a rough idea in which state your CPU is in and offer you options to reduce energy consumption as much as possible.

This application is in continuous development if my schedule allows.
Feel free to suggest new features and improvements. But since I don't promise anything it sometimes might be faster to fork the repository, add it yourself and then send me a pull request (if you want to share it with the rest of the world). Contributors are welcome!


text:
const uuid = require('uuid');
const jwt = require('jsonwebtoken');
const User = require('../../models/User');
const wrap = require('../../utilities/wrap');
const Mailer = require('../../mail');
const { ONE_DAY_S, ONE_DAY_MS } = require('../../constants');
const { MINIMUM_PASSWORD_LENGTH, MINIMUM_PASSWORD_MESSAGE } = require('../../constants/user');

const mailer = new Mailer();

module.exports = ({ express, config }) => {
  const router = new express.Router();

  router.post(
    '/',
    wrap(function* authenticate(req, res) {
      req.checkBody('email').isEmail();
      req.checkBody('password').notEmpty();

      const errors = req.validationErrors();

      if (errors) {
        return res.status(400).send(errors);
      }

      const { email, password } = req.body;

      const user = yield User.forge({ email }).fetch();

      if (!user) {
        return res.status(400).json({ message: 'Authentication failed.' });
      }

      const validPassword = user.comparePassword(password);

      if (!validPassword) {
        return res.status(400).json({ message: 'Authentication failed.' });
      }

      const token = jwt.sign(
        {
          name: user.get('name'),
          email: user.get('email'),
        },
        config.secret,
        {
          expiresIn: ONE_DAY_S,
        }
      );

      return res.json({ token });
    })
  );

  router.route('/resetPassword').post(
    wrap(function* resetPassword(req, res) {
      req.checkBody('email').isEmail();

      const errors = req.validationErrors();

      if (errors) {
        return res.status(400).send(errors);
      }

      const { email } = req.body;

      const user = yield User.forge({ email }).fetch();

      if (!user) {
        // Send 200 with reset password so that people can't guess the email address
        return res.json({ message: `A email has been sent to ${email} with further instructions.` });
      }

      const resetPasswordToken = uuid.v4();

      user.set({
        resetPasswordToken,
        resetPasswordExpires: Date.now() + ONE_DAY_MS,
      });

      yield user.save();

      yield mailer.send(
        {
          to: email,
          subject: 'Reset Password',
          resetUrl: `http://${req.headers.host}/admin/reset/${resetPasswordToken}`,
        },
        'resetPassword'
      );

      return res.json({ message: `A email has been sent to ${email} with further instructions.` });
    })
  );

  router.route('/resetPassword/:token').put(
    wrap(function* resetPassword(req, res) {
      req.checkBody('token').equals(req.params.token);
      req.checkBody('password', MINIMUM_PASSWORD_MESSAGE).isLength({ min: MINIMUM_PASSWORD_LENGTH });
      req.checkBody('confirmPassword').equals(req.body.confirmPassword);

      const errors = req.validationErrors();

      if (errors) {
        return res.status(400).send(errors);
      }

      const { token, password } = req.body;

      const user = yield User.forge({ resetPasswordToken: token }).where('reset_password_expires', '>', Date.now()).fetch();

      if (!user) {
        return res.status(400).json({ message: 'Password reset token is invalid or has expired.' });
      }

      user.set({
        resetPasswordToken: null,
        resetPasswordExpires: null,
        password,
      });

      yield user.save();

      yield mailer.send(
        {
          to: user.get('email'),
          subject: 'Your password has been changed',
        },
        'resetPasswordConfirmation'
      );

      return res.json({ message: 'Password Reset Successfully!' });
    })
  );

  return router;
};


text:
package nl.esciencecenter.xenon.adaptors.gridengine;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import nl.esciencecenter.xenon.XenonException;
import nl.esciencecenter.xenon.adaptors.scripting.RemoteCommandRunner;
import nl.esciencecenter.xenon.adaptors.scripting.SchedulerConnection;
import nl.esciencecenter.xenon.adaptors.scripting.ScriptingAdaptor;
import nl.esciencecenter.xenon.adaptors.scripting.ScriptingParser;
import nl.esciencecenter.xenon.adaptors.slurm.SlurmAdaptor;
import nl.esciencecenter.xenon.credentials.Credential;
import nl.esciencecenter.xenon.engine.XenonEngine;
import nl.esciencecenter.xenon.engine.XenonProperties;
import nl.esciencecenter.xenon.engine.jobs.JobImplementation;
import nl.esciencecenter.xenon.engine.jobs.JobStatusImplementation;
import nl.esciencecenter.xenon.engine.jobs.QueueStatusImplementation;
import nl.esciencecenter.xenon.engine.jobs.SchedulerImplementation;
import nl.esciencecenter.xenon.files.RelativePath;
import nl.esciencecenter.xenon.jobs.InvalidJobDescriptionException;
import nl.esciencecenter.xenon.jobs.Job;
import nl.esciencecenter.xenon.jobs.JobCanceledException;
import nl.esciencecenter.xenon.jobs.JobDescription;
import nl.esciencecenter.xenon.jobs.JobStatus;
import nl.esciencecenter.xenon.jobs.NoSuchJobException;
import nl.esciencecenter.xenon.jobs.NoSuchQueueException;
import nl.esciencecenter.xenon.jobs.QueueStatus;
import nl.esciencecenter.xenon.jobs.Scheduler;
import nl.esciencecenter.xenon.jobs.Streams;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Interface to the GridEngine command line tools. Will run commands to submit/list/cancel jobs and get the status of queues.
 *
 * @author Niels Drost
 *
 */
public class GridEngineSchedulerConnection extends SchedulerConnection {

    private static final Logger LOGGER = LoggerFactory.getLogger(GridEngineSchedulerConnection.class);

    public static final String JOB_OPTION_JOB_SCRIPT = "job.script";

    public static final String JOB_OPTION_PARALLEL_ENVIRONMENT = "parallel.environment";

    public static final String JOB_OPTION_PARALLEL_SLOTS = "parallel.slots";

    public static final String JOB_OPTION_RESOURCES = "resources";

    private static final String[] VALID_JOB_OPTIONS = new String[] { JOB_OPTION_JOB_SCRIPT, JOB_OPTION_PARALLEL_ENVIRONMENT,
            JOB_OPTION_PARALLEL_SLOTS, JOB_OPTION_RESOURCES };

    private static final String QACCT_HEADER = "==============================================================";

    protected static void verifyJobDescription(JobDescription description) throws XenonException {
        SchedulerConnection.verifyJobOptions(description.getJobOptions(), VALID_JOB_OPTIONS, GridEngineAdaptor.ADAPTOR_NAME);

        if (description.isInteractive()) {
            throw new InvalidJobDescriptionException(GridEngineAdaptor.ADAPTOR_NAME, "Adaptor does not support interactive jobs");
        }

        if (description.isStartSingleProcess()) {
            throw new InvalidJobDescriptionException(SlurmAdaptor.ADAPTOR_NAME,
                    "StartSingleProcess option not supported");
        }

        //check for option that overrides job script completely.
        if (description.getJobOptions().get(JOB_OPTION_JOB_SCRIPT) != null) {
            //no remaining settings checked.
            return;
        }

        //perform standard checks.
        SchedulerConnection.verifyJobDescription(description, GridEngineAdaptor.ADAPTOR_NAME);

        //check if the parallel environment and queue are specified.
        if (description.getNodeCount() != 1) {
            if (!description.getJobOptions().containsKey(JOB_OPTION_PARALLEL_ENVIRONMENT)) {
                throw new InvalidJobDescriptionException(GridEngineAdaptor.ADAPTOR_NAME,
                        "Parallel job requested but mandatory parallel.environment option not specificied.");
            }
            if (description.getQueueName() == null && !description.getJobOptions().containsKey(JOB_OPTION_PARALLEL_SLOTS)) {
                throw new InvalidJobDescriptionException(GridEngineAdaptor.ADAPTOR_NAME,
                        "Parallel job requested but neither queue nor number of slots specificied (at least one is required)");
            }
        }
    }

    protected static JobStatus getJobStatusFromQacctInfo(Map<String, String> info, Job job) throws XenonException {
        Integer exitcode = null;
        Exception exception = null;
        String state = "done";

        if (info == null) {
            return null;
        }

        SchedulerConnection.verifyJobInfo(info, job, GridEngineAdaptor.ADAPTOR_NAME, "jobnumber", "exit_status", "failed");

        String exitcodeString = info.get("exit_status");
        String failedString = info.get("failed");

        try {
            exitcode = Integer.parseInt(info.get("exit_status"));
        } catch (NumberFormatException e) {
            throw new XenonException(GridEngineAdaptor.ADAPTOR_NAME, "cannot parse exit code of job " + job.getIdentifier()
                    + " from string " + exitcodeString, e);

        }

        if (failedString.equals("0")) {
            //Success!
        } else if (failedString.startsWith("100")) {
            //error code for killed jobs
            exception = new JobCanceledException(GridEngineAdaptor.ADAPTOR_NAME, "Job killed by signal");
        } else {
            //unknown error code
            exception = new XenonException(GridEngineAdaptor.ADAPTOR_NAME, "Job reports error: " + failedString);
        }

        return new JobStatusImplementation(job, state, exitcode, exception, false, true, info);
    }

    protected static JobStatus getJobStatusFromQstatInfo(Map<String, Map<String, String>> info, Job job) throws XenonException {
        boolean done = false;
        Map<String, String> jobInfo = info.get(job.getIdentifier());

        if (jobInfo == null) {
            return null;
        }

        SchedulerConnection.verifyJobInfo(jobInfo, job, GridEngineAdaptor.ADAPTOR_NAME, "JB_job_number", "state", "long_state");

        String longState = jobInfo.get("long_state");
        String stateCode = jobInfo.get("state");

        Exception exception = null;
        if (stateCode.contains("E")) {
            exception = new XenonException(GridEngineAdaptor.ADAPTOR_NAME, "Job reports error state: " + stateCode);
            done = true;
        }

        return new JobStatusImplementation(job, longState, null, exception, "running".equals(longState), done, jobInfo);
    }

    private final long accountingGraceTime;

    /**
     * Map with the last seen time of jobs. There is a delay between jobs disappearing from the qstat queue output, and
     * information about this job appearing in the qacct output. Instead of throwing an exception, we allow for a certain grace
     * time. Jobs will report the status "pending" during this time. Typical delays are in the order of seconds.
     */
    private final Map<String, Long> lastSeenMap;

    //list of jobs we have killed before they even started. These will not end up in qacct, so we keep them here.
    private final Set<Long> deletedJobs;

    private final Scheduler scheduler;

    private final GridEngineXmlParser parser;

    private final GridEngineSetup setupInfo;

    GridEngineSchedulerConnection(ScriptingAdaptor adaptor, String scheme, String location, Credential credential,
            XenonProperties properties, XenonEngine engine) throws XenonException {

        super(adaptor, scheme, location, credential, properties, engine, properties
                .getLongProperty(GridEngineAdaptor.POLL_DELAY_PROPERTY));

        boolean ignoreVersion = properties.getBooleanProperty(GridEngineAdaptor.IGNORE_VERSION_PROPERTY);
        accountingGraceTime = properties.getLongProperty(GridEngineAdaptor.ACCOUNTING_GRACE_TIME_PROPERTY);

        parser = new GridEngineXmlParser(ignoreVersion);

        lastSeenMap = new HashMap<String, Long>();
        deletedJobs = new HashSet<Long>();

        //will run a few commands to fetch info
        setupInfo = new GridEngineSetup(this);

        scheduler = new SchedulerImplementation(GridEngineAdaptor.ADAPTOR_NAME, getID(), scheme, location,
                setupInfo.getQueueNames(), credential, getProperties(), false, false, true);
    }

    @Override
    public Scheduler getScheduler() {
        return scheduler;
    }

    @Override
    public String[] getQueueNames() {
        return setupInfo.getQueueNames();
    }

    @Override
    public String getDefaultQueueName() {
        return null;
    }

    private synchronized void updateJobsSeenMap(Set<String> identifiers) {
        long currentTime = System.currentTimeMillis();

        for (String identifier : identifiers) {
            lastSeenMap.put(identifier, currentTime);
        }

        long expiredTime = currentTime + accountingGraceTime;

        Iterator<Entry<String, Long>> iterator = lastSeenMap.entrySet().iterator();

        while (iterator.hasNext()) {
            Entry<String, Long> entry = iterator.next();

            if (entry.getValue() > expiredTime) {
                iterator.remove();
            }
        }

    }

    private synchronized boolean haveRecentlySeen(String identifier) {
        if (!lastSeenMap.containsKey(identifier)) {
            return false;
        }

        return (lastSeenMap.get(identifier) + accountingGraceTime) > System.currentTimeMillis();
    }

    private synchronized void addDeletedJob(Job job) {
        deletedJobs.add(Long.parseLong(job.getIdentifier()));
    }

    /**
     * Note: Works exactly once per job.
     */
    private synchronized boolean jobWasDeleted(Job job) {
        //optimization of common case
        if (deletedJobs.isEmpty()) {
            return false;
        }
        return deletedJobs.remove(Long.parseLong(job.getIdentifier()));
    }

    private void jobsFromStatus(String statusOutput, Scheduler scheduler, List<Job> result) throws XenonException {
        Map<String, Map<String, String>> status = parser.parseJobInfos(statusOutput);

        updateJobsSeenMap(status.keySet());

        for (String jobID : status.keySet()) {
            result.add(new JobImplementation(scheduler, jobID, false, false));
        }

    }

    @Override
    public Job[] getJobs(String... queueNames) throws XenonException {
        ArrayList<Job> result = new ArrayList<Job>();

        if (queueNames == null || queueNames.length == 0) {
            String statusOutput = runCheckedCommand(null, "qstat", "-xml");

            jobsFromStatus(statusOutput, getScheduler(), result);
        } else {
            for (String queueName : queueNames) {
                RemoteCommandRunner runner = runCommand(null, "qstat", "-xml", "-q", queueName);

                if (runner.success()) {
                    jobsFromStatus(runner.getStdout(), getScheduler(), result);
                } else if (runner.getExitCode() == 1) {
                    //sge returns "1" as the exit code if there is something wrong with the queue, ignore
                    LOGGER.warn("Failed to get queue status for queue " + runner);
                    throw new NoSuchQueueException(GridEngineAdaptor.ADAPTOR_NAME, "Failed to get queue status for queue \""
                            + queueName + "\": " + runner);
                } else {
                    throw new XenonException(GridEngineAdaptor.ADAPTOR_NAME, "Failed to get queue status for queue \""
                            + queueName + "\": " + runner);
                }
            }
        }

        Job[] resultArray = result.toArray(new Job[result.size()]);

        return resultArray;
    }

    @Override
    public QueueStatus getQueueStatus(String queueName) throws XenonException {
        String qstatOutput = runCheckedCommand(null, "qstat", "-xml", "-g", "c");

        Map<String, Map<String, String>> allMap = parser.parseQueueInfos(qstatOutput);

        Map<String, String> map = allMap.get(queueName);

        if (map == null || map.isEmpty()) {
            throw new NoSuchQueueException(GridEngineAdaptor.ADAPTOR_NAME, "Cannot get status of queue \"" + queueName
                    + "\" from server, perhaps it does not exist?");
        }

        return new QueueStatusImplementation(getScheduler(), queueName, null, map);
    }

    @Override
    public QueueStatus[] getQueueStatuses(String... queueNames) throws XenonException {
        if (queueNames == null) {
            throw new IllegalArgumentException("Queue names cannot be null");
        }

        if (queueNames.length == 0) {
            queueNames = getQueueNames();
        }

        QueueStatus[] result = new QueueStatus[queueNames.length];

        String qstatOutput = runCheckedCommand(null, "qstat", "-xml", "-g", "c");

        Map<String, Map<String, String>> allMap = parser.parseQueueInfos(qstatOutput);

        for (int i = 0; i < queueNames.length; i++) {
            if (queueNames[i] == null) {
                result[i] = null;
            } else {
                //state for only the requested queue
                Map<String, String> map = allMap.get(queueNames[i]);

                if (map == null || map.isEmpty()) {
                    Exception exception = new NoSuchQueueException(GridEngineAdaptor.ADAPTOR_NAME,
                            "Cannot get status of queue \"" + queueNames[i] + "\" from server, perhaps it does not exist?");
                    result[i] = new QueueStatusImplementation(getScheduler(), queueNames[i], exception, null);
                } else {
                    result[i] = new QueueStatusImplementation(getScheduler(), queueNames[i], null, map);
                }
            }
        }

        return result;

    }

    @Override
    public Job submitJob(JobDescription description) throws XenonException {
        String output;
        RelativePath fsEntryPath = getFsEntryPath().getRelativePath();

        verifyJobDescription(description);

        //check for option that overrides job script completely.
        String customScriptFile = description.getJobOptions().get(JOB_OPTION_JOB_SCRIPT);

        if (customScriptFile == null) {
            String jobScript = GridEngineJobScriptGenerator.generate(description, fsEntryPath, setupInfo);

            output = runCheckedCommand(jobScript, "qsub");
        } else {
            //the user gave us a job script. Pass it to qsub as-is

            //convert to absolute path if needed
            if (!customScriptFile.startsWith("/")) {
                RelativePath scriptFile = fsEntryPath.resolve(customScriptFile);
                customScriptFile = scriptFile.getAbsolutePath();
            }

            output = runCheckedCommand(null, "qsub", customScriptFile);
        }

        String identifier = ScriptingParser.parseJobIDFromLine(output, GridEngineAdaptor.ADAPTOR_NAME, "Your job");

        updateJobsSeenMap(Collections.singleton(identifier));

        Job result = new JobImplementation(getScheduler(), identifier, description, false, false);

        return result;
    }

    @Override
    public JobStatus cancelJob(Job job) throws XenonException {
        String identifier = job.getIdentifier();
        String qdelOutput = runCheckedCommand(null, "qdel", identifier);

        String killedOutput = "has registered the job " + identifier + " for deletion";
        String deletedOutput = "has deleted job " + identifier;

        int matched = ScriptingParser.checkIfContains(qdelOutput, GridEngineAdaptor.ADAPTOR_NAME, killedOutput, deletedOutput);

        //keep track of the deleted jobs.
        if (matched == 1) {
            addDeletedJob(job);
        } else {
            //it will take a while to get this job to the accounting. Remember it existed for now
            updateJobsSeenMap(Collections.singleton(identifier));
        }

        return getJobStatus(job);
    }

    private Map<String, Map<String, String>> getQstatInfo() throws XenonException {
        RemoteCommandRunner runner = runCommand(null, "qstat", "-xml");

        if (!runner.success()) {
            LOGGER.debug("failed to get job status {}", runner);
            return new HashMap<String, Map<String, String>>();
        }

        Map<String, Map<String, String>> result = parser.parseJobInfos(runner.getStdout());

        //mark jobs we found as seen, in case they disappear from the queue
        updateJobsSeenMap(result.keySet());

        return result;
    }

    private Map<String, String> getQacctInfo(Job job) throws XenonException {
        RemoteCommandRunner runner = runCommand(null, "qacct", "-j", job.getIdentifier());

        if (!runner.success()) {
            LOGGER.debug("failed to get job status {}", runner);
            return null;
        }

        Map<String, String> result = ScriptingParser.parseKeyValueLines(runner.getStdout(), ScriptingParser.WHITESPACE_REGEX,
                GridEngineAdaptor.ADAPTOR_NAME, QACCT_HEADER);

        return result;
    }

    /**
     * Get job status. First checks given qstat info map, but also runs additional qacct and qdel commands if needed.
     *
     * @param qstatInfo
     *            the info to get the job status from.
     * @param job
     *            the job to get the status for.
     * @return the JobStatus of the job.
     * @throws XenonException
     *             in case the info is not valid.
     * @throws XenonException
     *             in case an additional command fails to run.
     */
    private JobStatus getJobStatus(Map<String, Map<String, String>> qstatInfo, Job job) throws XenonException {

        if (job == null) {
            return null;
        }

        JobStatus status = getJobStatusFromQstatInfo(qstatInfo, job);

        if (status != null && status.hasException()) {
            cancelJob(job);
            status = null;
        }

        if (status == null) {
            Map<String, String> qacctInfo = getQacctInfo(job);
            status = getJobStatusFromQacctInfo(qacctInfo, job);
        }

        //perhaps the job was killed while it was not running yet ("deleted", in sge speak). This will make it disappear from
        //qstat/qacct output completely
        if (status == null && jobWasDeleted(job)) {
            Exception exception = new JobCanceledException(GridEngineAdaptor.ADAPTOR_NAME, "Job " + job.getIdentifier()
                    + " deleted by user while still pending");
            status = new JobStatusImplementation(job, "killed", null, exception, false, true, null);
        }

        //this job is neither in qstat nor qacct output. we assume it is "in between" for a certain grace time.
        if (status == null && haveRecentlySeen(job.getIdentifier())) {
            status = new JobStatusImplementation(job, "unknown", null, null, false, false, new HashMap<String, String>());
        }

        return status;
    }

    @Override
    public JobStatus getJobStatus(Job job) throws XenonException {
        Map<String, Map<String, String>> info = getQstatInfo();

        JobStatus result = getJobStatus(info, job);

        //this job really does not exist. throw an exception
        if (result == null) {
            throw new NoSuchJobException(GridEngineAdaptor.ADAPTOR_NAME, "Job " + job.getIdentifier() + " not found on server");
        }

        return result;
    }

    @Override
    public JobStatus[] getJobStatuses(Job... jobs) throws XenonException {
        Map<String, Map<String, String>> info = getQstatInfo();

        JobStatus[] result = new JobStatus[jobs.length];

        for (int i = 0; i < result.length; i++) {
            if (jobs[i] == null) {
                result[i] = null;
            } else {
                result[i] = getJobStatus(info, jobs[i]);

                //this job really does not exist. set it to an error state.
                if (result[i] == null) {
                    Exception exception = new NoSuchJobException(GridEngineAdaptor.ADAPTOR_NAME, "Job " + jobs[i].getIdentifier()
                            + " not found on server");
                    result[i] = new JobStatusImplementation(jobs[i], null, null, exception, false, false, null);
                }
            }
        }
        return result;
    }

    @Override
    public Streams getStreams(Job job) throws XenonException {
        throw new XenonException(GridEngineAdaptor.ADAPTOR_NAME, "does not support interactive jobs");
    }

}


text:
package edu.wkd.towave.memorycleaner.mvp.views.impl.fragment;

import android.content.Context;
import edu.wkd.towave.memorycleaner.adapter.AutoStartAdapter;
import edu.wkd.towave.memorycleaner.mvp.views.View;

/**
 * Created by Administrator on 2016/5/5.
 */
public interface AutoStartView extends View {
    void onProgressUpdate(int current, int max, String appName);

    void onPreExecute();

    void onPostExecute(AutoStartAdapter recyclerAdapter);

    void stopRefresh();

    void startRefresh();

    boolean isRefreshing();

    void enableSwipeRefreshLayout(boolean enable);

    void initViews(AutoStartAdapter recyclerAdapter, Context context);

    //RelativeLayout setDialogValues(String[] memory);
    void showSnackbar(String message);

    void setFabVisible(boolean visible);
}


text:
package com.business.service;

import com.business.domain.OrderGoods;

/**
 * Created by billb on 2015-04-07.
 */
public interface OrderGoodsService {

    void addOrderGoods(OrderGoods goods);

    void deleteOrderGoods(int id);

    void editOrderGoods(OrderGoods goods);

}


text:
@lombok.EqualsAndHashCode class EqualsAndHashCodeEmpty {
  EqualsAndHashCodeEmpty() {
    super();
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
    if ((o == this))
        return true;
    if ((! (o instanceof EqualsAndHashCodeEmpty)))
        return false;
    final EqualsAndHashCodeEmpty other = (EqualsAndHashCodeEmpty) o;
    if ((! other.canEqual((java.lang.Object) this)))
        return false;
    return true;
  }
  protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) {
    return (other instanceof EqualsAndHashCodeEmpty);
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
    final int result = 1;
    return result;
  }
}
@lombok.EqualsAndHashCode(callSuper = true) class EqualsAndHashCodeEmptyWithSuper extends EqualsAndHashCodeEmpty {
  EqualsAndHashCodeEmptyWithSuper() {
    super();
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) {
    if ((o == this))
        return true;
    if ((! (o instanceof EqualsAndHashCodeEmptyWithSuper)))
        return false;
    final EqualsAndHashCodeEmptyWithSuper other = (EqualsAndHashCodeEmptyWithSuper) o;
    if ((! other.canEqual((java.lang.Object) this)))
        return false;
    if ((! super.equals(o)))
        return false;
    return true;
  }
  protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) {
    return (other instanceof EqualsAndHashCodeEmptyWithSuper);
  }
  public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() {
    final int result = super.hashCode();
    return result;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen android:title="@string/security_settings_title"
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:settings="http://schemas.android.com/apk/res/com.android.settings">
    <com.android.settingslib.RestrictedPreference android:persistent="false" android:title="@string/unlock_set_unlock_launch_picker_title_profile" android:key="unlock_set_or_change_profile" android:summary="@string/unlock_set_unlock_mode_pin" settings:keywords="@string/keywords_lockscreen" />
</PreferenceScreen>


text:
#pragma once
#include <iostream>
#include <vector>
#include "Message.h"
#include "FixedFileBuffer.h"
#include "Producer.h"
using namespace std;

/**
 *	Kafka Application Class
 *
 *	Coding Convention
 *	- camelCase
 */
class KafkaApp
{
	//FixedFileBuffer<Producer> prodBuffer;
	fstream prodList;
	//vector<Producer> producerList;

//Constructor, Destructor
public:
	KafkaApp();
	~KafkaApp();

//Method
public:
	void run();
	void addMessage();
	void requestMsgByTopic();
	vector<Message> requestMsgByTopic(int to);
	vector<Message> requestMsgByProdID(int prodID);
	void printRequestMsgByProdID();
	void recoveryCheck();	//producerList È®ÀÎ ÈÄ º¹±¸

//static method
public:
	/**
	 *	ºñ¾îÀִ°Š-> ""
	 *	Tombstone -> "RIP"
	 */
	static int hashRecord[2];
	static FixedFileBuffer<TopicHash> hashBuffer;

	//static string hashTable[100];
	static int getAddrInHashTable(string key);
};


text:
ACTUALLYCHAT
============

Overview
---------
ACTUALLY CHAT is a chat bot that can carry a conversation with a real person while simulating a first date conversation.


text:
package org.grails.config;

import grails.config.Config;
import grails.util.GrailsStringUtils;
import org.codehaus.groovy.runtime.DefaultGroovyMethods;
import org.grails.core.exceptions.GrailsConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.ConversionException;
import org.springframework.core.convert.support.ConfigurableConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.util.ClassUtils;

import java.util.*;

/**
 * A {@link Config} implementation that operates against a {@link org.grails.config.NavigableMap}
 *
 * @author Graeme Rocher
 * @since 3.0
 */

public abstract class NavigableMapConfig implements Config {
    protected static final Logger LOG = LoggerFactory.getLogger(NavigableMapConfig.class);
    protected ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    protected ConfigurableConversionService conversionService = new DefaultConversionService();
    protected NavigableMap configMap = new NavigableMap() {
        @Override
        protected Object mergeMapEntry(NavigableMap targetMap, String sourceKey, Object newValue) {
            if(newValue instanceof CharSequence) {
                newValue = resolvePlaceholders(newValue.toString());
            }
            return super.mergeMapEntry(targetMap, sourceKey, newValue);
        }
    };

    @Override
    public int hashCode() {
        return configMap.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof NavigableMapConfig) {
            return this.configMap.equals(((NavigableMapConfig)obj).configMap);
        }
        return false;
    }

    @Override
    public String toString() {
        return configMap.toString();
    }

    @Override
    public Object getAt(Object key) {
        return get(key);
    }

    @Override
    public void setAt(Object key, Object value) {
        configMap.put(key.toString(), value);
    }

    @Override
    public int size() {
        return configMap.size();
    }

    @Override
    public boolean isEmpty() {
        return configMap.isEmpty();
    }

    @Override
    public boolean containsKey(Object key) {
        return containsProperty(key.toString());
    }

    @Override
    public boolean containsValue(Object value) {
        return configMap.containsValue(value);
    }

    @Override
    public Object get(Object key) {
        return configMap.getProperty(key.toString());
    }

    @Override
    public Object put(String key, Object value) {
        return configMap.put(key, value);
    }

    @Override
    public Object remove(Object key) {
        return configMap.remove(key);
    }

    @Override
    public void putAll(Map<? extends String, ?> m) {
        configMap.putAll(m);
    }

    @Override
    public void clear() {
        configMap.clear();
    }

    @Override
    public Set<String> keySet() {
        return configMap.keySet();
    }

    @Override
    public Collection<Object> values() {
        return configMap.values();
    }

    @Override
    public Set<Entry<String, Object>> entrySet() {
        return configMap.entrySet();
    }

    @Override
    @Deprecated
    public Map<String, Object> flatten() {
        if(LOG.isWarnEnabled()) {
            LOG.warn("A plugin or your application called the flatten() method which can degrade startup performance");
        }
        return configMap;
    }

    @Override
    public Properties toProperties() {
        return configMap.toProperties();
    }

    @Override
    public Object navigate(String... path) {
        return configMap.navigate(path);
    }

    @Override
    public Config merge(Map<String, Object> toMerge) {
        configMap.merge(toMerge, true);
        return this;
    }

    public Object asType(Class c) {
        if(c==Boolean.class || c==boolean.class) return false;
        return null;
    }

    @Override
    public Iterator<Entry<String, Object>> iterator() {
        return DefaultGroovyMethods.iterator(configMap);
    }

    @Override
    public boolean containsProperty(String key) {
        return getProperty(key, Object.class) != null;
    }

    @Override
    public String getProperty(String key) {
        return getProperty(key, String.class);
    }

    @Override
    public String getProperty(String key, String defaultValue) {
        return getProperty(key, String.class, defaultValue);
    }

    @Override
    public <T> T getProperty(String key, Class<T> targetType) {
        return getProperty(key, targetType, null);
    }

    @Override
    public <T> T getProperty(String key, Class<T> targetType, T defaultValue, List<T> allowedValues) {
        T value = getProperty(key, targetType, defaultValue);
        if(!allowedValues.contains(value)) {
            throw new GrailsConfigurationException("Invalid configuration value [$value] for key [${key}]. Possible values $allowedValues");
        }
        return value;
    }

    @Override
    public <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
        Object originalValue = configMap.get(key);
        if(originalValue != null) {
            if(targetType.isInstance(originalValue)) {
                return (T)originalValue;
            }
            else {
                if(!(originalValue instanceof NavigableMap)) {

                    try {
                        T value = conversionService.convert(originalValue, targetType);
                        return DefaultGroovyMethods.asBoolean(value) ? value : defaultValue;
                    } catch (ConversionException e) {
                        if(targetType.isEnum()) {
                            String stringValue = originalValue.toString();
                            try {
                                T value = (T) toEnumValue(targetType, stringValue);
                                return value;
                            } catch (Throwable e2) {
                                // ignore e2 and throw original
                            }
                        }
                    }
                }
            }
        }
        return defaultValue;
    }

    private Object toEnumValue(Class targetType, String stringValue) {
        return Enum.valueOf(targetType, stringValue.toUpperCase());
    }

    @Override
    public String getRequiredProperty(String key) throws IllegalStateException {
        String value = getProperty(key);
        if(GrailsStringUtils.isBlank(value)) {
            throw new IllegalStateException("Value for key ["+key+"] cannot be resolved");
        }
        return value;
    }

    @Override
    public <T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException {
        T value = getProperty(key, targetType);
        if(value == null) {
            throw new IllegalStateException("Value for key ["+key+"] cannot be resolved");
        }
        return value;
    }

    public static class ClassConversionException extends ConversionException {

        public ClassConversionException(Class<?> actual, Class<?> expected) {
            super(String.format("Actual type %s is not assignable to expected type %s", actual.getName(), expected.getName()));
        }

        public ClassConversionException(String actual, Class<?> expected, Exception ex) {
            super(String.format("Could not find/load class %s during attempt to convert to %s", actual, expected.getName()), ex);
        }
    }
}


text:
@interface MOBProjectionEPSG4284 : MOBProjection

@end


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe FatCache::Shortcuts do

  describe 'when included in a class' do
    before do
      @manatee_class = Class.new
      @manatee_class.send(:include, FatCache::Shortcuts)
    end

    it 'provides a `cache`  method at the class level' do
      @manatee_class.should respond_to(:cache)
    end

    it 'provides a `cache`  method at the instance level' do
      @manatee_class.new.should respond_to(:cache)
    end

    describe 'the class level `cache` method' do
      it 'yields the FatCache class' do
        @manatee_class.cache
      end
    end

    describe 'the instance level `cache` method' do
      it 'yields the FatCache class' do
        @manatee_class.new.cache
      end
    end
  end

end


text:
//                validatorDescriptor.ClientAttributes(clientValidationRegistrationContext);
//                clientAttributes.Combine(clientValidationRegistrationContext.ClientAttributes);
//            }

//            context.ElementShape.ClientValidationAttributes = clientAttributes;
//        }

//        private dynamic BuildSettingsEditor(ElementEditorContext context, ValidatorDescriptor validatorDescriptor) {
//            if (String.IsNullOrWhiteSpace(validatorDescriptor.SettingsFormName))
//                return null;

//            return _formManager.Bind(_formManager.Build(validatorDescriptor.SettingsFormName), context.ValueProvider);
//        }
//    }
//}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface net.sf.jasperreports.engine.fill.JRMeasuredText (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.sf.jasperreports.engine.fill.JRMeasuredText

Packages that use JRMeasuredText

Package
Description

net.sf.jasperreports.engine.fill

Contains fill time implementations for the library's main interfaces and the entire
 engine used in the filling process (the actual core of JasperReports).

net.sf.jasperreports.engine.util

Contains utility classes for the core library.

Uses of JRMeasuredText in net.sf.jasperreports.engine.fill

Classes in net.sf.jasperreports.engine.fill that implement JRMeasuredText

Modifier and Type
Class and Description

protected static class
TextMeasurer.TextMeasuredState

Methods in net.sf.jasperreports.engine.fill that return JRMeasuredText

Modifier and Type
Method and Description

JRMeasuredText
JRTextMeasurer.measure(JRStyledText styledText,
       int remainingTextStart,
       int availableStretchHeight,
       boolean canOverflow)

Fit a text chunk in a given space.

JRMeasuredText
TextMeasurer.measure(JRStyledText styledText,
       int remainingTextStart,
       int availableStretchHeight,
       boolean canOverflow)

Uses of JRMeasuredText in net.sf.jasperreports.engine.util

Methods in net.sf.jasperreports.engine.util that return JRMeasuredText

Modifier and Type
Method and Description

JRMeasuredText
JdkGlyphFixTextMeasurer.measure(JRStyledText styledText,
       int remainingTextStart,
       int availableStretchHeight,
       boolean canOverflow)

Calls super.measure, catches
 sun.font.GlyphLayout NPEs and reattempts the call.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <Accelerate/Accelerate.h>

struct _FINCHAIN {
  int length; // Length of state vector
  int currentIter;

  double *currentState, *avgState, *varState, *proposedState, *_M2;
  double logLHDCurrentState;
  double accProb, avgAccProb;

  gsl_rng *r;
};

typedef struct _FINCHAIN FINCHAIN;

/*
  Initialises the finite dimensional chain
*/
void finmcmc_initChain(FINCHAIN *C, int n);

/*
  Frees the finite dimensional chain
*/
void finmcmc_freeChain(FINCHAIN *C);

void finmcmc_printChain(FINCHAIN C);

void finmcmc_writeChain(const FINCHAIN *C, FILE *fp);

void finmcmc_gausRanVec(const FINCHAIN *C, double *x, double stdDev);

/*
  Proposes a standard RWMH move
*/
void finmcmc_proposeRWMH(const FINCHAIN *C, double stdDev, double beta);

/*
  Update chain
*/
void finmcmc_updateRWMH(FINCHAIN *C, double logLHDOfProposal);

//void fin_initChain(FINCHAIN *C, int n, int sizePhi);

//void sampleRMWH(CHAIN *C);
//void sampleIndependenceSampler(CHAIN *C);
//void updateMean(CHAIN *C);
//void updateVar(CHAIN *C);
//void randomPriorDraw(gsl_rng *r, double PRIOR_ALPHA, fftw_complex *randDrawCoeffs);


text:
<?php

/**
 * Used to manage site config defintions
 * @author paulsidekick@gmail.com
 *
 * <code>
 * //could be set to App::$config if you wanted it globally accessible
 * $config = new \sb\Config\Db(App::$db);
 * $config->set('name', 'paul');
 * $config->delete('name');
 * echo $config->get('name');
 * print_r($config->getAll());
 * </code>
 *
 * Database must have following table and support INSERT AND DELETE
 *
    CREATE TABLE sb_config(
      k VARCHAR(100) PRIMARY KEY,
      v TEXT,
      t VARCHAR(5) DEFAULT 'str'
    );
 */

namespace sb\Config;

class Db{

    /**
     * Caches variables
     * @var array
     */
    protected $data = Array();

    /**
     * The database to load the defintions from.
     * @var PDO
     */
    protected $db;

    /**
     * The table name that the config values are stored in
     * @var string
     */
    protected $table = 'sb_config';

    /**
     * Instantiates the class and sets the db used
     * @param \PDO $db
     * @param string $prefix Only loads config values that start with a specific prefix
     */
    public function __construct(\PDO $db, $prefix=''){
        $this->db = $db;
        $this->load($prefix);
    }

    /**
     * Used to load all site definitions
     */
    public function load($prefix=''){
        $values = Array();

        $sql = "SELECT k, v, t FROM ".$this->table;
        if($prefix){
            $sql .= " WHERE k LIKE :prefix";
            $values[':prefix'] = $prefix.'%';
        }

        $stmt = $this->db->prepare($sql);
        $result = $stmt->execute($values);
        $rows = $this->db->s2o($sql, $values);
        foreach($rows as $row){

            $v = $row->v;

            if($row->t == 'json'){
                $v = json_decode($v);
            } else if($row->t == 'php'){
                $v = unserialize($v);
            } else if($row->t == 'int'){
                $v = (int) $v;
            } else {
                $v = (string) $v;
            }

            $this->data[$row->k] = $v;
        }

    }

    /**
     * Get a specific definition by key
     * @param string $key The key to load the value for
     * @param mixed $default_value The default value to give if nothing is found
     * @return string
     */
    public function get($key, $default_value = NULL){
        //return val for key from $data
        return isset($this->data[$key]) ? $this->data[$key] : $default_value;
    }

    /**
     * Return all the currently existing pairs for debugging, etc
     * @return array
     */
    public function getAll(){
        return $this->data;
    }

    /**
     * Save the defintions back to the db
     * @param string $key The key to store the value under
     * @param string $val The value of the key
     * @param string $type The type of the object str, int, php, json
     */
    public function set($key, $val, $type='str'){

        $this->delete($key);

        $orig_val = $val;

        if($type == 'php' || (is_object($val) && $type == 'str')){
            $val = serialize($val);
        } else if($type == 'json'){
            $val = json_encode($val);
        } else if($type == 'int'){
            $val = (int) $val;
        } else {
            $val = (string) $val;
        }

        $sql = "INSERT INTO ".$this->table." (k, v, t) VALUES (:k, :v, :t)";
        $stmt = $this->db->prepare($sql);
        $result = $stmt->execute(Array(
            ':k' => $key,
            ':v' => $val,
            ':t' => $type
        ));

        if($result){

            $this->data[$key] = $orig_val;
        }

        return $result ? 1 : 0;

    }

    /**
     * Deletes a key so that it no longer exists at all
     * @param string $key
     * @return boolean
     */
    public function delete($key){
        $sql = "DELETE FROM ".$this->table." WHERE k = :k";
        $stmt = $this->db->prepare($sql);
        $result = $stmt->execute(Array(":k" => $key));

        if(isset($this->data[$key])){
            unset($this->data[$key]);
        }

        return $result;
    }
}


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

namespace AnimalHierarchy
{
    class Program
    {
        static void Main(string[] args)
        {
            Kitten[] kittens = new Kitten[3]
            {
                new Kitten("Kittty1", 3),
                new Kitten("Kittty2", 5),
                new Kitten("Kittty3", 12)
            };
            Tomcat[] tomcats = new Tomcat[3]
            {
                new Tomcat("Tomcat1", 3),
                new Tomcat("Tomcat2", 8),
                new Tomcat("Tomcat3", 12)
            };
            Dog[] dogs = new Dog[3]
            {
                new Dog("Dog1", 15, Sex.male),
                new Dog("Dog2", 13, Sex.male),
                new Dog("Dog3", 12, Sex.female)
            };
            Frogg[] froggs = new Frogg[3]
            {
                new Frogg("Frogg1", 1, Sex.male),
                new Frogg("Frogg2", 1, Sex.female),
                new Frogg("Frogg3", 2, Sex.female)
            };
            string message = "Average age of";
            Console.WriteLine("{0} {1} - {2}", message, kittens.GetType().GetElementType(), GetAnimalAverageAge(kittens));
            Console.WriteLine("{0} {1} - {2}", message, typeof(Tomcat), GetAnimalAverageAge(tomcats));
            Console.WriteLine("{0} {1} - {2}", message, typeof(Dog), GetAnimalAverageAge(dogs));
            Console.WriteLine("{0} {1} - {2}", message, typeof(Frogg), GetAnimalAverageAge(froggs));

        }

        public static double GetAnimalAverageAge(Animal[] animals)
        {
            int ageSum = animals.Sum(animal => animal.Age);
            return ageSum / animals.Length;
        }
    }
}


text:
id: 43b1152e-7b97-44a5-8576-353aa103e746
post_id: f21c0ebe-c086-4094-9cd9-8af507646b4d
draft: false
author:
    name: gwern
    email: gwern0@gmail.com
    ip: 141.156.136.175
---

> It's possible the lances have some sort of special properties for each of the four children — kind of like kill switches — although why there would be a lance each is up for debate.

In the Confidential Information framework, that's exactly what the Lance(s) are for: stopping the Seeds of Life from doing stuff outside their assigned tasks. Adam and Lilith are 2 seeds, so it's plausible that the 4 seen in Second Impact are seeds themselves, and hence would have an accompanying Lance.


text:
package com.kiselev.reflection.ui.impl.type;

public class TypeUtils {

    public String getType(Class<?> clazz) {
        String type = "class ";

        if (clazz.isEnum()) type = "enum ";
        if (clazz.isInterface()) type = "interface ";
        if (clazz.isAnnotation()) type = "@interface ";

        return type;
    }
}


text:
package com.score.student.scoremanage.util;

import antlr.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created by yaguang.wang
 * on 2017/8/15.
 * coder utils SHA1,Base64 and MD5
 */
public class CoderUtils {
    public static final String KEY_SHA = "SHA";
    public static final String KEY_MD5 = "MD5";

    /**
     * BASE64 解码
     *
     * @param key 需要解码的字段
     * @return 解码后的字段
     * @throws IOException 解码失败
     */
    public static byte[] decryptBASE64(String key) throws IOException {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64 加密
     *
     * @param key 需要被译成密文的字符串的二进制
     * @return 翻译成的密文
     */
    public static String encryptBASE64(byte[] key) {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    /**
     * MD5 加密
     *
     * @param data 需要加密的数据
     * @return 加密后的字符串
     * @throws NoSuchAlgorithmException 未找到加密算法
     */
    public static byte[] encryptMD5(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
        md5.update(data);
        return md5.digest();
    }

    /**
     * SHA 加密
     *
     * @param data 需要加密的数据
     * @return 加密后的字符串
     * @throws NoSuchAlgorithmException 未找到加密算法
     */
    public static byte[] encryptSHA(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance(KEY_SHA);
        md5.update(data);
        return md5.digest();
    }
}


text:
package org.jbehaviour.plugins.system.impl;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import org.jbehaviour.plugins.system.ISystemAsyncTread;

public class SystemAsyncThread extends Thread implements ISystemAsyncTread {

	private ProcessBuilder pb;
	private int result = -999999999;

	private BufferedWriter stdin = null;
	private InputStream stderr = null;
	private InputStream stdout = null;

	private int iStdout = 0;
	private int iStderr = 0;
	private StringBuilder sbStdout = new StringBuilder();
	private StringBuilder sbStderr = new StringBuilder();

	private List<String> stdoutAsList = new ArrayList<String>();
	private List<String> stderrAsList = new ArrayList<String>();

	public SystemAsyncThread(List<String> args) {
		pb = new ProcessBuilder(args);
	}

	@Override
	public synchronized void start() {
		try {
			super.start();
		} catch(Exception e) {
			e.printStackTrace();
			result = -4;
		}
	}

	@Override
	public void run() {
		System.err.println("Starting ...");
		try {
			System.err.println("start");

			/**
			 * start the process
			 */
			Process process = pb.start();

			/**
			 * get stdin, stdout and stderr
			 * stream
			 */
			stdin  = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
			stderr = process.getErrorStream();
			stdout = process.getInputStream();

			/**
			 * sync wait
			 */
			result = process.waitFor();

			int car=0;

			/**
			 * dump stdout
			 */
			for(iStdout=0;(car = stdout.read()) > 0;iStdout++) {
				switch(car) {
					case 13:
						break;
					case 10:
						String value = sbStdout.toString();
						stdoutAsList.add(value);
					    System.out.println (value);
					    sbStdout.setLength(0);
						break;
					default:
						sbStdout.append((char) car);
				}
			}

			/**
			 * dump stderr
			 */
			for(iStderr=0;(car = stderr.read()) > 0;iStderr++) {
				switch(car) {
				case 13:
					break;
				case 10:
					String value = sbStderr.toString();
					stderrAsList.add(value);
				    System.err.println (value);
				    sbStderr.setLength(0);
					break;
				default:
					sbStderr.append((char) car);
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
			result = -2;
		} catch (InterruptedException e) {
			e.printStackTrace();
			result = -3;
		}
	}

	@Override
	public synchronized List<String> getStdoutAsList() {
		return stdoutAsList;
	}

	@Override
	public synchronized List<String> getStderrAsList() {
		return stderrAsList;
	}

	@Override
	public synchronized boolean ready() {
		return result != -999999999;
	}

	@Override
	public void write(String string) throws IOException {
		if(stdin == null) {
			throw new IOException("stdin is null");
		}
		stdin.write(string);
		stdin.flush();
	}

	@Override
	public int getResult() {
		return result;
	}

	@Override
	public int waitFor() throws InterruptedException {
		this.join();
		return this.getResult();
	}

	public int getiStdout() {
		return iStdout;
	}

	public int getiStderr() {
		return iStderr;
	}
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.data.meta.description }}{% endif %}">
    <title>{% if page.fulltitle %}{{ page.fulltitle | markdownify | strip_html }}{% else %}{% if page.title %}{{ page.title | markdownify | strip_html }} | {% endif %}{{ site.data.meta.title | markdownify | strip_html }}{% endif %}</title>
  </head>
  <body>
    {{ content }}
  </body>
</html>


text:
var restify = require('restify');
var services = require('./services.js');
var Results = require('./results.js');
var Slack = require('./slack.js');
var keepalive = require('./heroku-keepalive.js');
var knox = require('knox');

var server = restify.createServer();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

var port = process.env.PORT || 5000;

server.get('/', function(req, res, next) {
	res.send(200, 'Hello world');
	return next();
});

server.listen(port, function() {
	console.log('%s listening at %s', server.name, server.url);
});

keepalive(server);

if (process.env.NODE_ENV === 'production') {
  console.log('[' + process.env.NODE_ENV +'] ' + 'Did awake server at: ' + new Date());
}

var user = process.env.DRIBBBLE_USER;

var pingDribbbleInterval = process.env.DRIBBBLE_INTERVAL ? parseFloat(process.env.DRIBBBLE_INTERVAL) : 3; // Default 3 hours

setInterval(function() {
	services.fetchFollowedPostsForUser(user)
	.then(function(results){
		Results.handleResults(results);
	});
}, pingDribbbleInterval * 60 * 60 * 1000);


text:
@{

# Script module or binary module file associated with this manifest.
RootModule = 'Saritasa.RemoteManagement'

# Version number of this module.
ModuleVersion = '1.23.2'

# ID used to uniquely identify this module
GUID = '6e18f454-853c-413b-b614-39c8128c1399'

# Author of this module
Author = 'Anton Zimin'

# Company or vendor of this module
CompanyName = 'Saritasa'

# Copyright statement for this module
Copyright = '(c) 2016-2017 Saritasa. All rights reserved.'

# Description of the functionality provided by this module
Description = 'Contains functions to execute actions on a remote server. Allows to set up IIS, import sites and app pools, install MSI packages.'

# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''

# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''

# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''

# Minimum version of Microsoft .NET Framework required by this module
# DotNetFrameworkVersion = ''

# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''

# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''

# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(
    @{ ModuleName='Saritasa.General'; ModuleVersion='1.1.0'; GUID='7c7dc05c-033b-4838-8619-b84792571317' },
    @{ ModuleName='Saritasa.WinRM'; ModuleVersion='1.3.0'; GUID='4356a667-8e3d-43a8-9a2e-49eee4f67eed' }
)

# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()

# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()

# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()

# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()

# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()

# Functions to export from this module
FunctionsToExport = @('Import-AppPool', 'Import-Site',
    'Export-AppPool', 'Export-Site', 'Install-Arr', 'Install-Iis',
    'Install-WebManagementService', 'Install-WebDeploy',
    'Install-UrlRewrite', 'Install-MsiPackage', 'Import-PersonalSslCertificate')

# Cmdlets to export from this module
CmdletsToExport = @()

# Variables to export from this module
VariablesToExport = @()

# Aliases to export from this module
AliasesToExport = @()

# DSC resources to export from this module
# DscResourcesToExport = @()

# List of all modules packaged with this module
# ModuleList = @()

# List of all files packaged with this module
# FileList = @()

# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{

    PSData = @{

        # Tags applied to this module. These help with module discovery in online galleries.
        Tags = 'IIS', 'UrlRewrite', 'Management', 'WebManagement', 'WebDeploy',
            'AppPool', 'Site', 'MSI', 'WinRM'

        # A URL to the license for this module.
        LicenseUri = 'https://raw.githubusercontent.com/Saritasa/PSGallery/master/LICENSE'

        # A URL to the main website for this project.
        ProjectUri = 'https://github.com/Saritasa/PSGallery'

        # A URL to an icon representing this module.
        # IconUri = ''

        # ReleaseNotes of this module
        # ReleaseNotes = ''

    } # End of PSData hashtable

} # End of PrivateData hashtable

# HelpInfo URI of this module
# HelpInfoURI = ''

# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''

}


text:
package com.hxxc.user.app.ui.financial;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.hxxc.user.app.AppManager;
import com.hxxc.user.app.Event.MainEvent;
import com.hxxc.user.app.HXXCApplication;
import com.hxxc.user.app.Midhandler;
import com.hxxc.user.app.R;
import com.hxxc.user.app.UserInfoConfig;
import com.hxxc.user.app.adapter.CommonAdapter;
import com.hxxc.user.app.bean.UserInfo;
import com.hxxc.user.app.data.bean.AdviserBean;
import com.hxxc.user.app.rest.Api;
import com.hxxc.user.app.rest.BaseSubscriber;
import com.hxxc.user.app.rest.RxApiThread;
import com.hxxc.user.app.ui.MainActivity2;
import com.hxxc.user.app.ui.base.BaseRxActivity;
import com.hxxc.user.app.utils.BtnUtils;
import com.hxxc.user.app.utils.CommonUtil;
import com.hxxc.user.app.utils.LogUtil;
import com.hxxc.user.app.utils.SPUtils;
import com.hxxc.user.app.utils.SharedPreUtils;
import com.hxxc.user.app.widget.CircleImageView;
import com.squareup.picasso.Picasso;

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

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by houwen.lai on 2016/9/27.
 * 搜索顾问页
 */

public class SearchFinancialActivity extends BaseRxActivity implements AdapterView.OnItemClickListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbar_title;

    @BindView(R.id.ed_search_financial)
    EditText ed_search_financial;
    @BindView(R.id.btn_search_financial)
    Button btn_search_financial;

    @BindView(R.id.listview_search_financial)
    ListView listview;

    private boolean FlagSearch = true;//搜索

    private String areaId;
    private Dialog dialog;
    private String fid;
    private String mobile;
    private String code;
    private String pass;
    private String pass_again;
    private String pCode;
    private TextView btn_sure;

    public static SearchFinancialActivity searchFinancialActivity = null;

    @Override
    public int getLayoutId() {
        return R.layout.financial_search_financial;
    }

    @Override
    public void initView() {
        searchFinancialActivity = this;
        mobile = getIntent().getStringExtra("mobile");
        code = getIntent().getStringExtra("code");
        pass = getIntent().getStringExtra("pass");
        pass_again = getIntent().getStringExtra("pass_again");
        pCode = getIntent().getStringExtra("pCode");
        toolbar_title.setText("搜索顾问");
        setSupportActionBar(toolbar);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        AppManager.getAppManager().addActivity(this);

        areaId = getIntent().getStringExtra("areaId");

        ed_search_financial.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    FlagSearch = false;
                    btn_search_financial.setText("搜索");
                    btn_delete_search.setText("");
                } else {
                    btn_search_financial.setText("取消");
                    btn_delete_search.setText("清除历史记录");
                    FlagSearch = true;
                    searchHistory();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        listview.setOnItemClickListener(this);

        view_delete = View.inflate(mContext, R.layout.financial_search_delete_his, null);
        btn_delete_search = (Button) view_delete.findViewById(R.id.btn_delete_search);
        view_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清除历史记录
                historyList.clear();
                SharedPreUtils.getInstanse().putKeyValue(mContext, UserInfoConfig.TypeSearchHistory, HXXCApplication.getInstance().getGson().toJson(historyList));
                searchHisttoryAdapter.notifyDataSetChanged();
            }
        });

        listview.addFooterView(view_delete);

        String history = SharedPreUtils.getInstanse().getKeyValue(mContext, UserInfoConfig.TypeSearchHistory);

        if (historyList == null) historyList = new ArrayList<String>();
        historyList.clear();
        if (!TextUtils.isEmpty(history))
            historyList = HXXCApplication.getInstance().getGson().fromJson(history, new TypeToken<List<String>>() {
            }.getType());

        searchHistory();

    }

    @Override
    public void initPresenter() {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.btn_search_financial)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search_financial://搜索
                if (BtnUtils.isFastDoubleClick()) {
                    if (btn_search_financial.getText().toString().contains("搜索")) {
                        FlagSearch = false;
                        searchFinancial(ed_search_financial.getText().toString().trim());
                    } else ed_search_financial.setText("");
                }

                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //搜索
        if (FlagSearch) {
            FlagSearch = false;
            ed_search_financial.setText(historyList.get(i));
            searchFinancial(historyList.get(i));

        } else {//理财师信息

            //是否选择该理财师做顾问

            LogUtil.d("顾问 mobile=" + mobile + "_code=" + code + "_pass=" + pass + "_pass_again=" + pass_again + "_pCode=" + pCode);

            Intent intent = new Intent(mContext, DialogBindingFinancial.class);
            intent.putExtra("mobile", mobile);
            intent.putExtra("code", code);
            intent.putExtra("pass", pass);
            intent.putExtra("pass_again", pass_again);
            intent.putExtra("pCode", pCode);
            intent.putExtra("fid", "" + searchFinancialAdapter.getAdapterListData().get(i).getFid());
            intent.putExtra("fname", "" + searchFinancialAdapter.getAdapterListData().get(i).getFname());
            intent.putExtra("from", getIntent().getIntExtra("from",-1));
            mContext.startActivity(intent);
//            fid = "" + searchFinancialAdapter.getAdapterListData().get(i).getFid();
//            showMyDialog();
        }
    }

    private void showMyDialog() {
        if (dialog == null) {
            dialog = new Dialog(mContext, R.style.loadingDialogTheme);
            View inflate = View.inflate(mContext, R.layout.dialog_hint, null);
            TextView tv_des = (TextView) inflate.findViewById(R.id.tv_des);
            inflate.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (null != dialog) {
                        dialog.dismiss();
                    }
                }
            });
            tv_des.setText("确认绑定该顾问作为您的理财师?");
            btn_sure = (TextView) inflate.findViewById(R.id.btn_sure);
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btn_sure.setEnabled(false);
                    doRegister();
                }
            });
            dialog.setContentView(inflate);
        }
        dialog.show();
    }

    private void doRegister() {
        Api.getClient().getRegister(mobile, code, pass, pass_again, fid, pCode).compose(RxApiThread.convert()).
                subscribe(new BaseSubscriber<UserInfo>(this) {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        btn_sure.setEnabled(true);
                        dialog.dismiss();
                        Api.uid = userInfo.getUid() + "";
                        Api.token = userInfo.getToken();
                        SPUtils.geTinstance().setLoginCache(userInfo.getUid() + "", userInfo.getToken(), mobile, pass);
                        // 获取用户信息
                        Midhandler.getUserInfo();
                        // 获取理财师信息
                        Midhandler.getFinanceInfo();
                        EventBus.getDefault().post(new MainEvent(3));
                        startActivity(new Intent(SearchFinancialActivity.this, MainActivity2.class));
                    }

                    @Override
                    public void onFail(String fail) {
                        btn_sure.setEnabled(true);
                        dialog.dismiss();
                    }
                });
    }

    public void searchFinancial(String text) {
        //请求数据
//        searchHisttoryAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(text)) historyList.add(0, text);

        SharedPreUtils.getInstanse().putKeyValue(mContext, UserInfoConfig.TypeSearchHistory, HXXCApplication.getInstance().getGson().toJson(historyList));

        Api.getClient().getFpList(UserInfoConfig.ShowType_register, "", text, 1, 10).compose(RxApiThread.convert()).
                subscribe(new BaseSubscriber<List<AdviserBean>>(mContext) {
                    @Override
                    public void onSuccess(List<AdviserBean> adviserBeen) {
                        setSearchFinancialAdapter(adviserBeen);
                    }

                    @Override
                    public void onFail(String fail) {
                        btn_delete_search.setText("没有相关顾问");
                    }
                });
    }

    private String[] history = new String[]{"王小闲1", "王小闲2", "王小闲3"};
    SearchFinancialHisttoryAdapter searchHisttoryAdapter;
    private List<String> historyList;
    private View view_delete;
    private Button btn_delete_search;

    /**
     * 历史搜索记录
     */
    public void searchHistory() {

        LogUtil.d("搜索顾问" + HXXCApplication.getInstance().getGson().toJson(historyList));
        if (null == searchHisttoryAdapter) {
            searchHisttoryAdapter = new SearchFinancialHisttoryAdapter(mContext, historyList, R.layout.financial_search_item);
        }
        listview.setAdapter(searchHisttoryAdapter);
    }

    /**
     * 搜索历史
     */
    public class SearchFinancialHisttoryAdapter extends CommonAdapter<String> {

        public SearchFinancialHisttoryAdapter(Context context, List<String> list, int layoutId) {
            super(context, list, layoutId);
        }

        @Override
        public void convert(ViewHolder helper, String item, int position) {
            super.convert(helper, item, position);
            if (position % 2 == 1) {
                helper.getConvertView().setBackgroundColor(Color.parseColor("#FaFaFa"));
            } else helper.getConvertView().setBackgroundColor(Color.WHITE);

            helper.setText(R.id.tv_search_financial_name, item);

        }
    }

    SearchFinancialAdapter searchFinancialAdapter;

    public void setSearchFinancialAdapter(List<AdviserBean> list) {
        if (list != null && list.size() > 0)
            btn_delete_search.setText("");
        else btn_delete_search.setText("没有相关顾问");
        searchFinancialAdapter = new SearchFinancialAdapter(mContext, list, R.layout.adapter_finance_item);
        listview.setAdapter(searchFinancialAdapter);
    }

    /**
     * 搜索理财师
     */
    public class SearchFinancialAdapter extends CommonAdapter<AdviserBean> {

        public SearchFinancialAdapter(Context context, List<AdviserBean> list, int layoutId) {
            super(context, list, layoutId);

        }

        @Override
        public void convert(ViewHolder helper, AdviserBean item, int position) {
            super.convert(helper, item, position);

            LinearLayout linear_binding_financial = helper.getView(R.id.linear_binding_financial);

            TextView tv_recommend = helper.getView(R.id.tv_recommend);
            View line_recommend = helper.getView(R.id.line_recommend);

            CircleImageView img_icon = helper.getView(R.id.img_icon);

            TextView name_text = helper.getView(R.id.name_text);
            TextView service_count_text = helper.getView(R.id.service_count_text);
            TextView finance_no_text = helper.getView(R.id.finance_no_text);
            TextView amout_text = helper.getView(R.id.amout_text);

            ImageView is_check_img = helper.getView(R.id.is_check_img);

            if (position == 0) {
                tv_recommend.setVisibility(View.VISIBLE);
                line_recommend.setVisibility(View.VISIBLE);
            } else {
                tv_recommend.setVisibility(View.GONE);
                line_recommend.setVisibility(View.GONE);
            }
            is_check_img.setVisibility(View.GONE);

            if (position % 2 == 0)
                linear_binding_financial.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            else
                linear_binding_financial.setBackgroundColor(mContext.getResources().getColor(R.color.white_fafa));

            Picasso.with(mContext)
                    .load(item.getIcon())
                    .placeholder(R.drawable.default_financier_pic)
                    .error(R.drawable.default_financier_pic)
                    .into(img_icon);

            name_text.setText(item.getFname());
            finance_no_text.setText(item.getFinancialno());
            service_count_text.setText(item.getServicecount() + "位");
            amout_text.setText(CommonUtil.moneyType(item.getInvestmentamout().doubleValue() / 10000f) + "万");
        }
    }
}


text:
package leap.oauth2.webapp.token.at;

import leap.web.Request;
import leap.web.security.authc.AuthenticationContext;

public interface AccessTokenStore {

    AccessToken loadAccessToken(Request request, AuthenticationContext context);

    void saveAccessToken(Request request, AuthenticationContext context, AccessToken at);

    AccessToken refreshAndSaveAccessToken(Request request, AuthenticationContext context, AccessToken old);

    AccessToken loadAccessTokenByClientCredentials(String clientId, String clientSecret);

    AccessToken loadAccessTokenByPassword(String clientId, String clientSecret, String username, String password);

    AccessToken refreshAccessToken(AccessToken old);

}


text:
'use strict';

angular.module('geonotes', [
  'ngRoute',
  'ui.bootstrap',
  'geonoteControllers'
]).config(function ($routeProvider) {
  $routeProvider
  .when('/', {
     templateUrl: 'static/partials/main_offline.html',
     controller: 'CreateNoteController'
  })
  .otherwise({
    redirectTo: '/'
  });
});


text:
var cbpAnimatedHeader = (function() {

	var docElem = document.documentElement,
		header = $('.navbar-fixed-top'),
		didScroll = false,
		changeHeaderOn = 50;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
            $(header).addClass('navbar-shrink');
		}
		else {
            $(header).removeClass('navbar-shrink');
		}
		didScroll = false;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	init();

})();


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>cn.net.openid.jos</groupId>
		<artifactId>jos-tools</artifactId>
		<version>1.2-SNAPSHOT</version>
	</parent>
	<groupId>cn.net.openid.jos.jos-tools</groupId>
	<artifactId>db-migration</artifactId>
	<packaging>pom</packaging>
	<name>Java OpenID Server - Tools - Database Migration</name>
	<modules>
		<module>1.0-alpha1_1.0-alpha3</module>
	</modules>
	<reporting>
		<outputDirectory>../../target/site/${project.artifactId}/</outputDirectory>
	</reporting>
</project>


text:
========
ThriftPy
========

.. image:: http://img.shields.io/travis/eleme/thriftpy/develop.svg?style=flat
   :target: https://travis-ci.org/eleme/thriftpy

.. image:: http://img.shields.io/github/release/eleme/thriftpy.svg?style=flat
   :target: https://github.com/eleme/thriftpy/releases

.. image:: http://img.shields.io/pypi/v/thriftpy.svg?style=flat
   :target: https://pypi.python.org/pypi/thriftpy

.. image:: http://img.shields.io/pypi/dm/thriftpy.svg?style=flat
   :target: https://pypi.python.org/pypi/thriftpy

ThriftPy is a pure python implementation of
`Apache Thrift <http://thrift.apache.org/>`_ in a pythonic way.

Documentation: https://thriftpy.readthedocs.org/

Installation
============

Install with pip.

.. code:: bash

    $ pip install thriftpy

You may also install cython first to build cython extension locally.

.. code:: bash

    $ pip install cython thriftpy

Code Demo
=========

ThriftPy make it super easy to write server/client code with thrift. Let's
checkout this simple pingpong service demo.

We need a 'pingpong.thrift' file:

::

    service PingPong {
        string ping(),
    }

Then we can make a server:

.. code:: python

    import thriftpy
    pingpong_thrift = thriftpy.load("pingpong.thrift", module_name="pingpong_thrift")

    from thriftpy.rpc import make_server

    class Dispatcher(object):
        def ping(self):
            return "pong"

    server = make_server(pingpong_thrift.PingPong, Dispatcher(), '127.0.0.1', 6000)
    server.serve()

And a client:

.. code:: python

    import thriftpy
    pingpong_thrift = thriftpy.load("pingpong.thrift", module_name="pingpong_thrift")

    from thriftpy.rpc import make_client

    client = make_client(pingpong_thrift.PingPong, '127.0.0.1', 6000)
    client.ping()

See, it's that easy!

You can refer to 'examples' and 'tests' directory in source code for more
usage examples.

Features
========

Currently ThriftPy have these features (also advantages over the upstream
python lib):

- Supports python2.6+, python3.3+, pypy and pypy3.

- Pure python implementation. No longer need to compile & install the 'thrift'
  package. All you need is thriftpy and thrift file.

- Compatible with Apache Thrift. You can use ThriftPy together with the
  official implementation servers and clients, such as a upstream server with
  a thriftpy client or the opposite.

  Currently implemented protocols and transports:

  * binary protocol (python and cython)

  * buffered transport (python & cython)

  * tornado server and client (with tornado 4.0)

  * framed transport

  * json protocol

- Can directly load thrift file as module, the sdk code will be generated on
  the fly.

  For example, ``pingpong_thrift = thriftpy.load("pingpong.thrift", module_name="pingpong_thrift")``
  will load 'pingpong.thrift' as 'pingpong_thrift' module.

  Or, when import hook enabled by ``thriftpy.install_import_hook()``, you can
  directly use ``import pingpong_thrift`` to import the 'pingpong.thrift' file
  as module, you may also use ``from pingpong_thrift import PingService`` to
  import specific object from the thrift module.

- Easy RPC server/client setup.

Contribute
==========

1. Fork the repo and make changes.

2. Write a test which shows a bug was fixed or the feature works as expected.

3. Make sure ``travis-ci`` or ``tox`` tests succeed.

4. Send pull request.

Contributors
============

https://github.com/eleme/thriftpy/graphs/contributors

Changelog
=========

https://github.com/eleme/thriftpy/blob/master/CHANGES.rst


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

class Cache_Apc extends Proxima_Cache_Apc {}


text:
package org.bitcoins.protocol.rpc.bitcoincore.networking

/**
 * Created by Tom on 1/5/2016.
 */
trait NetworkInfo {
  def version : Int
  def subVersion : String
  def protocolVersion: Int
  def localServices : String
  def timeOffSet : Int
  def connections : Int
  def networks : Seq[NetworkConnections]
  def relayFee : Double
  def localAddresses : Seq[Int]
}

//TODO: Change localaddresses from array[string] to array of connections. see https://bitcoin.org/en/developer-reference#getnetworkinfo

case class NetworkInfoImpl(version : Int, subVersion : String, protocolVersion : Int, localServices : String,
  timeOffSet : Int, connections : Int, networks : Seq[NetworkConnections], relayFee : Double, localAddresses: Seq[Int]) extends NetworkInfo