text:
from django.db import connections, models, router
from django.db.models.deletion import Collector
from django.utils import encoding

import bleach

import amo.models
from amo import urlresolvers
from . import utils

class Translation(amo.models.ModelBase):
    """
    Translation model.

    Use :class:`translations.fields.TranslatedField` instead of a plain foreign
    key to this model.
    """

    autoid = models.AutoField(primary_key=True)
    id = models.IntegerField()
    locale = models.CharField(max_length=10)
    localized_string = models.TextField(null=True)
    localized_string_clean = models.TextField(null=True)

    class Meta:
        db_table = 'translations'
        unique_together = ('id', 'locale')

    def __unicode__(self):
        return self.localized_string and unicode(self.localized_string) or ''

    def __nonzero__(self):
        # __nonzero__ is called to evaluate an object in a boolean context.  We
        # want Translations to be falsy if their string is empty.
        return (bool(self.localized_string) and
                bool(self.localized_string.strip()))

    def __eq__(self, other):
        # Django implements an __eq__ that only checks pks.  We need to check
        # the strings if we're dealing with existing vs. unsaved Translations.
        return self.__cmp__(other) == 0

    def __cmp__(self, other):
        if hasattr(other, 'localized_string'):
            return cmp(self.localized_string, other.localized_string)
        else:
            return cmp(self.localized_string, other)

    def clean(self):
        if self.localized_string:
            self.localized_string = self.localized_string.strip()

    def save(self, **kwargs):
        self.clean()
        return super(Translation, self).save(**kwargs)

    def delete(self, using=None):
        # FIXME: if the Translation is the one used as default/fallback,
        # then deleting it will mean the corresponding field on the related
        # model will stay empty even if there are translations in other
        # languages!
        cls = self.__class__
        using = using or router.db_for_write(cls, instance=self)
        # Look for all translations for the same string (id=self.id) except the
        # current one (autoid=self.autoid).
        qs = cls.objects.filter(id=self.id).exclude(autoid=self.autoid)
        if qs.using(using).exists():
            # If other Translations for the same id exist, we just need to
            # delete this one and *only* this one, without letting Django
            # collect dependencies (it'd remove the others, which we want to
            # keep).
            assert self._get_pk_val() is not None
            collector = Collector(using=using)
            collector.collect([self], collect_related=False)
            # In addition, because we have FK pointing to a non-unique column,
            # we need to force MySQL to ignore constraints because it's dumb
            # and would otherwise complain even if there are remaining rows
            # that matches the FK.
            with connections[using].constraint_checks_disabled():
                collector.delete()
        else:
            # If no other Translations with that id exist, then we should let
            # django behave normally. It should find the related model and set
            # the FKs to NULL.
            return super(Translation, self).delete(using=using)

    delete.alters_data = True

    @classmethod
    def _cache_key(cls, pk, db):
        # Hard-coding the class name here so that subclasses don't try to cache
        # themselves under something like "o:translations.purifiedtranslation".
        #
        # Like in ModelBase, we avoid putting the real db in the key because it
        # does us more harm than good.
        key_parts = ('o', 'translations.translation', pk, 'default')
        return ':'.join(map(encoding.smart_unicode, key_parts))

    @classmethod
    def new(cls, string, locale, id=None):
        """
        Jumps through all the right hoops to create a new translation.

        If ``id`` is not given a new id will be created using
        ``translations_seq``.  Otherwise, the id will be used to add strings to
        an existing translation.

        To increment IDs we use a setting on MySQL. This is to support multiple
        database masters -- it's just crazy enough to work! See bug 756242.
        """
        if id is None:
            # Get a sequence key for the new translation.
            cursor = connections['default'].cursor()
            cursor.execute("""UPDATE translations_seq
                              SET id=LAST_INSERT_ID(id + @@global.auto_increment_increment)""")

            # The sequence table should never be empty. But alas, if it is,
            # let's fix it.
            if not cursor.rowcount > 0:
                cursor.execute("""INSERT INTO translations_seq (id)
                                  VALUES(LAST_INSERT_ID(id + @@global.auto_increment_increment))""")

            cursor.execute('SELECT LAST_INSERT_ID()')
            id = cursor.fetchone()[0]

        # Update if one exists, otherwise create a new one.
        q = {'id': id, 'locale': locale}
        try:
            trans = cls.objects.get(**q)
            trans.localized_string = string
        except cls.DoesNotExist:
            trans = cls(localized_string=string, **q)

        return trans

class PurifiedTranslation(Translation):
    """Run the string through bleach to get a safe, linkified version."""

    class Meta:
        proxy = True

    def __unicode__(self):
        if not self.localized_string_clean:
            self.clean()
        return unicode(self.localized_string_clean)

    def __html__(self):
        return unicode(self)

    def clean(self):
        from amo.utils import clean_nl
        super(PurifiedTranslation, self).clean()
        cleaned = bleach.clean(self.localized_string)
        linkified = bleach.linkify(cleaned, nofollow=True,
                filter_url=urlresolvers.get_outgoing_url)
        self.localized_string_clean = clean_nl(linkified).strip()

    def __truncate__(self, length, killwords, end):
        return utils.truncate(unicode(self), length, killwords, end)

class LinkifiedTranslation(PurifiedTranslation):
    """Run the string through bleach to get a linkified version."""

    class Meta:
        proxy = True

    def clean(self):
        linkified = bleach.linkify(self.localized_string,
                filter_url=urlresolvers.get_outgoing_url)
        clean = bleach.clean(linkified, tags=['a'],
                             attributes={'a': ['href', 'rel']})
        self.localized_string_clean = clean

class TranslationSequence(models.Model):
    """
    The translations_seq table, so syncdb will create it during testing.
    """
    id = models.IntegerField(primary_key=True)

    class Meta:
        db_table = 'translations_seq'

def delete_translation(obj, fieldname):
    field = obj._meta.get_field(fieldname)
    trans_id = getattr(obj, field.attname)
    obj.update(**{field.name: None})
    if trans_id:
        Translation.objects.filter(id=trans_id).delete()


text:
class Array
  alias_method :value_map, :map
end

class Object
  def value_map
    yield self
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System.Security.Cryptography;
using ElectronicCash;

namespace BitCommitment
{
    /// <summary>
    /// A class to perform bit commitment. It does not care what the input is; it's just a
    /// facility for exchanging bit commitment messages. Based on Bruce Schneier's one-way
    /// function method for committing bits. See p.87 of `Applied Cryptography`.
    /// </summary>
    public class BitCommitmentProvider
    {
        public byte[] AliceRandBytesR1 { get; set; }
        public byte[] AliceRandBytesR2 { get; set; }
        public byte[] AliceBytesToCommitB { get; set; }

        public BitCommitmentProvider(byte[] randBytesR1,
            byte[] randBytesR2,
            byte[] bytesToCommit)
        {
            AliceRandBytesR1 = randBytesR1;
            AliceRandBytesR2 = randBytesR2;
            AliceBytesToCommitB = bytesToCommit;
        }

        /// <summary>
        /// <para>Returns a byte array containing the one way function computed for the triple
        /// (R_1, R_2, B) where R_1 is AliceRandBytesR1, R_2 is AliceRandBytesR2, and B is the byte(s)
        /// Alice wants to commit.</para>
        ///
        /// <para>Commitment by one way function works like this:
        /// <list type="number">
        ///     <item>
        ///         <description>Alice generates two random bit strings, R1, R2</description>
        ///     </item>
        ///     <item>
        ///         <description>Alice then creates a message consisting of her random strings and the "bit" she
        ///                     wishes to commit, e.g. the triple (R1, R2, b). We use string concatenation.</description>
        ///     </item>
        ///     <item>
        ///         <description>Alice computes the one way function on this message (we use SHA256), and sends the hash as well as R1 to Bob.</description>
        ///     </item>
        ///     <item>
        ///         <description>This transmission is evidence of commitment. Bob cannot invert the hash, so the message is secure.</description>
        ///     </item>
        ///     <item>
        ///         <description>Then, to verify, Alice sends Bob the original message (R1, R2, b).</description>
        ///     </item>
        ///     <item>
        ///         <description>Bob then computes the one way function on the message and compares it and R1 with the hash and random value received from Alice. If they match, the "bit" is valid</description>
        ///     </item>
        /// </list></para>
        ///
        /// <para>
        ///     Source: 'Applied Cryptography' by Schneier, 2nd edition. See page 87
        /// </para>
        /// </summary>
        /// <returns>The SHA256 hash of the message</returns>
        public byte[] BitCommitMessage()
        {
            var r1 = Helpers.GetString(AliceRandBytesR1);
            var r2 = Helpers.GetString(AliceRandBytesR2);
            var b = Helpers.GetString(AliceBytesToCommitB);
            var hashProvider = SHA256.Create();

            var hashedMessage = hashProvider.ComputeHash(Helpers.GetBytes(r1 + r2 + b));

            return (hashedMessage);
        }
    }
}


text:
Server: CERN/3.0A
Date: Tue, 14 Jan 1997 21:48:08 GMT
Content-Type: text/html
Content-Length: 869
Last-Modified: Tue, 14 Jan 1997 03:12:08 GMT

<title>Real/Expr -- Source Codes</title>

<!WA0>

<!WA1>Source Codes

<!WA3> Sorry,
temporary, FTP is not available.

<!WA4><!WA5> Expr.tar.gz The old
version of

Real/Expr. (g++-2.7.2)

The new version is coming soon. Please, send your e-mail address to
get it via e-mailing to
<!WA6>ouchi@simulation.nyu.edu.
Thank you.

[ <!WA7>Real/Expr Homepage ]

<address>
Should you have any comment, send an e-mail to
<!WA8>
ouchi@simulation.nyu.edu
</address>


text:
<!--
 * Copyright (c) 2011 The Chromium Authors. All rights reserved.  Use of this
 * source code is governed by a BSD-style license that can be found in the
 * LICENSE file.
-->
<html>
<head>
<script>
  chrome.test.runTests([
    function createIncognitoWindow() {
      chrome.windows.create({ url: "about:blank", incognito: true },
                            function(window) {
        chrome.test.assertEq(window, undefined);
        chrome.test.notifyPass();
      });
    }
  ]);
</script>
</head>
</html>


text:
"""RCS interface module.

Defines the class RCS, which represents a directory with rcs version
files and (possibly) corresponding work files.

"""

import fnmatch
import os
import regsub
import string
import tempfile

class RCS:

    """RCS interface class (local filesystem version).

    An instance of this class represents a directory with rcs version
    files and (possible) corresponding work files.

    Methods provide access to most rcs operations such as
    checkin/checkout, access to the rcs metadata (revisions, logs,
    branches etc.) as well as some filesystem operations such as
    listing all rcs version files.

    XXX BUGS / PROBLEMS

    - The instance always represents the current directory so it's not
    very useful to have more than one instance around simultaneously

    """

    # Characters allowed in work file names
    okchars = string.ascii_letters + string.digits + '-_=+'

    def __init__(self):
        """Constructor."""
        pass

    def __del__(self):
        """Destructor."""
        pass

    # --- Informational methods about a single file/revision ---

    def log(self, name_rev, otherflags = ''):
        """Return the full log text for NAME_REV as a string.

        Optional OTHERFLAGS are passed to rlog.

        """
        f = self._open(name_rev, 'rlog ' + otherflags)
        data = f.read()
        status = self._closepipe(f)
        if status:
            data = data + "%s: %s" % status
        elif data[-1] == '\n':
            data = data[:-1]
        return data

    def head(self, name_rev):
        """Return the head revision for NAME_REV"""
        dict = self.info(name_rev)
        return dict['head']

    def info(self, name_rev):
        """Return a dictionary of info (from rlog -h) for NAME_REV

        The dictionary's keys are the keywords that rlog prints
        (e.g. 'head' and its values are the corresponding data
        (e.g. '1.3').

        XXX symbolic names and locks are not returned

        """
        f = self._open(name_rev, 'rlog -h')
        dict = {}
        while 1:
            line = f.readline()
            if not line: break
            if line[0] == '\t':
                # XXX could be a lock or symbolic name
                # Anything else?
                continue
            i = string.find(line, ':')
            if i > 0:
                key, value = line[:i], string.strip(line[i+1:])
                dict[key] = value
        status = self._closepipe(f)
        if status:
            raise IOError, status
        return dict

    # --- Methods that change files ---

    def lock(self, name_rev):
        """Set an rcs lock on NAME_REV."""
        name, rev = self.checkfile(name_rev)
        cmd = "rcs -l%s %s" % (rev, name)
        return self._system(cmd)

    def unlock(self, name_rev):
        """Clear an rcs lock on NAME_REV."""
        name, rev = self.checkfile(name_rev)
        cmd = "rcs -u%s %s" % (rev, name)
        return self._system(cmd)

    def checkout(self, name_rev, withlock=0, otherflags=""):
        """Check out NAME_REV to its work file.

        If optional WITHLOCK is set, check out locked, else unlocked.

        The optional OTHERFLAGS is passed to co without
        interpretation.

        Any output from co goes to directly to stdout.

        """
        name, rev = self.checkfile(name_rev)
        if withlock: lockflag = "-l"
        else: lockflag = "-u"
        cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name)
        return self._system(cmd)

    def checkin(self, name_rev, message=None, otherflags=""):
        """Check in NAME_REV from its work file.

        The optional MESSAGE argument becomes the checkin message
        (default "<none>" if None); or the file description if this is
        a new file.

        The optional OTHERFLAGS argument is passed to ci without
        interpretation.

        Any output from ci goes to directly to stdout.

        """
        name, rev = self._unmangle(name_rev)
        new = not self.isvalid(name)
        if not message: message = "<none>"
        if message and message[-1] != '\n':
            message = message + '\n'
        lockflag = "-u"
        if new:
            f = tempfile.NamedTemporaryFile()
            f.write(message)
            f.flush()
            cmd = 'ci %s%s -t%s %s %s' % \
                  (lockflag, rev, f.name, otherflags, name)
        else:
            message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message)
            cmd = 'ci %s%s -m"%s" %s %s' % \
                  (lockflag, rev, message, otherflags, name)
        return self._system(cmd)

    # --- Exported support methods ---

    def listfiles(self, pat = None):
        """Return a list of all version files matching optional PATTERN."""
        files = os.listdir(os.curdir)
        files = filter(self._isrcs, files)
        if os.path.isdir('RCS'):
            files2 = os.listdir('RCS')
            files2 = filter(self._isrcs, files2)
            files = files + files2
        files = map(self.realname, files)
        return self._filter(files, pat)

    def isvalid(self, name):
        """Test whether NAME has a version file associated."""
        namev = self.rcsname(name)
        return (os.path.isfile(namev) or
                os.path.isfile(os.path.join('RCS', namev)))

    def rcsname(self, name):
        """Return the pathname of the version file for NAME.

        The argument can be a work file name or a version file name.
        If the version file does not exist, the name of the version
        file that would be created by "ci" is returned.

        """
        if self._isrcs(name): namev = name
        else: namev = name + ',v'
        if os.path.isfile(namev): return namev
        namev = os.path.join('RCS', os.path.basename(namev))
        if os.path.isfile(namev): return namev
        if os.path.isdir('RCS'):
            return os.path.join('RCS', namev)
        else:
            return namev

    def realname(self, namev):
        """Return the pathname of the work file for NAME.

        The argument can be a work file name or a version file name.
        If the work file does not exist, the name of the work file
        that would be created by "co" is returned.

        """
        if self._isrcs(namev): name = namev[:-2]
        else: name = namev
        if os.path.isfile(name): return name
        name = os.path.basename(name)
        return name

    def islocked(self, name_rev):
        """Test whether FILE (which must have a version file) is locked.

        XXX This does not tell you which revision number is locked and
        ignores any revision you may pass in (by virtue of using rlog
        -L -R).

        """
        f = self._open(name_rev, 'rlog -L -R')
        line = f.readline()
        status = self._closepipe(f)
        if status:
            raise IOError, status
        if not line: return None
        if line[-1] == '\n':
            line = line[:-1]
        return self.realname(name_rev) == self.realname(line)

    def checkfile(self, name_rev):
        """Normalize NAME_REV into a (NAME, REV) tuple.

        Raise an exception if there is no corresponding version file.

        """
        name, rev = self._unmangle(name_rev)
        if not self.isvalid(name):
            raise os.error, 'not an rcs file %s' % `name`
        return name, rev

    # --- Internal methods ---

    def _open(self, name_rev, cmd = 'co -p', rflag = '-r'):
        """INTERNAL: open a read pipe to NAME_REV using optional COMMAND.

        Optional FLAG is used to indicate the revision (default -r).

        Default COMMAND is "co -p".

        Return a file object connected by a pipe to the command's
        output.

        """
        name, rev = self.checkfile(name_rev)
        namev = self.rcsname(name)
        if rev:
            cmd = cmd + ' ' + rflag + rev
        return os.popen("%s %s" % (cmd, `namev`))

    def _unmangle(self, name_rev):
        """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple.

        Raise an exception if NAME contains invalid characters.

        A NAME_REV argument is either NAME string (implying REV='') or
        a tuple of the form (NAME, REV).

        """
        if type(name_rev) == type(''):
            name_rev = name, rev = name_rev, ''
        else:
            name, rev = name_rev
        for c in rev:
            if c not in self.okchars:
                raise ValueError, "bad char in rev"
        return name_rev

    def _closepipe(self, f):
        """INTERNAL: Close PIPE and print its exit status if nonzero."""
        sts = f.close()
        if not sts: return None
        detail, reason = divmod(sts, 256)
        if reason == 0: return 'exit', detail   # Exit status
        signal = reason&0x7F
        if signal == 0x7F:
            code = 'stopped'
            signal = detail
        else:
            code = 'killed'
        if reason&0x80:
            code = code + '(coredump)'
        return code, signal

    def _system(self, cmd):
        """INTERNAL: run COMMAND in a subshell.

        Standard input for the command is taken from /dev/null.

        Raise IOError when the exit status is not zero.

        Return whatever the calling method should return; normally
        None.

        A derived class may override this method and redefine it to
        capture stdout/stderr of the command and return it.

        """
        cmd = cmd + " </dev/null"
        sts = os.system(cmd)
        if sts: raise IOError, "command exit status %d" % sts

    def _filter(self, files, pat = None):
        """INTERNAL: Return a sorted copy of the given list of FILES.

        If a second PATTERN argument is given, only files matching it
        are kept.  No check for valid filenames is made.

        """
        if pat:
            def keep(name, pat = pat):
                return fnmatch.fnmatch(name, pat)
            files = filter(keep, files)
        else:
            files = files[:]
        files.sort()
        return files

    def _remove(self, fn):
        """INTERNAL: remove FILE without complaints."""
        try:
            os.unlink(fn)
        except os.error:
            pass

    def _isrcs(self, name):
        """INTERNAL: Test whether NAME ends in ',v'."""
        return name[-2:] == ',v'


text:
<manifest
    package="com.tundem.actionitembadge.library">

</manifest>


text:
package com.paratussoftware;

import org.opencv.core.Core;

public class Grimoire {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static void main(final String[] args) {
        if (args.length == 3) {
            Settings.PORT_NUMBER = Integer.valueOf(args[0]);
            Settings.IMAGE_WIDTH = Integer.valueOf(args[1]);
            Settings.IMAGE_HEIGHT = Integer.valueOf(args[2]);
        } else {
            System.out.println("Invalid Arguments. Expected: port image_width image_height");
            System.exit(1);
        }
    }
}


text:
<?php

namespace Unicodeveloper\Mention\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class ApiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param $type
     * @param Request $request
     * @return Response
     */
    public function index($type, Request $request)
    {
        try {
            $resultColumns = [];
            $query = $request->get('q');
            $column = $request->get('c');

            $model = app()->make(config('mentions.' . $type));

            $records = $model->where($column, 'LIKE', "%$query%")
                             ->get([$column]);

            foreach ($records as $record) {
                $resultColumns[] = $record->$column;
            }

            return response()->json($resultColumns);
        } catch (\ReflectionException $e) {
            return response()->json('Not Found', 404);
        }
    }
}


text:
<application>
  <component name="PluginManagerConfigurable" installedProportions="0.5919811" />
</application>


text:
layout: default
title: Basic overcoming the monster plot
---

##Overcoming the Monster

A hero learns of a great evil overshadowing the land (sometimes not his own land). He gets special equipment, weapons, or skills, then heads out and defeats the evil, freeing the land.
The first half of one of the oldest known stories, The Epic of Gilgamesh, is set in this form. So is the first James Bond movie Dr. No, and of course a wealth of stories in between. Also the base for many video games, e.g. any Super Mario jump'n'run. Here's the gist of how the stages run:

###Anticipation Stage and Call

The fearsome Monster makes his presence known, often from "a great distance" although occasionally more up close and personal. Its nature is base and vile, a picture of the dark side of humanity. To drive this home, it is "highly alarming in its appearance and behaviour"... treacherous and deadly, ugly or ill-formed, and, often, "something about its nature [is] mysterious... hard to define" (elusive, shapeless, nightmarish).
The Monster may be humanoid, animal, or a combination of both (e.g., the Minotaur). If it's humanoid, it will still have bestial qualities, as well as some deformity or abnormality that shows it as not quite human (abnormal size counts). If it's physically an animal, it will be "invested with attributes no animal in nature would possess, such as a peculiar cunning or malevolence" - thus partly human. As for combinations: We tend to imagine creatures composed of things we know, such as the dragon with "a reptilian body, a bat's wings and the head of a giant toad or lizard." (Hey, even when we craft eldritch abominations we give them a squid's tentacles, right?)

During the course of the story, the Monster may take on any of three basic roles:
|Predator: Prowls around, trying to find victims. The Devil goes about like a roaring lion, seeking whom he may devour.
|Holdfast: Zealously guards a Treasure or a Princess. Very suspicious of any strangers, but may be sleeping when the Hero comes to claim it.
|Avenger: "When its guardianship is in any way challenged," the Monster rushes out to find and destroy those who've taken its Treasure.

All three are found in the pattern story "Jack and the Beanstalk": First it's "Fee fi fo fum, I smell the blood of an Englishman," then it's the sleeping giant guarding his treasures, and finally it's the angry giant pursuing Jack across the clouds and down the beanstalk.

Anyway. So the Monster poses a grave threat. Who's going to stop him? The Hero, who receives his Call to Adventure. If he's smart, he heads out immediately (since The Call Knows Where You Live!) - and after all, who else is gonna kill that thing?

###Dream Stage

The Hero prepares for battle while moving closer to the Monster (either he's heading out, or the Monster's approaching his home). But the danger is still "comfortably remote" and everything seems to be working out okay.

###Frustration Stage

The Monster shows up and shows off, "in all his awesome power." There's no contest here: No way the Hero can beat a thing this strong! At this point, the Hero seems to be "slipping into the monster's power" and "may even fall helplessly into the monster's clutches."

###Nightmare Stage

Time for the climactic battle. The odds seem to be against our Hero even surviving this fight. But, of course, we know how these things turn out, right?

###The Thrilling Escape from Death, and Death of the Monster

The Monster's power is broken, and it dies; the people who had been under its power are liberated; the Hero emerges victorious.
To symbolically complete the tale, the Hero receives three things:
* A treasure (an inheritance counts)
* A kingdom (something to rule over, e.g., a cook hero might get his own restaurant)
* A Princess (or, in the case of a female Hero, a Prince - either way, it's the ultimate mate, the Hero's other half)

And they all lived Happily Ever After.


text:
pub mod filterdb;
pub mod rpc_filter;


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_EXPRESSIONS_SVECDVECINNEREXPR_H_
#define _BLAZE_MATH_EXPRESSIONS_SVECDVECINNEREXPR_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <blaze/math/Aliases.h>
#include <blaze/math/constraints/ColumnVector.h>
#include <blaze/math/constraints/DenseVector.h>
#include <blaze/math/constraints/RowVector.h>
#include <blaze/math/constraints/SparseVector.h>
#include <blaze/math/Exception.h>
#include <blaze/math/expressions/DenseVector.h>
#include <blaze/math/expressions/SparseVector.h>
#include <blaze/math/traits/MultTrait.h>
#include <blaze/system/MacroDisable.h>
#include <blaze/util/FunctionTrace.h>
#include <blaze/util/Types.h>
#include <blaze/util/typetraits/RemoveReference.h>

namespace blaze {

//=================================================================================================
//
//  GLOBAL BINARY ARITHMETIC OPERATORS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Multiplication operator for the scalar product (inner product) of a sparse and a
//        dense vector (\f$ s=\vec{a}*\vec{b} \f$).
// \ingroup sparse_vector
//
// \param lhs The left-hand side sparse vector for the inner product.
// \param rhs The right-hand side dense vector for the inner product.
// \return The scalar product.
// \exception std::invalid_argument Vector sizes do not match.
//
// This operator represents the scalar product (inner product) of a sparse vector and a dense
// vector:

   \code
   using blaze::columnVector;
   using blaze::rowVector;

   blaze::CompressedVector<double,rowVector> a;
   blaze::DynamicVector<double,columnVector> b;
   blaze::real res;
   // ... Resizing and initialization
   res = a * b;
   \endcode

// The operator returns a scalar value of the higher-order element type of the two involved
// vector element types \a VT1::ElementType and \a VT2::ElementType. Both vector types \a VT1
// and \a VT2 as well as the two element types \a VT1::ElementType and \a VT2::ElementType
// have to be supported by the MultTrait class template.\n
// In case the current sizes of the two given vectors don't match, a \a std::invalid_argument
// is thrown.
*/
template< typename VT1    // Type of the left-hand side sparse vector
        , typename VT2 >  // Type of the right-hand side dense vector
inline decltype(auto)
   operator*( const SparseVector<VT1,true>& lhs, const DenseVector<VT2,false>& rhs )
{
   BLAZE_FUNCTION_TRACE;

   using CT1      = CompositeType_t<VT1>;    // Composite type of the left-hand side sparse vector expression
   using CT2      = CompositeType_t<VT2>;    // Composite type of the right-hand side dense vector expression
   using XT1      = RemoveReference_t<CT1>;  // Auxiliary type for the left-hand side composite type
   using XT2      = RemoveReference_t<CT2>;  // Auxiliary type for the right-hand side composite type
   using ET1      = ElementType_t<XT1>;      // Element type of the left-hand side sparse vector expression
   using ET2      = ElementType_t<XT2>;      // Element type of the right-hand side dense vector expression
   using MultType = MultTrait_t<ET1,ET2>;    // Multiplication result type

   BLAZE_CONSTRAINT_MUST_BE_SPARSE_VECTOR_TYPE( VT1 );
   BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE ( VT2 );
   BLAZE_CONSTRAINT_MUST_BE_ROW_VECTOR_TYPE   ( VT1 );
   BLAZE_CONSTRAINT_MUST_BE_COLUMN_VECTOR_TYPE( VT2 );

   if( (~lhs).size() != (~rhs).size() ) {
      BLAZE_THROW_INVALID_ARGUMENT( "Vector sizes do not match" );
   }

   CT1 left ( ~lhs );
   CT2 right( ~rhs );

   auto element( left.begin() );
   auto end    ( left.end()   );

   MultType sp{};

   if( element != end ) {
      sp = element->value() * right[ element->index() ];
      ++element;
      for( ; element!=end; ++element )
         sp += element->value() * right[ element->index() ];
   }

   return sp;
}
//*************************************************************************************************

} // namespace blaze

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:top="-1.0px">
        <shape android:shape="rectangle">
            <solid android:color="@color/news_background_pressed_bl" />
            <stroke android:width="1.0px" android:color="@color/news_border_bl" />
            <corners android:radius="2.0dip" android:topLeftRadius="0.0dip" android:topRightRadius="0.0dip" android:bottomLeftRadius="2.0dip" android:bottomRightRadius="2.0dip" />
        </shape>
    </item><!-- pressed -->
    <item android:top="-1.0px">
        <shape android:shape="rectangle">
            <solid android:color="@color/news_background_bl" />
            <stroke android:width="1.0px" android:color="@color/news_border_bl" />
            <corners android:radius="2.0dip" android:topLeftRadius="0.0dip" android:topRightRadius="0.0dip" android:bottomLeftRadius="2.0dip" android:bottomRightRadius="2.0dip" />
        </shape>
    </item>
</selector>


text:
#ifndef WEBRTC_MODULES_AUDIO_PROCESSING_TEST_TEST_UTILS_H_
#define WEBRTC_MODULES_AUDIO_PROCESSING_TEST_TEST_UTILS_H_

#include <math.h>
#include <iterator>
#include <limits>
#include <string>
#include <vector>

#include "webrtc/base/constructormagic.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/common_audio/channel_buffer.h"
#include "webrtc/common_audio/wav_file.h"
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/modules/interface/module_common_types.h"

namespace webrtc {

static const AudioProcessing::Error kNoErr = AudioProcessing::kNoError;
#define EXPECT_NOERR(expr) EXPECT_EQ(kNoErr, (expr))

class RawFile final {
 public:
  explicit RawFile(const std::string& filename);
  ~RawFile();

  void WriteSamples(const int16_t* samples, size_t num_samples);
  void WriteSamples(const float* samples, size_t num_samples);

 private:
  FILE* file_handle_;

  RTC_DISALLOW_COPY_AND_ASSIGN(RawFile);
};

void WriteIntData(const int16_t* data,
                  size_t length,
                  WavWriter* wav_file,
                  RawFile* raw_file);

void WriteFloatData(const float* const* data,
                    int samples_per_channel,
                    int num_channels,
                    WavWriter* wav_file,
                    RawFile* raw_file);

// Exits on failure; do not use in unit tests.
FILE* OpenFile(const std::string& filename, const char* mode);

int SamplesFromRate(int rate);

void SetFrameSampleRate(AudioFrame* frame,
                        int sample_rate_hz);

template <typename T>
void SetContainerFormat(int sample_rate_hz,
                        int num_channels,
                        AudioFrame* frame,
                        rtc::scoped_ptr<ChannelBuffer<T> >* cb) {
  SetFrameSampleRate(frame, sample_rate_hz);
  frame->num_channels_ = num_channels;
  cb->reset(new ChannelBuffer<T>(frame->samples_per_channel_, num_channels));
}

AudioProcessing::ChannelLayout LayoutFromChannels(int num_channels);

template <typename T>
float ComputeSNR(const T* ref, const T* test, int length, float* variance) {
  float mse = 0;
  float mean = 0;
  *variance = 0;
  for (int i = 0; i < length; ++i) {
    T error = ref[i] - test[i];
    mse += error * error;
    *variance += ref[i] * ref[i];
    mean += ref[i];
  }
  mse /= length;
  *variance /= length;
  mean /= length;
  *variance -= mean * mean;

  float snr = 100;  // We assign 100 dB to the zero-error case.
  if (mse > 0)
    snr = 10 * log10(*variance / mse);
  return snr;
}

// Returns a vector<T> parsed from whitespace delimited values in to_parse,
// or an empty vector if the string could not be parsed.
template<typename T>
std::vector<T> ParseList(const std::string& to_parse) {
  std::vector<T> values;

  std::istringstream str(to_parse);
  std::copy(
      std::istream_iterator<T>(str),
      std::istream_iterator<T>(),
      std::back_inserter(values));

  return values;
}

// Parses the array geometry from the command line.
//
// If a vector with size != num_mics is returned, an error has occurred and an
// appropriate error message has been printed to stdout.
std::vector<Point> ParseArrayGeometry(const std::string& mic_positions,
                                      size_t num_mics);

}  // namespace webrtc

#endif  // WEBRTC_MODULES_AUDIO_PROCESSING_TEST_TEST_UTILS_H_


text:
package com.jadic.cmd.resp;

import org.jboss.netty.buffer.ChannelBuffer;

import com.jadic.cmd.CmdHeadIc2Pos;
import com.jadic.utils.KKTool;

/**
 * 获取附加费应答
 * @author Jadic
 * @created 2012-11-26
 */
public class CmdGetSurchargeI2P extends CmdHeadIc2Pos {

	private byte[] ver;//附加费版本
	private byte[] surchargeData;//附加费文件

	public CmdGetSurchargeI2P() {
		super();
		ver = new byte[4];
		surchargeData = new byte[128];
	}

	@Override
	public int getCmdSize() {
		return super.getCmdSize()
			 + this.ver.length
			 + this.surchargeData.length
			 + super.getCmdEndSize();
	}

	@Override
	public short getCmdPackSize() {
		return (short)(this.getCmdSize() - 6 - this.getCmdEndSize());
	}

	@Override
	public boolean fillChannelBuffer(ChannelBuffer channelBuffer) {
		if (!super.fillChannelBuffer(channelBuffer))
			return false;
		try {
			channelBuffer.writeBytes(this.ver);
			channelBuffer.writeBytes(this.surchargeData);

			byte[] d = new byte[this.getCmdSize() - super.getCmdEndSize() - 2 - 2];//计算校验值时去掉头和尾
			channelBuffer.getBytes(4, d, 0, d.length);
			channelBuffer.writeByte(KKTool.getLRC1(d));
			channelBuffer.writeByte(KKTool.getLRC2(d));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public byte[] getVer() {
		return ver;
	}

	public void setVer(byte[] ver) {
		this.ver = ver;
	}

	public byte[] getSurchargeData() {
		return surchargeData;
	}

	public void setSurchargeData(byte[] surchargeData) {
		this.surchargeData = surchargeData;
	}

}


text:
using System.Collections.Generic;
using NDatabase.Api;
using NDatabase.Exceptions;
using NDatabase.Tool.Wrappers;

namespace NDatabase.Core.Query.List
{
    /// <summary>
    ///   A simple list to hold query result.
    /// </summary>
    /// <remarks>
    ///   A simple list to hold query result. It is used when no index and no order by is used and inMemory = true
    /// </remarks>
    internal class SimpleList<TItem> : List<TItem>, IInternalObjectSet<TItem>
    {
        private int _currentPosition;

        public SimpleList()
        {
        }

        protected SimpleList(int initialCapacity) : base(initialCapacity)
        {
        }

        #region IObjects<E> Members

        public virtual void AddWithKey(IOdbComparable key, TItem o)
        {
            Add(o);
        }

        public virtual TItem GetFirst()
        {
            return Count == 0 ? default(TItem) : this[0];
        }

        public virtual bool HasNext()
        {
            return _currentPosition < Count;
        }

        public TItem Next()
        {
            return !HasNext()
                ? default(TItem)
                : this[_currentPosition++];
        }

        public virtual void Reset()
        {
            _currentPosition = 0;
        }

        public void AddOid(OID oid)
        {
            throw new OdbRuntimeException(NDatabaseError.InternalError.AddParameter("Add Oid not implemented "));
        }

        #endregion
    }
}


text:
<title>CX.LS 3 by @Classicxii</title>

<link rel="stylesheet" href="Style.css" type="text/css" media="screen" />

<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no"/>

two fourteen

56°c

72%

tue 23 feb


text:
import re

def solve(rawformula):
    """
    Test all possible translations betwee Character string and Numbered String
    Return the Solution to the puzzle or None if no solution is found.
    """
    for formula in fill_in(rawFormula):
        if valid(formula):
            return formula
    return None

def valid(formula):
    """
    Formula is valid only if it has no leading zero on any of it's numbers
    and the formula evalutates as True.
    Returns True or False
    """
    try:
        return not re.search(r'\b0[0-9]', forumla) and eval(formula) is True
    except ArithmeticError:
        return False
    except:
        return False

print valid('1+1==2')


text:
% !TEX TS-program = pdflatex
% !TEX encoding = UTF-8 Unicode

\documentclass[11pt]{report} % use larger type; default would be 10pt

\usepackage[utf8]{inputenc} % set input encoding (not needed with XeLaTeX)

%%% Examples of Article customizations
% These packages are optional, depending whether you want the features they provide.
% See the LaTeX Companion or other references for full information.

%%% PAGE DIMENSIONS
\usepackage{geometry} % to change the page dimensions
\geometry{a4paper} % or letterpaper (US) or a5paper or....
% \geometry{margin=2in} % for example, change the margins to 2 inches all round
% \geometry{landscape} % set up the page for landscape
%   read geometry.pdf for detailed page layout information

\usepackage{graphicx} % support the \includegraphics command and options

% \usepackage[parfill]{parskip} % Activate to begin paragraphs with an empty line rather than an indent

%%% PACKAGES
\usepackage{booktabs} % for much better looking tables
\usepackage{array} % for better arrays (eg matrices) in maths
\usepackage{paralist} % very flexible & customisable lists (eg. itemize/itemize, etc.)
\usepackage{verbatim} % adds environment for commenting out blocks of text & for better verbatim
\usepackage{subfig} % make it possible to include more than one captioned figure/table in a single float
% These packages are all incorporated in the memoir class to one degree or another...

%%% HEADERS & FOOTERS
\usepackage{fancyhdr} % This should be set AFTER setting up the page geometry
\pagestyle{fancy} % options: empty , plain , fancy
\renewcommand{\headrulewidth}{0pt} % customise the layout...
\lhead{Software Requirements Specification for Links}\chead{}\rhead{}
\lfoot{}\cfoot{\thepage}\rfoot{}

%%% SECTION TITLE APPEARANCE
\usepackage{sectsty}
\allsectionsfont{\sffamily\mdseries\upshape} % (See the fntguide.pdf for font help)
% (This matches ConTeXt defaults)

%%% ToC (table of contents) APPEARANCE
\usepackage[nottoc,notlof,notlot]{tocbibind} % Put the bibliography in the ToC
\usepackage[titles,subfigure]{tocloft} % Alter the style of the Table of Contents
\renewcommand{\cftsecfont}{\rmfamily\mdseries\upshape}
\renewcommand{\cftsecpagefont}{\rmfamily\mdseries\upshape} % No bold!
\renewcommand{\chaptername}{}

\usepackage{titlesec}
\usepackage{lipsum}
\titleformat{\chapter}
{\filcenter\normalfont\LARGE\bfseries}
{\chaptertitlename~\thechapter} {0.5em} {}

%%% END Article customizations

%%% The "real" document content comes below...

\title{Software Requirements Specification for "Links" \\ Version 1.0}
\author{Abhijith Madhav, Arjun S Bharadwaj}
%\date{} % Activate to display a given date or no date (if empty),
         % otherwise the current date is printed

\begin{document}
\maketitle
{\center {\LARGE { \bf Revisions} \\ } }
. \\
\begin{tabular}{ | c | c | c | c | }
\hline
  Version & Primary Author(s) & Description of Version  & Date Completed\\
  \hline
  \hline
  1.0 & Abhijith Madhav(MT2013002) & Initial version sent to Client & \date{February 5, 2014} \\
   & Arjun S Bharadwaj(MT2013026) & & \\
\hline
\hline
  2.0 & Abhijith Madhav(MT2013002) & Elaboration of product scope. Made & \date{February 7, 2014} \\
   & Arjun S Bharadwaj(MT2013026) & interoperability as an FR.& \\
\hline
  3.0 & Abhijith Madhav(MT2013002) & Changes to NFR. & \date{March 10, 2014} \\
   & Arjun S Bharadwaj(MT2013026) & & \\
\hline
\end{tabular}
\tableofcontents
\chapter{Introduction}
This document provides the Software Requirement Specifications of the project. Specifically it provides the details on the functional and non functional aspects of the project.
\section{Document Purpose}
The document describes the software requirements of "Links", version 1.0. The software requirements encapsulate the whole of the product.

\section{Product Scope}
"Links" is website offering bookmarking services with the specific requirement being that it should be deployable on a private server within an organization.

The purpose is to enable people in an organization to share bookmarks with each other.

The specific benefit delivered by "Links" is that sharing/publishing of bookmarks can be controlled at the required level of granularity.

"Links" is intended to be an extensible, modular system with an exposed API. Third parties must be able to write plugins and applications using this API.

It is envisioned to seemlessly fit into the "share" motto of the net community, be it through simple email or through popular social platforms like facebook and twitter. A trigger based action execution like that of ifttt.com augments this motto and is intended to be a part of "Links".

\maketitle
\chapter{Overall description}
This section provides the overall description of the project. This includes the product perspective and the functionality.
\section{Product Perspective}
A bookmarking service is a centralized online service which enables users to add, annotate, edit and share bookmarks of web documents, the most popular being Delicious. "Scuttle" is one of the other well known open source alternative. "Links" is envisioned on similar lines with the specific objective that it is aimed at deployment within an organization.
\section{Product Functionality}
\begin{enumerate}
\item
Provide for user accounts/signup.
\item
Provide for website bookmark management.
\item
Provide for management of user groups for sharing bookmarks.
\item
Provide for options to share website bookmarks amongst users and groups.
\item
Provide options to push website bookmarks onto popular social media and via email.
\end{enumerate}

\maketitle
\chapter{Functional Requirements}
This section specifies the functional requirements of the project.
\section{Functional Requirements}
This section provides the functional requirements of the project.
\begin{enumerate}
	\item
		Login
		\begin{itemize}
			\item
				User logs into the system.
			\item
				\emph{Input:} User enters the login details and clicks on login.
			\item
				\emph{Output:}
					\begin{itemize}
						\item
							If the validation of the user credentials is successful:
							\begin{itemize}
								\item
									The user is redirected to the Homepage.
							\end{itemize}

						\item
							If the validation of the login details is unsuccessful:
							\begin{itemize}
								\item
									An appropriate error message is shown to the user.
							\end{itemize}
					\end{itemize}
		\end{itemize}

	\item
		Signup
		\begin{itemize}
			\item
				User clicks on Signup.
			\item
				\emph{Input:} Signup details are asked.
			\item
				\emph{Output:}
					\begin{itemize}
						\item
							If validation of the details is successful:
							\begin{itemize}
								\item
									Account is created.
							\end{itemize}

						\item
							If validation of the details is unsuccessful:
							\begin{itemize}
								\item
									An appropriate error message is shown to the user.
							\end{itemize}
					\end{itemize}
		\end{itemize}

	\item
		Save Links
		\begin{itemize}
			\item
				User bookmarks the links.
			\item
				\emph{Input:} A Title, URI, Tags and Annotations are provided.
			\item
				\emph{Output:}
					\begin{itemize}
						\item
							After the link is saved:
							\begin{itemize}
								\item
									Acknowledgement for the action is provided.
									\item
									Suggest tags if same link was shared by others based on the visibility level of the user.
							\end{itemize}
					\end{itemize}
		\end{itemize}

	\item
		Edit  Links
		\begin{itemize}
			\item
				User edits the links.
			\item
				\emph{Input:} An existing link, modified data (title, tags, annotations).
			\item
				\emph{Output:}
					\begin{itemize}
						\item
							After the link is updated:
						\begin{itemize}
							\item
								Acknowledgement for the update is provided.
						\end{itemize}
					\end{itemize}
		\end{itemize}

	\item
		Delete   Links
		\begin{itemize}
			\item
				User deletes  the links.
			\item
				\emph{Input:} An existing link shared by the user.
			\item
				\emph{Output:}
					\begin{itemize}
						\item
							After the link is deleted:
						\begin{itemize}
							\item
								Acknowledgement for the deletion is provided.
						\end{itemize}
					\end{itemize}
			\end{itemize}

	\item
		Create User Groups
		\begin{itemize}
			\item
				Creation of Groups by the user.
			\item
				\emph{Input:} Group name and group description corresponding to the group.
			\item
				\emph{Output:}
					\begin{itemize}
						\item
							If the group name is not already used:
						\begin{itemize}
							\item
								Acknowledgement for the creation is provided.
						\end{itemize}

						\item
							If the group name already exists:
						\begin{itemize}
							\item
								Appropriate error message.
						\end{itemize}
					\end{itemize}
			\end{itemize}

	\item
		Join Group
		\begin{itemize}
			\item
				User joins the group.
			\item
				\emph{Input:} Group name of the group that the user wishes to subscribe to.
			\item
				\emph{Output:} Acknowledgement of the subscription is provided.
		\end{itemize}

	\item
		Unjoin Group
		\begin{itemize}
			\item
				User unjoins the group.
			\item
				\emph{Input:} Group name of the group that the user wishes to unsubscribe to.
			\item
				\emph{Output:} Acknowledgement of the un-subscription is provided.
		\end{itemize}

	\item
		Share
		\begin{itemize}
			\item
				Sharing of the links.
			\item
				\emph{Input:} A set of bookmarks to be shared via email or popular social media
			\item
				\emph{Output:} Share bookmarks via the specified media.
		\end{itemize}

	\item
		Add Members
		\begin{itemize}
			\item
				Add members to the group.
			\item
				\emph{Input:} User names by the group owner.
			\item
				\emph{Output:} Acknowledgement of addition to group.
		\end{itemize}

	\item
		Remove Members
		\begin{itemize}
			\item
				Remove members to the group.
			\item
				\emph{Input:} User names by the group owner.
			\item
				\emph{Output:} Acknowledgement of deletion to group.
		\end{itemize}
\item
Interoperability\\
Expose APIs through which the following can be done
\begin{itemize}
\item
Search based on bookmarks, annotations, tags in accordance to the visibility of the user.
\item
Add, delete and edit the bookmarks in accordance to the visibility of the user.
\end{itemize}
As a proof of concept, an android application that consumes the data from the provided APIs will be created
\end{enumerate}
\maketitle
\chapter{Non-functional Requirements}
This section specifies the non-functional aspects of the project.
\section{Security Requirements}
\begin{enumerate}
\item
All users must be authenticated before being given modification privileges in "Links".
\item
Third party clients must not have access to passwords of users and must instead use a token based authentication scheme.
\item
User passwords must be stored as salted hashes in the "Links" system.
\item
HTTPS connections between clients and the "Links" server must be supported.
\end{enumerate}
\section{User Experience}
\begin{enumerate}
\item
The browser extension using the "Links" API  must enable saving and/or sharing bookmarks from a third party website without having to navigate away from that site.
\item
Where possible, portions of any "Links" webpage must be updated without having to refresh the entire webpage from the server.
\end{enumerate}
\end{document}


text:
<?php

global $eSyndiCat;

$eSyndiCat->loadPluginClass("Calendar", "calendar", "esyn");
$esynCalendar = new esynCalendar();

$year = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$month = isset($_GET['month']) ? $_GET['month'] : date('m');

$year = esynSanitize::sql($year);
$month = esynSanitize::sql($month);

$days = $esynCalendar->getActiveDays($year, $month);

$links = array();

if ($days)
{
	foreach($days as $key => $val)
	{
		$links[(int)$val['date']] = array(IA_URL."date/{$year}/{$month}/{$val['date']}/", 'linked-day');
	}
}

echo $esynCalendar->generateCalendar($year, $month, $links);