text:
from __future__ import division, unicode_literals

import os
import hashlib
import logging
import platform

from collections import defaultdict

from .bencode import bencode, bdecode
from .humanize import humanize_bytes
from .utils import is_unsplitable, get_root_of_unsplitable, Pieces

logger = logging.getLogger('autotorrent')

class Color:
    BLACK = '\033[90m'
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    PINK = '\033[95m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'
    ENDC = '\033[0m'

COLOR_OK = Color.GREEN
COLOR_MISSING_FILES = Color.RED
COLOR_ALREADY_SEEDING = Color.BLUE
COLOR_FOLDER_EXIST_NOT_SEEDING = Color.YELLOW
COLOR_FAILED_TO_ADD_TO_CLIENT = Color.PINK

class Status:
    OK = 0
    MISSING_FILES = 1
    ALREADY_SEEDING = 2
    FOLDER_EXIST_NOT_SEEDING = 3
    FAILED_TO_ADD_TO_CLIENT = 4

status_messages = {
  Status.OK: '%sOK%s' % (COLOR_OK, Color.ENDC),
  Status.MISSING_FILES: '%sMissing%s' % (COLOR_MISSING_FILES, Color.ENDC),
  Status.ALREADY_SEEDING: '%sSeeded%s' % (COLOR_ALREADY_SEEDING, Color.ENDC),
  Status.FOLDER_EXIST_NOT_SEEDING: '%sExists%s' % (COLOR_FOLDER_EXIST_NOT_SEEDING, Color.ENDC),
  Status.FAILED_TO_ADD_TO_CLIENT: '%sFailed%s' % (COLOR_FAILED_TO_ADD_TO_CLIENT, Color.ENDC),
}

CHUNK_SIZE = 65536

class UnknownLinkTypeException(Exception):
    pass

class IllegalPathException(Exception):
    pass

class AutoTorrent(object):
    def __init__(self, db, client, store_path, add_limit_size, add_limit_percent, delete_torrents, link_type='soft'):
        self.db = db
        self.client = client
        self.store_path = store_path
        self.add_limit_size = add_limit_size
        self.add_limit_percent = add_limit_percent
        self.delete_torrents = delete_torrents
        self.link_type = link_type
        self.torrents_seeded = set()

    def try_decode(self, value):
        try:
            return value.decode('utf-8')
        except UnicodeDecodeError:
            logger.debug('Failed to decode %r using UTF-8' % value)

        return value.decode('iso-8859-1')

    def is_legal_path(self, path):
        for p in path:
            if p in ['.', '..'] or '/' in p:
                return False
        return True

    def populate_torrents_seeded(self):
        """
        Fetches a list of currently-seeded info hashes
        """
        self.torrents_seeded = set(x.lower() for x in self.client.get_torrents())

    def get_info_hash(self, torrent):
        """
        Creates the info hash of a torrent
        """
        return hashlib.sha1(bencode(torrent[b'info'])).hexdigest()

    def find_hash_checks(self, torrent, result):
        """
        Uses hash checking to find pieces
        """
        modified_result = False
        pieces = Pieces(torrent)

        if self.db.hash_slow_mode:
            logger.info('Slow mode enabled, building hash size table')
            self.db.build_hash_size_table()

        start_size = 0
        end_size = 0
        logger.info('Hash scan mode enabled, checking for incomplete files')
        for f in result:
            start_size = end_size
            end_size += f['length']

            if f['completed']:
                continue

            files_to_check = []
            logger.debug('Building list of file names to match hash with.')

            if self.db.hash_size_mode:
                logger.debug('Using hash size mode to find files')
                files_to_check += self.db.find_hash_size(f['length'])

            if self.db.hash_name_mode:
                logger.debug('Using hash name mode to find files')
                name = f['path'][-1]
                files_to_check += self.db.find_hash_name(name)

            if self.db.hash_slow_mode:
                logger.debug('Using hash slow mode to find files')
                files_to_check += self.db.find_hash_varying_size(f['length'])

            logger.debug('Found %i files to check for matching hash' % len(files_to_check))

            checked_files = set()
            for db_file in files_to_check:
                if db_file in checked_files:
                    logger.debug('File %s already checked, skipping' % db_file)

                checked_files.add(db_file)
                logger.info('Hash checking %s' % db_file)
                match_start, match_end = pieces.match_file(db_file, start_size, end_size)
                logger.info('We go result for file %s start:%s end:%s' % (db_file, match_start, match_end))

                if match_start or match_end: # this file is all-good
                    size = os.path.getsize(db_file)
                    if size != f['length']: # size does not match, need to align file
                        logger.debug('File does not have correct size, need to align it')
                        if match_start and match_end:
                            logger.debug('Need to find alignment in the middle of the file')
                            modification_point = pieces.find_piece_breakpoint(db_file, start_size, end_size)
                        elif match_start:
                            logger.debug('Need to modify from the end of the file')
                            modification_point = min(f['length'], size)
                        elif match_end:
                            logger.debug('Need to modify at the front of the file')
                            modification_point = 0

                        if size > f['length']:
                            modification_action = 'remove'
                        else:
                            modification_action = 'add'

                        f['completed'] = False
                        f['postprocessing'] = ('rewrite', modification_action, modification_point)
                        modified_result = True
                    else:
                        logger.debug('Perfect size, perfect match !')
                        f['completed'] = True

                    f['actual_path'] = db_file
                    break

        return modified_result, result

    def index_torrent(self, torrent):
        """
        Indexes the files in the torrent.
        """
        torrent_name = torrent[b'info'][b'name']
        logger.debug('Handling torrent name %r' % (torrent_name, ))
        torrent_name = self.try_decode(torrent_name)
        if not self.is_legal_path([torrent_name]):
            raise IllegalPathException('That is a dangerous torrent name %r, bailing' % torrent_name)

        logger.info('Found name %r for torrent' % torrent_name)

        if self.db.exact_mode:
            prefix = 'd' if b'files' in torrent[b'info'] else 'f'

            paths = self.db.find_exact_file_path(prefix, torrent_name)
            if paths:
                for path in paths:
                    logger.debug('Checking exact path %r' % path)
                    if prefix == 'f':
                        logger.info('Did an exact match to a file')
                        size = os.path.getsize(path)
                        if torrent[b'info'][b'length'] != size:
                            continue

                        return {'mode': 'exact',
                                'source_path': os.path.dirname(path),
                                'files': [{
                                    'actual_path': path,
                                    'length': size,
                                    'path': [torrent_name],
                                    'completed': True,
                                }]}
                    else:
                        result = []
                        for f in torrent[b'info'][b'files']:
                            orig_path = [self.try_decode(x) for x in f[b'path']]
                            p = os.path.join(path, *orig_path)

                            if not os.path.isfile(p):
                                logger.debug('File %r does not exist' % p)
                                break

                            size = os.path.getsize(p)
                            if size != f[b'length']:
                                logger.debug('File %r did not match, this is not exact (got size %s, expected %s)' % (p, size, f[b'length']))
                                break

                            result.append({
                                'actual_path': p,
                                'length': f[b'length'],
                                'path': orig_path,
                                'completed': True,
                            })
                        else:
                            logger.info('Did an exact match to a path')
                            return {'mode': 'exact',
                                    'source_path': path,
                                    'files': result}

        result = []
        if b'files' in torrent[b'info']: # multifile torrent
            files_sorted = {}
            files = {}
            if b'files' in torrent[b'info']:

                i = 0
                path_files = defaultdict(list)
                for f in torrent[b'info'][b'files']:
                    logger.debug('Handling torrent file %r' % (f, ))
                    orig_path = [self.try_decode(x) for x in f[b'path'] if x] # remove empty fragments
                    if not self.is_legal_path(orig_path):
                        raise IllegalPathException('That is a dangerous torrent path %r, bailing' % orig_path)

                    path = [torrent_name] + orig_path
                    name = path.pop()

                    path_files[os.path.join(*path)].append({
                        'path': orig_path,
                        'length': f[b'length'],
                    })

                    files_sorted['/'.join(orig_path)] = i
                    i += 1

            if self.db.unsplitable_mode:
                unsplitable_paths = set()
                for path, files in path_files.items():
                    if is_unsplitable(f['path'][-1] for f in files):
                        path = path.split(os.sep)
                        name = get_root_of_unsplitable(path)
                        if not name:
                            continue

                        while path[-1] != name:
                            path.pop()
                        unsplitable_paths.add(os.path.join(*path))

            for path, files in path_files.items():
                if self.db.unsplitable_mode:
                    path = path.split(os.sep)
                    while path and os.path.join(*path) not in unsplitable_paths:
                        path.pop()
                else:
                    path = None

                if path:
                    name = path[-1]
                    for f in files:
                        actual_path = self.db.find_unsplitable_file_path(name, f['path'], f['length'])
                        f['actual_path'] = actual_path
                        f['completed'] = actual_path is not None
                    result += files
                else:
                    for f in files:
                        actual_path = self.db.find_file_path(f['path'][-1], f['length'])
                        f['actual_path'] = actual_path
                        f['completed'] = actual_path is not None
                    result += files
            # re-sort the torrent to fit original ordering
            result = sorted(result, key=lambda x:files_sorted['/'.join(x['path'])])

        else: # singlefile torrent
            length = torrent[b'info'][b'length']
            actual_path = self.db.find_file_path(torrent_name, length)

            result.append({
                'actual_path': actual_path,
                'length': length,
                'path': [torrent_name],
                'completed': actual_path is not None,
            })

        mode = 'link'
        if self.db.hash_mode:
            modified_result, result = self.find_hash_checks(torrent, result)
            if modified_result:
                mode = 'hash'

        return {'mode': mode, 'files': result}

    def parse_torrent(self, torrent):
        """
        Parses the torrent and finds the physical location of files
        in the torrent
        """
        files = self.index_torrent(torrent)

        found_size, missing_size = 0, 0
        for f in files['files']:
            if f['completed'] or f.get('postprocessing'):
                found_size += f['length']
            else:
                missing_size += f['length']

        return found_size, missing_size, files

    def link_files(self, destination_path, files):
        """
        Links the files to the destination_path if they are found.
        """
        if not os.path.isdir(destination_path):
            os.makedirs(destination_path)

        for f in files:
            if f['completed']:
                destination = os.path.join(destination_path, *f['path'])

                file_path = os.path.dirname(destination)
                if not os.path.isdir(file_path):
                    logger.debug('Folder %r does not exist, creating' % file_path)
                    os.makedirs(file_path)

                logger.debug('Making %s link from %r to %r' % (self.link_type, f['actual_path'], destination))

                if self.link_type == 'soft':
                    os.symlink(f['actual_path'], destination)
                elif self.link_type == 'hard':
                    os.link(f['actual_path'], destination)
                elif self.link_type == 'ref':
                    self.reflink(f['actual_path'], destination)
                else:
                    raise UnknownLinkTypeException('%r is not a known link type' % self.link_type)

    def reflink(self, path, destination):
        """
        Perform a reflink (if supported, currently only xfs, apfs, btrfs is)
        This code is modified from dvc (https://github.com/iterative/dvc/blob/f4bec650eddc8874b3f7ab2f8b34bc5dfe60fd49/dvc/system.py#L105).
        These libraries are available under the Apache 2.0 license, which can be obtained from http://www.apache.org/licenses/LICENSE-2.0.
        """
        system = platform.system()
        logger.debug('platform is %r', system)
        try:
           if system == "Windows":
               ret = self.reflink_windows(path, destination)
           elif system == "Darwin":
               ret = self.reflink_darwin(path, destination)
           elif system == "Linux":
               ret = self.reflink_linux(path, destination)
           else:
               ret = -1
        except IOError:
               ret = -1

        if ret != 0:
               raise Exception("reflink is not supported")

    def reflink_linux(self, path, destination):
        """
        Linux only reflink via syscall FICLONE on supported filesystems
        """
        import os
        import fcntl

        FICLONE = 0x40049409

        try:
            ret = 255
            with open(path, "r") as s, open(destination, "w+") as d:
                ret = fcntl.ioctl(d.fileno(), FICLONE, s.fileno())
        finally:
            if ret != 0:
                os.unlink(destination)

        return ret

    def reflink_windows(self, path, destination):
        return -1

    def reflink_darwin(self, path, destination):
        import ctypes

        LIBC = "libc.dylib"
        LIBC_FALLBACK = "/usr/lib/libSystem.dylib"
        try:
            clib = ctypes.CDLL(LIBC)
        except OSError as exc:
            logger.debug(
                "unable to access '{}' (errno '{}'). "
                "Falling back to '{}'.".format(LIBC, exc.errno, LIBC_FALLBACK)
            )
            if exc.errno != errno.ENOENT:
                raise
            # NOTE: trying to bypass System Integrity Protection (SIP)
            clib = ctypes.CDLL(LIBC_FALLBACK)

        if not hasattr(clib, "clonefile"):
            return -1

        clonefile = clib.clonefile
        clonefile.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
        clonefile.restype = ctypes.c_int

        return clonefile(
            ctypes.c_char_p(path.encode("utf-8")),
            ctypes.c_char_p(destination.encode("utf-8")),
            ctypes.c_int(0),
        )

    def rewrite_hashed_files(self, destination_path, files):
        """
        Rewrites files from the actual_path to the correct file inside destination_path.
        """
        if not os.path.isdir(destination_path):
            os.makedirs(destination_path)

        for f in files:
            if not f['completed'] and 'postprocessing' in f:
                destination = os.path.join(destination_path, *f['path'])

                file_path = os.path.dirname(destination)
                if not os.path.isdir(file_path):
                    logger.debug('Folder %r does not exist, creating' % file_path)
                    os.makedirs(file_path)

                logger.debug('Rewriting file from %r to %r' % (f['actual_path'], destination))

                _, modification_action, modification_point = f['postprocessing']
                current_size = os.path.getsize(f['actual_path'])
                expected_size = f['length']
                diff = abs(current_size - expected_size)

                # write until modification_point, do action, write rest of file

                modified = False
                bytes_written = 0
                with open(destination, 'wb') as output_fp:
                    with open(f['actual_path'], 'rb') as input_fp:
                        logger.debug('Opened file %s and writing its data to %s - The breakpoint is %i' % (f['actual_path'], destination, modification_point))
                        while True:
                            if not modified and bytes_written == modification_point:
                                logger.debug('Time to modify with action %s and bytes %i' % (modification_action, diff))
                                modified = True
                                if modification_action == 'remove':
                                    seek_point = bytes_written + diff
                                    logger.debug('Have to shrink compared to original file, seeking to %i' % (seek_point, ))
                                    input_fp.seek(seek_point)
                                elif modification_action == 'add':
                                    logger.debug('Need to add data, writing %i empty bytes' % diff)
                                    while diff > 0:
                                        write_bytes = min(CHUNK_SIZE, diff)
                                        output_fp.write(b'\x00' * write_bytes)
                                        diff -= write_bytes

                            read_bytes = CHUNK_SIZE
                            if not modified:
                                read_bytes = min(read_bytes, modification_point-bytes_written)

                            logger.debug('Reading %i bytes' % (read_bytes, ))
                            data = input_fp.read(read_bytes)
                            if not data:
                                break
                            output_fp.write(data)
                            bytes_written += read_bytes
                logger.debug('Done rewriting file')

    def handle_torrentfile(self, path, dry_run=False):
        """
        Checks a torrentfile for files to seed, groups them by found / not found.
        The result will also include the total size of missing / not missing files.
        """
        logger.info('Handling file %s' % path)

        torrent = self.open_torrentfile(path)

        if self.check_torrent_in_client(torrent):
            self.print_status(Status.ALREADY_SEEDING, path, 'Already seeded')
            if self.delete_torrents:
                logger.info('Removing torrent %r' % path)
                os.remove(path)
            return Status.ALREADY_SEEDING

        found_size, missing_size, files = self.parse_torrent(torrent)
        if found_size + missing_size == 0:
            missing_percent = 100
        else:
            missing_percent = (missing_size / (found_size + missing_size)) * 100
        found_percent = 100 - missing_percent
        would_not_add = missing_size and missing_percent > self.add_limit_percent or missing_size > self.add_limit_size

        if dry_run:
            return found_size, missing_size, would_not_add, [f['actual_path'] for f in files['files'] if f.get('actual_path')]

        if would_not_add:
            logger.info('Files missing from %s, only %3.2f%% found (%s missing)' % (path, found_percent, humanize_bytes(missing_size)))
            self.print_status(Status.MISSING_FILES, path, 'Missing files, only %3.2f%% found (%s missing)' % (found_percent, humanize_bytes(missing_size)))
            return Status.MISSING_FILES

        if files['mode'] == 'link' or files['mode'] == 'hash':
            logger.info('Preparing torrent using link mode')
            destination_path = os.path.join(self.store_path, os.path.splitext(os.path.basename(path))[0])

            if os.path.isdir(destination_path):
                logger.info('Folder exist but torrent is not seeded %s' % destination_path)
                self.print_status(Status.FOLDER_EXIST_NOT_SEEDING, path, 'The folder exist, but is not seeded by torrentclient')
                return Status.FOLDER_EXIST_NOT_SEEDING

            self.link_files(destination_path, files['files'])
        elif files['mode'] == 'exact':
            logger.info('Preparing torrent using exact mode')
            destination_path = files['source_path']

        fast_resume = True
        if files['mode'] == 'hash':
            fast_resume = False
            logger.info('There are files found using hashing that needs rewriting.')
            self.rewrite_hashed_files(destination_path, files['files'])

        if self.delete_torrents:
            logger.info('Removing torrent %r' % path)
            os.remove(path)

        if self.client.add_torrent(torrent, destination_path, files['files'], fast_resume):
            self.print_status(Status.OK, path, 'Torrent added successfully')
            return Status.OK
        else:
            self.print_status(Status.FAILED_TO_ADD_TO_CLIENT, path, 'Failed to send torrent to client')
            return Status.FAILED_TO_ADD_TO_CLIENT

    def check_torrent_in_client(self, torrent):
        """
        Checks if a torrent is currently seeded
        """
        info_hash = self.get_info_hash(torrent)
        return info_hash in self.torrents_seeded

    def open_torrentfile(self, path):
        """
        Opens and parses a torrent file
        """
        with open(path, 'rb') as f:
            return bdecode(f.read())

    def print_status(self, status, torrentfile, message):
        print(' %-20s %r %s' % ('[%s]' % status_messages[status], os.path.splitext(os.path.basename(torrentfile))[0], message))

redpajama_set_name: RedPajamaGithub


text:
class QueryRow
  attr_reader :query

  def initialize(row)
    @query = row[0]
    @description = row[1]
  end

  def name
    @description.blank? ? @query : @description
  end

  def empty?
    @query.blank?
  end
end


text:
<resources>
    <string name="app_name">Ux</string>
</resources>


text:
title: Milky way
author: chennaiastronomyclub
layout: post
permalink: /2014/11/04/milky-way/
tags: [milky way]
categories: [Astrophotography]
---

![Milky way](/img/milky.jpg)
Photo Credit: Tamil Eniyan


text:
Nextcloud in your enterprise or organization

Nextcloud gives organizations control over their data. Manage access to data across devices and platforms, on-premise, on existing storage or with cloud storage. Communicate through secure video and audio chat and leverage file sharing and collaboration capabilities. Nextcloud integrates in your infrastructure, offering the extensibility and features you need combined with the logging and fine grained control over file access and communication required in regulated industries.

Enterprise capabilities

Nextcloud offers you a full open source file sync and share solution, including:

File sync and share from any device and with an easy to use web interface

Access to all data in your organization, no matter where it is stored

Seamless collaboration and communication built in

Fully secure and encrypted data handling with fine grained file access control

Compliance capabilities with retention, logging and auditing

Support for Calendar, Contacts and secure video and audio chat

The Nextcloud Enterprise Subscription

We can provide you the confidence of knowing that your Nextcloud deployment is backed by the technical expertise of the engineers who wrote the software and with the features you need for your organization.

With the Nextcloud Enterprise subscription you get:

Full lifecycle support, from project inception to production and user growth

Help to scale your Nextcloud installation to large amounts of storage and many users

Security and hardening consulting

Advanced enterprise integration features and capabilities

Access to the roadmap of the open source project

Access to the core Nextcloud engineers

Access to consulting for custom capabilities

Full support for integrated video conferencing and communication features based on spreed.me and WebRTC

Available early July

Contact us for more information.

<form name="sales" method="post" action="salessubmit/">

Your name

		<input  type="text" name="yourname" maxlength="60" size="60">

Email

		<input  type="text" name="email" maxlength="80" size="60">

Organization

		<input  type="text" name="organization" maxlength="80" size="60" placeholder="">

Phone number

		<input  type="text" name="phone" maxlength="40" size="60" placeholder="Please include country code">

Your message

		<textarea  name="comments" maxlength="1000" cols="60" rows="6" placeholder="Let us know how we can help you!"></textarea>

		<input type="submit" value=" Submit inquiry ">

</form>


text:
package org.luapp.practise.proxy;

/**
 * Created by lumeng on 2015/3/7.
 */
public class Car implements Movable {
    @Override
    public void move() {
        System.out.println("Moving......");
    }
}


text:
Installation
============

To begin, add the dependent bundles::

    php composer.phar require sonata-project/easy-extends-bundle

Next, be sure to enable the new bundles in your application kernel:

.. code-block:: php

  <?php
  // app/appkernel.php
  public function registerBundles()
  {
      return array(
          // ...
          new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
          // ...
      );
  }


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NuGet.Common;
using NuGet.Protocol;
using Sleet;

namespace Test.Common
{
    public static class CatalogReaderTestHelpers
    {
        public static async Task CreateCatalogAsync(string root, string feedRoot, string nupkgFolder, Uri baseUri, int catalogPageSize, ILogger log)
        {
            using (var cache = new LocalCache())
            {
                var sleetConfig = CreateSleetConfig(root, feedRoot, baseUri);
                var settings = LocalSettings.Load(sleetConfig);
                var fileSystem = await FileSystemFactory.CreateFileSystemAsync(settings, cache, "feed");
                var feedSettings = await FeedSettingsUtility.GetSettingsOrDefault(fileSystem, log, CancellationToken.None);
                feedSettings.CatalogEnabled = true;
                feedSettings.SymbolsEnabled = false;
                feedSettings.CatalogPageSize = catalogPageSize;

                var success = await InitCommand.InitAsync(settings, fileSystem, feedSettings, log, CancellationToken.None);

                if (success != true)
                {
                    throw new InvalidOperationException("Catalog init failed");
                }

                if (Directory.GetFiles(nupkgFolder).Any())
                {
                    success = await PushCommand.PushPackages(settings, fileSystem, new List<string>() { nupkgFolder }, false, false, log, CancellationToken.None);

                    if (success != true)
                    {
                        throw new InvalidOperationException("Push failed");
                    }
                }
            }
        }

        public static Task CreateCatalogAsync(string root, string feedRoot, string nupkgFolder, Uri baseUri, ILogger log)
        {
            return CreateCatalogAsync(
                root,
                feedRoot,
                nupkgFolder,
                baseUri,
                new FeedSettings().CatalogPageSize,
                log);
        }

        public static async Task PushPackagesAsync(string root, string nupkgFolder, Uri baseUri, ILogger log)
        {
            var sleetConfig = Path.Combine(root, "sleet.json");

            if (Directory.GetFiles(nupkgFolder).Any())
            {
                using (var cache = new LocalCache())
                {
                    var settings = LocalSettings.Load(sleetConfig);
                    var fileSystem = await FileSystemFactory.CreateFileSystemAsync(settings, cache, "feed");

                    var success = await PushCommand.PushPackages(settings, fileSystem, new List<string>() { nupkgFolder }, true, false, log, CancellationToken.None);

                    if (success != true)
                    {
                        throw new InvalidOperationException("Push failed");
                    }
                }
            }
        }

        public static string CreateSleetConfig(string root, string feedRoot, Uri baseUri)
        {
            var path = Path.Combine(root, "sleet.json");

            var json = CatalogReaderTestHelpers.CreateConfigWithLocal("feed", feedRoot, baseUri.AbsoluteUri);

            File.WriteAllText(path, json.ToString());

            return path;
        }

        public static HttpSource GetHttpSource(LocalCache cache, string outputRoot, Uri baseUri)
        {
            var fileSystem = new PhysicalFileSystem(cache, Sleet.UriUtility.CreateUri(outputRoot), baseUri);

            return TestHttpSourceResourceProvider.CreateSource(new Uri(baseUri + "index.json"), fileSystem);
        }

        public static JObject CreateConfigWithLocal(string sourceName, string sourcePath, string baseUri)
        {
            // Create the config template
            var json = new JObject
            {
                { "username", "test" },
                { "useremail", "test@tempuri.org" }
            };

            var sourcesArray = new JArray();
            json.Add("sources", sourcesArray);

            var folderJson = new JObject
            {
                { "name", sourceName },
                { "type", "local" },
                { "path", sourcePath }
            };

            if (!string.IsNullOrEmpty(baseUri))
            {
                folderJson.Add("baseURI", baseUri);
            }

            sourcesArray.Add(folderJson);

            return json;
        }
    }
}


text:
namespace content {

class WebContentsAudioInputStream::Impl
    : public base::RefCountedThreadSafe<WebContentsAudioInputStream::Impl>,
      public AudioMirroringManager::MirroringDestination {
 public:
  // Takes ownership of |mixer_stream|.  The rest outlive this instance.
  Impl(int render_process_id, int main_render_frame_id,
       AudioMirroringManager* mirroring_manager,
       const scoped_refptr<WebContentsTracker>& tracker,
       media::VirtualAudioInputStream* mixer_stream);

  // Open underlying VirtualAudioInputStream and start tracker.
  bool Open();

  // Start the underlying VirtualAudioInputStream and instruct
  // AudioMirroringManager to begin a mirroring session.
  void Start(AudioInputCallback* callback);

  // Stop the underlying VirtualAudioInputStream and instruct
  // AudioMirroringManager to shutdown a mirroring session.
  void Stop();

  // Close the underlying VirtualAudioInputStream and stop the tracker.
  void Close();

  // Accessor to underlying VirtualAudioInputStream.
  media::VirtualAudioInputStream* mixer_stream() const {
    return mixer_stream_.get();
  }

 private:
  friend class base::RefCountedThreadSafe<WebContentsAudioInputStream::Impl>;

  typedef AudioMirroringManager::SourceFrameRef SourceFrameRef;

  enum State {
    CONSTRUCTED,
    OPENED,
    MIRRORING,
    CLOSED
  };

  ~Impl() override;

  // Notifies the consumer callback that the stream is now dead.
  void ReportError();

  // (Re-)Start/Stop mirroring by posting a call to AudioMirroringManager on the
  // IO BrowserThread.
  void StartMirroring();
  void StopMirroring();

  // Invoked on the UI thread to make sure WebContents muting is turned off for
  // successful audio capture.
  void UnmuteWebContentsAudio();

  // AudioMirroringManager::MirroringDestination implementation
  void QueryForMatches(const std::set<SourceFrameRef>& candidates,
                       const MatchesCallback& results_callback) override;
  void QueryForMatchesOnUIThread(const std::set<SourceFrameRef>& candidates,
                                 const MatchesCallback& results_callback);
  media::AudioOutputStream* AddInput(
      const media::AudioParameters& params) override;

  // Callback which is run when |stream| is closed.  Deletes |stream|.
  void ReleaseInput(media::VirtualAudioOutputStream* stream);

  // Called by WebContentsTracker when the target of the audio mirroring has
  // changed.
  void OnTargetChanged(bool had_target);

  // Injected dependencies.
  const int initial_render_process_id_;
  const int initial_main_render_frame_id_;
  AudioMirroringManager* const mirroring_manager_;
  const scoped_refptr<WebContentsTracker> tracker_;
  // The AudioInputStream implementation that handles the audio conversion and
  // mixing details.
  const scoped_ptr<media::VirtualAudioInputStream> mixer_stream_;

  State state_;

  // Set to true if |tracker_| reports a NULL target, which indicates the target
  // is permanently lost.
  bool is_target_lost_;

  // Current callback used to consume the resulting mixed audio data.
  AudioInputCallback* callback_;

  base::ThreadChecker thread_checker_;

  DISALLOW_COPY_AND_ASSIGN(Impl);
};

WebContentsAudioInputStream::Impl::Impl(
    int render_process_id, int main_render_frame_id,
    AudioMirroringManager* mirroring_manager,
    const scoped_refptr<WebContentsTracker>& tracker,
    media::VirtualAudioInputStream* mixer_stream)
    : initial_render_process_id_(render_process_id),
      initial_main_render_frame_id_(main_render_frame_id),
      mirroring_manager_(mirroring_manager),
      tracker_(tracker),
      mixer_stream_(mixer_stream),
      state_(CONSTRUCTED),
      is_target_lost_(false),
      callback_(NULL) {
  DCHECK(mirroring_manager_);
  DCHECK(tracker_.get());
  DCHECK(mixer_stream_.get());

  // WAIS::Impl can be constructed on any thread, but will DCHECK that all
  // its methods from here on are called from the same thread.
  thread_checker_.DetachFromThread();
}

WebContentsAudioInputStream::Impl::~Impl() {
  DCHECK(state_ == CONSTRUCTED || state_ == CLOSED);
}

bool WebContentsAudioInputStream::Impl::Open() {
  DCHECK(thread_checker_.CalledOnValidThread());

  DCHECK_EQ(CONSTRUCTED, state_) << "Illegal to Open more than once.";

  if (!mixer_stream_->Open())
    return false;

  state_ = OPENED;

  tracker_->Start(
      initial_render_process_id_, initial_main_render_frame_id_,
      base::Bind(&Impl::OnTargetChanged, this));

  return true;
}

void WebContentsAudioInputStream::Impl::Start(AudioInputCallback* callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(callback);

  if (state_ != OPENED)
    return;

  callback_ = callback;
  if (is_target_lost_) {
    ReportError();
    callback_ = NULL;
    return;
  }

  state_ = MIRRORING;
  mixer_stream_->Start(callback);

  StartMirroring();

  // WebContents audio muting is implemented as audio capture to nowhere.
  // Unmuting will stop that audio capture, allowing AudioMirroringManager to
  // divert audio capture to here.
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&Impl::UnmuteWebContentsAudio, this));
}

void WebContentsAudioInputStream::Impl::Stop() {
  DCHECK(thread_checker_.CalledOnValidThread());

  if (state_ != MIRRORING)
    return;

  state_ = OPENED;

  mixer_stream_->Stop();
  callback_ = NULL;

  StopMirroring();
}

void WebContentsAudioInputStream::Impl::Close() {
  DCHECK(thread_checker_.CalledOnValidThread());

  Stop();

  if (state_ == OPENED) {
    state_ = CONSTRUCTED;
    tracker_->Stop();
    mixer_stream_->Close();
  }

  DCHECK_EQ(CONSTRUCTED, state_);
  state_ = CLOSED;
}

void WebContentsAudioInputStream::Impl::ReportError() {
  DCHECK(thread_checker_.CalledOnValidThread());

  // TODO(miu): Need clean-up of AudioInputCallback interface in a future
  // change, since its only implementation ignores the first argument entirely
  callback_->OnError(NULL);
}

void WebContentsAudioInputStream::Impl::StartMirroring() {
  DCHECK(thread_checker_.CalledOnValidThread());

  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&AudioMirroringManager::StartMirroring,
                 base::Unretained(mirroring_manager_),
                 make_scoped_refptr(this)));
}

void WebContentsAudioInputStream::Impl::StopMirroring() {
  DCHECK(thread_checker_.CalledOnValidThread());

  BrowserThread::PostTask(
      BrowserThread::IO,
      FROM_HERE,
      base::Bind(&AudioMirroringManager::StopMirroring,
                 base::Unretained(mirroring_manager_),
                 make_scoped_refptr(this)));
}

void WebContentsAudioInputStream::Impl::UnmuteWebContentsAudio() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  WebContents* const contents = tracker_->web_contents();
  if (contents)
    contents->SetAudioMuted(false);
}

void WebContentsAudioInputStream::Impl::QueryForMatches(
    const std::set<SourceFrameRef>& candidates,
    const MatchesCallback& results_callback) {
  BrowserThread::PostTask(
      BrowserThread::UI,
      FROM_HERE,
      base::Bind(&Impl::QueryForMatchesOnUIThread,
                 this,
                 candidates,
                 media::BindToCurrentLoop(results_callback)));
}

void WebContentsAudioInputStream::Impl::QueryForMatchesOnUIThread(
    const std::set<SourceFrameRef>& candidates,
    const MatchesCallback& results_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  std::set<SourceFrameRef> matches;
  WebContents* const contents = tracker_->web_contents();
  if (contents) {
    // Add each ID to |matches| if it maps to a RenderFrameHost that maps to the
    // currently-tracked WebContents.
    for (std::set<SourceFrameRef>::const_iterator i = candidates.begin();
         i != candidates.end(); ++i) {
      WebContents* const contents_containing_frame =
          WebContents::FromRenderFrameHost(
              RenderFrameHost::FromID(i->first, i->second));
      if (contents_containing_frame == contents)
        matches.insert(*i);
    }
  }

  results_callback.Run(matches);
}

media::AudioOutputStream* WebContentsAudioInputStream::Impl::AddInput(
    const media::AudioParameters& params) {
  // Note: The closure created here holds a reference to "this," which will
  // guarantee the VirtualAudioInputStream (mixer_stream_) outlives the
  // VirtualAudioOutputStream.
  return new media::VirtualAudioOutputStream(
      params,
      mixer_stream_.get(),
      base::Bind(&Impl::ReleaseInput, this));
}

void WebContentsAudioInputStream::Impl::ReleaseInput(
    media::VirtualAudioOutputStream* stream) {
  delete stream;
}

void WebContentsAudioInputStream::Impl::OnTargetChanged(bool had_target) {
  DCHECK(thread_checker_.CalledOnValidThread());

  is_target_lost_ = !had_target;

  if (state_ == MIRRORING) {
    if (is_target_lost_) {
      ReportError();
      Stop();
    } else {
      StartMirroring();
    }
  }
}

// static
WebContentsAudioInputStream* WebContentsAudioInputStream::Create(
    const std::string& device_id,
    const media::AudioParameters& params,
    const scoped_refptr<base::SingleThreadTaskRunner>& worker_task_runner,
    AudioMirroringManager* audio_mirroring_manager) {
  int render_process_id;
  int main_render_frame_id;
  if (!WebContentsMediaCaptureId::ExtractTabCaptureTarget(
          device_id, &render_process_id, &main_render_frame_id)) {
    return NULL;
  }

  return new WebContentsAudioInputStream(
      render_process_id, main_render_frame_id,
      audio_mirroring_manager,
      new WebContentsTracker(false),
      new media::VirtualAudioInputStream(
          params, worker_task_runner,
          media::VirtualAudioInputStream::AfterCloseCallback()));
}

WebContentsAudioInputStream::WebContentsAudioInputStream(
    int render_process_id, int main_render_frame_id,
    AudioMirroringManager* mirroring_manager,
    const scoped_refptr<WebContentsTracker>& tracker,
    media::VirtualAudioInputStream* mixer_stream)
    : impl_(new Impl(render_process_id, main_render_frame_id,
                     mirroring_manager, tracker, mixer_stream)) {}

WebContentsAudioInputStream::~WebContentsAudioInputStream() {}

bool WebContentsAudioInputStream::Open() {
  return impl_->Open();
}

void WebContentsAudioInputStream::Start(AudioInputCallback* callback) {
  impl_->Start(callback);
}

void WebContentsAudioInputStream::Stop() {
  impl_->Stop();
}

void WebContentsAudioInputStream::Close() {
  impl_->Close();
  delete this;
}

double WebContentsAudioInputStream::GetMaxVolume() {
  return impl_->mixer_stream()->GetMaxVolume();
}

void WebContentsAudioInputStream::SetVolume(double volume) {
  impl_->mixer_stream()->SetVolume(volume);
}

double WebContentsAudioInputStream::GetVolume() {
  return impl_->mixer_stream()->GetVolume();
}

bool WebContentsAudioInputStream::SetAutomaticGainControl(bool enabled) {
  return impl_->mixer_stream()->SetAutomaticGainControl(enabled);
}

bool WebContentsAudioInputStream::GetAutomaticGainControl() {
  return impl_->mixer_stream()->GetAutomaticGainControl();
}

bool WebContentsAudioInputStream::IsMuted() {
  return false;
}

}  // namespace content


text:
<?php
/**
 * index.php
 * @author Revin Roman
 * @link https://rmrevin.com
 */

use rmrevin\yii\module\Comments\tests\web\models\User;
use rmrevin\yii\module\Comments\widgets\CommentListWidget;
use yii\helpers\Html;

/** @var User $User */
$User = \Yii::$app->getUser()->getIdentity();

?>
    <div class="login">
        <?php
        if (\Yii::$app->getUser()->getIsGuest()) {
            echo 'Not logged. ';
            echo Html::a('Login', ['/sign/in']);
        } else {
            echo sprintf('Logged as %s. ', $User->name);
            echo Html::a('Logout', ['/sign/out']);
        }
        ?>
    </div>
<?php

echo CommentListWidget::widget([
    'entity' => 'test-1',
]);


text:
import unittest

import bottle
from bottle import tob, touni

class TestSecureCookies(unittest.TestCase):
    def setUp(self):
        self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
        self.key = tob('secret')

    def testDeEncode(self):
        cookie = bottle.cookie_encode(self.data, self.key)
        decoded = bottle.cookie_decode(cookie, self.key)
        self.assertEqual(self.data, decoded)
        decoded = bottle.cookie_decode(cookie+tob('x'), self.key)
        self.assertEqual(None, decoded)

    def testIsEncoded(self):
        cookie = bottle.cookie_encode(self.data, self.key)
        self.assertTrue(bottle.cookie_is_encoded(cookie))
        self.assertFalse(bottle.cookie_is_encoded(tob('some string')))

class TestSecureCookiesInBottle(unittest.TestCase):
    def setUp(self):
        self.data = dict(a=5, b=touni('υηι¢σ∂є'), c=[1,2,3,4,tob('bytestring')])
        self.secret = tob('secret')
        bottle.app.push()
        bottle.response.bind()

    def tear_down(self):
        bottle.app.pop()

    def get_pairs(self):
        for k, v in bottle.response.headerlist:
            if k == 'Set-Cookie':
                key, value = v.split(';')[0].split('=', 1)
                yield key.lower().strip(), value.strip()

    def set_pairs(self, pairs):
        header = ','.join(['%s=%s' % (k, v) for k, v in pairs])
        bottle.request.bind({'HTTP_COOKIE': header})

    def testValid(self):
        bottle.response.set_cookie('key', self.data, secret=self.secret)
        pairs = self.get_pairs()
        self.set_pairs(pairs)
        result = bottle.request.get_cookie('key', secret=self.secret)
        self.assertEqual(self.data, result)

    def testWrongKey(self):
        bottle.response.set_cookie('key', self.data, secret=self.secret)
        pairs = self.get_pairs()
        self.set_pairs([(k+'xxx', v) for (k, v) in pairs])
        result = bottle.request.get_cookie('key', secret=self.secret)
        self.assertEqual(None, result)

if __name__ == '__main__': #pragma: no cover
    unittest.main()


text:
typedef enum : NSUInteger {
    TFPhoneNum = 101,
    TFNickname,
    TFInviCode
} TFType;

@interface LoginVC ()
@property (weak, nonatomic) IBOutlet ZYTextField *phoneTextF;
@property (weak, nonatomic) IBOutlet ZYTextField *nameTextF;
@property (weak, nonatomic) IBOutlet ZYTextField *inviteCodeTextF;
@property (weak, nonatomic) IBOutlet UITextField *questionTextF;
@property (weak, nonatomic) IBOutlet UITextField *answerTextF;
@property (strong, nonatomic) LoginVM *vm;
@property (strong, nonatomic) NSString *phone;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;
@end

@implementation LoginVC

#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];

    [self initNavigationBar];
    _submitBtn.enabled = NO;
    [_submitBtn setBackgroundImage:[UIImage imageWithColor:kGlobalColor] forState:UIControlStateNormal];
    [_submitBtn setBackgroundImage:[UIImage imageWithColor:kGrayColor] forState:UIControlStateDisabled];

    RAC(self.submitBtn, enabled) = \
    [RACSignal combineLatest:@[
                               self.phoneTextF.rac_textSignal,
                               self.nameTextF.rac_textSignal,
                               self.inviteCodeTextF.rac_textSignal,
                               self.questionTextF.rac_textSignal,
                               self.answerTextF.rac_textSignal
                               ]
                      reduce:^(NSString *phone, NSString *name, NSString *inviteCode, NSString *question, NSString *answer) {
//                         return @(phone.length == 11 && name.length > 0 && inviteCode.length == 6 && question.length > 0 && answer.length > 0);
                          return @1;
                    }];
}

- (void)initNavigationBar
{
    self.title = @"注册";
    self.bHideNavigationBottomLine = YES;
}

#pragma mark - button action
- (IBAction)clickSubmit:(UIButton *)sender {

    User *userInfo = USERDEFAULTS.userInfo;
    userInfo.phone = _phone;

    self.bHud = YES;
    [_vm verifyPhoneHasRegistered:_phone responseBlock:^(NSString *msg, id data) {
        self.bHud = NO;
        if (data == 0) {
            NSLog(@"该号码已经注册过");
            return ;
        }
        [UserDefaults saveUserInfo:userInfo];
        [self pushViewController:@"SetGestureCodeVC" Param:nil];
    }];
}

- (IBAction)helpBtnClick:(id)sender {
    UIAlertController *alertCon = [UIAlertController alertControllerWithTitle:@"" message:@"通过唯一的邀请码才能注册,您可以从您身边的朋友中获得" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAct = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
    [alertCon addAction:okAct];
    [self presentViewController:alertCon animated:YES completion:nil];
}

#pragma mark - text field action
- (IBAction)textFieldDidChanged:(UITextField *)sender {

    if (sender.tag == TFPhoneNum) {
        if (sender.text.length > 11) {
            sender.text = [sender.text substringToIndex:11];
        }
    }
    if (sender.tag == TFInviCode) {
        if (sender.text.length > 6) {
            sender.text = [sender.text substringToIndex:6];
        }
    }
}

- (IBAction)textFieldEditingDidEnd:(UITextField *)sender {
    switch (sender.tag) {
        case TFPhoneNum:
        {
            [self tfCheck:[Util checkMoblieNumber:sender.text]
            WithTextField:sender];
        }
            break;
        case TFNickname:
        {
            if (sender.text.length > 0) {
                [self tfCheck:YES WithTextField:sender];
            } else {
                [self tfCheck:NO WithTextField:sender];
            }
        }
            break;
        case TFInviCode:
        {
            if (sender.text.length == 6) {
                [self tfCheck:YES WithTextField:sender];
            } else {
                [self tfCheck:NO WithTextField:sender];
            }
        }
            break;
    }
}

#pragma mark private
- (void)tfCheck:(BOOL)check WithTextField:(UITextField *)textf
{
    ZYTextField *tf = (ZYTextField *)textf;

    if (check == YES) {
        [tf setLineColor:kGrayColor];
        _phone = tf.text;
    } else {
        [tf setLineColor:[UIColor redColor]];
    }
}

@end


text:
from django.db import models
from taggit.managers import TaggableManager

class UserProfile(models.Model):
    username = models.CharField(max_length=5000)
    friends = models.CharField(max_length=5000)
    date_created = models.DateField()
    bio = models.TextField(default="Default bio")
    livesin = models.TextField(default="Earth")
    about = models.TextField()
    memories = models.CharField(max_length=5000)
    propic = models.FileField(upload_to="memorylane/static/images/profile")
    image = models.FileField(upload_to="memorylane/static/user-images", default="memorylane/static/user-images/Default.png")

    def __str__(self):
        return self.first_name + " " + self.last_name

class Memory(models.Model):
    name = models.CharField(max_length=100)
    location = models.CharField(max_length=100)
    lat = models.CharField(default=0, max_length=5000)
    lng = models.CharField(default=0, max_length=5000)
    image = models.FileField(upload_to="memorylane/static/images")
    author_image = models.FileField(default="memorylane/static/user-images/Default.png")
    first_name = models.CharField(max_length=100, default="Memory")
    last_name = models.CharField(max_length=100, default="Lane")
    description = models.TextField()
    author = models.CharField(max_length=100)
    date_created = models.DateField()
    tags = TaggableManager()

    def __str__(self):
    	return self.name

class Photo(models.Model):
    user = models.CharField(max_length=5000)
    photo = models.FileField(upload_to='memorylane/static/images')
    uploaded = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return '%s' % self.title


text:
require 'rails_helper'

describe TopicNotificationsController, type: :request do
  let(:valid_headers) do
    {
      'CONTENT_TYPE' => 'application/octet-stream',
      'ACCEPT' => 'application/octet-stream'
    }.merge(basic_auth_env)
  end

  describe 'POST #create' do
    context 'with default content-type' do
      it 'fails with status code 406' do
        post create_topic_notification_path

        expect(response.code).to eq '406'
      end
    end

    context 'when using binary content-type' do
      let(:create_topic_notification_request) do
        ElloProtobufs::NotificationService::CreateTopicNotificationRequest.new(
          topic: ElloProtobufs::TopicType::ANNOUNCEMENT_TOPIC,
          announcement: create(:protobuf_announcement)
        )
      end

      context 'when the creation succeeds' do
        before do
          successful_context = build_successful_context
          allow(CreateTopicNotification).to receive(:call).and_return(successful_context)

          post create_topic_notification_path, params: create_topic_notification_request.encode, headers: valid_headers
        end

        it 'passes the required params and request body to the interactor' do
          expect(CreateTopicNotification).to have_received(:call).with(
            request: create_topic_notification_request
          )
        end

        it 'succeeds with status code 200' do
          expect(response.code).to eq '200'
        end

        it 'responds with a successful response object' do
          resp = ElloProtobufs::NotificationService::ServiceResponse.decode(response.body)
          expect(resp).to be_success
        end
      end

      context 'when the creation fails' do
        let(:expected_failure_reason) { ElloProtobufs::NotificationService::ServiceFailureReason::UNKNOWN_TOPIC_TYPE }

        before do
          failed_context = build_failed_context(failure_reason: expected_failure_reason)
          allow(CreateTopicNotification).to receive(:call).and_return(failed_context)

          post create_topic_notification_path, params: create_topic_notification_request.encode, headers: valid_headers
        end

        it 'succeeds with status code 200' do
          expect(response.code).to eq '200'
        end

        it 'includes the correct failure reason in the response' do
          resp = ElloProtobufs::NotificationService::ServiceResponse.decode(response.body)
          expect(resp.failure_reason).to eq(expected_failure_reason)
        end
      end
    end

  end
end


text:
import { Component, Directive, Injectable } from '@angular/core';

/**
 * Should be 'Directive'
 */
@Directive({
  selector: '[ngbDirective]'
})
export class NgbDirective {}

/**
 * Should be 'Component'
 */
@Component({
  selector: 'ngb-component'
})
export class NgbComponent {}

/**
 * Should be 'Service'
 */
@Injectable()
export class NgbService {}

/**
 * Should be 'Class'
 */
export class NgbClass {}

/**
 * Should be 'Interface'
 */
export interface NgbInterface {}


text:
LB-API
======

The Lucky Bit API Java wrapper

This library provides some wrapper classes for the Lucky Bit API so that Java applications
can easily access the Lucky Bit database. This would be useful for a bet history analysis
tool, a betting bot, or a bitcoin address scraper (although that would be against the terms
of the license since it's evil).

To use, just call LuckyBit.nameOfAPICall(parameter) for the desired data. An appropriate
object containing the result (or null) will be returned. For data concerning the daily server
seeds and hashes, expect a Daily object that contains the date() of the seed and the data()
which can be seed or hash as requested. Information about the games are contained in the Game
class, and individual bets are represented by the Bet class.

No need to instance any objects. The API wrapper is seamless as long as you don't trouble
yourself with the object factory and connector (the kit package).


text:
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl

from itertools import islice

def normalize_reference(cell_range):
    # Normalize range to a str or None
    if not cell_range:
        cell_range = None
    elif isinstance(cell_range, str):
        cell_range = cell_range.upper()
    else:  # Assume a row generator
        cell_range = tuple(cell_range)
        first_cell = cell_range[0][0]
        last_cell = cell_range[-1][-1]
        cell_range = "%s:%s" % (first_cell.coordinate, last_cell.coordinate)
    return cell_range

class FilterColumn(object):
    __slots__ = ("_vals", "_col_id", "_blank")

    def __init__(self, col_id, vals, blank):
        self._vals = list(vals)
        self.col_id = col_id
        self.blank = blank

    @property
    def col_id(self):
        return self._col_id

    @col_id.setter
    def col_id(self, value):
        self._col_id = int(value)

    @property
    def vals(self):
        return self._vals

    @property
    def blank(self):
        return self._blank

    @blank.setter
    def blank(self, value):
        self._blank = bool(int(value)) if value else False

class SortCondition(object):
    __slots__ = ("_ref", "_descending")

    def __init__(self, ref, descending):
        self.ref = ref
        self.descending = descending

    @property
    def ref(self):
        """Return the ref for this sheet."""
        return self._ref

    @ref.setter
    def ref(self, value):
        self._ref = normalize_reference(value)

    @property
    def descending(self):
        return self._descending

    @descending.setter
    def descending(self, value):
        self._descending = bool(int(value)) if value else False

class AutoFilter(object):
    """Represents a auto filter.

    Don't create auto filters by yourself. It is created by :class:`~openpyxl.worksheet.Worksheet`.
    You can use via :attr:`~~openpyxl.worksheet.Worksheet.auto_filter` attribute.
    """
    __slots__ = ("_ref", "_filter_columns", "_sort_conditions")

    def __init__(self):
        self._ref = None
        self._filter_columns = {}
        self._sort_conditions = []

    @property
    def ref(self):
        """Return the reference of this auto filter."""
        return self._ref

    @ref.setter
    def ref(self, value):
        self._ref = normalize_reference(value)

    @property
    def filter_columns(self):
        """Return filters for columns."""
        return self._filter_columns

    def add_filter_column(self, col_id, vals, blank=False):
        """
        Add row filter for specified column.

        :param col_id: Zero-origin column id. 0 means first column.
        :type  col_id: int
        :param vals: Value list to show.
        :type  vals: str[]
        :param blank: Show rows that have blank cell if True (default=``False``)
        :type  blank: bool
        """
        filter_column = FilterColumn(col_id, vals, blank)
        self._filter_columns[filter_column.col_id] = filter_column
        return filter_column

    @property
    def sort_conditions(self):
        """Return sort conditions"""
        return self._sort_conditions

    def add_sort_condition(self, ref, descending=False):
        """
        Add sort condition for cpecified range of cells.

        :param ref: range of the cells (e.g. 'A2:A150')
        :type  ref: string
        :param descending: Descending sort order (default=``False``)
        :type  descending: bool
        """
        sort_condition = SortCondition(ref, descending)
        self._sort_conditions.append(sort_condition)
        return sort_condition


text:
    /**
     * @module TimeSpan
     */

    /**
     * Time span error
     * @class TimeSpanError
     * @extends {Error}
     * @constructor
     * @param {String} type Error type identifier
     * @param {String} message Error description
     */
    function TimeSpanError(type,message) {
      this.name = "TimeSpanError";
      this.message = message;

      this.type = type;

      this.getType = function(){
        return this.type;
      };

    }

    TimeSpanError.prototype = new Error();
    TimeSpanError.prototype.constructor = TimeSpanError;


text:
import { graphql, useStaticQuery } from 'gatsby'
import React from 'react'
import ExecPreview from '../components/execPreview'
import Layout from '../components/layout'
import SEO from '../components/seo'
import ContactForm from '../components/contactForm'

const IndexPage = () => {
  const execs = useStaticQuery(graphql`
    {
      allExecsYaml {
        nodes {
          name
          role
          photo {
            childImageSharp {
              fluid(maxWidth: 200) {
                ...GatsbyImageSharpFluid
              }
            }
          }
        }
      }
    }
  `).allExecsYaml.nodes

  return (
    <Layout>
      <SEO title="Home" />

We Are Code Network

Build anything, as long as it's awesome

        Our members are heavily involved in the local and international startup
        scene. Our goal as an organisation is to help create the best developer
        talent in the world, starting here in Brisbane. We're based at QUT and
        are expanding to other universities and organisations in the area.

        This site is a work in progress. If you'd like to contribute, you can do
        so here

Our Team

      <ExecPreview execs={execs} />
      <ContactForm />
    </Layout>
  )
}

export default IndexPage


text:
process.title = 'dnster';

require('../lib/cli');


text:
import unittest
"""
An element in a sorted array can be found in O(logN) time using Binary Search.
But suppose, we rotate an ascending order sorted array by an unknown amount. So
for instance, 1 2 3 4 5 may become 3 4 5 1 2. Devise a way to find an element in
rotated array in O(logN) time.
"""

"""
Approach:
1. The idea is to find a pivot element in rotated array.
2. A pivot element is such that element next to it is smaller than it. (Eg. 5 in above example)
3. Once we find such an element, we know the subarrays to its left and right are already sorted.
   So we can do a normal Binary Search on one of the two subarrays.
4. The trick is to find the pivot element in O(logN) time.
"""

def find_pivot(arr, low, high):
    if low > high:
        return -1
    mid = (low + high) / 2
    if mid < high and arr[mid] > arr[mid+1]:
        return mid
    if low < mid and arr[mid] < arr[mid-1]:
        return mid-1
    if arr[low] > arr[mid]:
        return find_pivot(arr, low, mid-1)
    elif arr[mid] > arr[high]:
        return find_pivot(arr, mid+1, high)
    else:
        # Handle test cases 2 and 3 as mentioned in test runner.
        left = find_pivot(arr, low, mid-1)
        right = find_pivot(arr, mid+1, high)
        if left == -1 and right == -1:
            return -1
        return left if left != -1 else right

def binary_search(arr, low, high, key):
    if low > high:
        return -1
    mid = (low + high) / 2
    if arr[mid] == key:
        return mid
    if arr[mid] < key:
        return binary_search(arr, mid+1, high, key)
    return binary_search(arr, low, mid-1, key)

def search_sorted_rotated(arr, key):
    n = len(arr)
    pivot = find_pivot(arr, 0, n-1)
    if pivot == -1:
        return binary_search(arr, 0, n-1, key)
    if arr[pivot] == key:
        return pivot
    if arr[0] < key:
        return binary_search(arr, 0, pivot-1, key)
    return binary_search(arr, pivot+1, n-1, key)

class TestSearchSortedRotated(unittest.TestCase):

    def test_search_sorted_rotated(self):
        arr = [3, 4, 5, 1, 2]
        self.assertEqual(search_sorted_rotated(arr, 1), 3)
        arr = [2, 2, 2, 2, 2, 0, 2]
        self.assertEqual(search_sorted_rotated(arr, 0), 5)
        arr = [2, 0, 2, 2, 2, 2, 2]
        self.assertEqual(search_sorted_rotated(arr, 0), 1)


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>summernote</title>

  <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">

  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" />

  <link rel="stylesheet" href="../dist/summernote.css">