text:
JINGO
=====

A simple git based _wiki engine_ written for Node.js.

The aim of this wiki engine is to provide a very easy way to create a centralized
documentation area for people used to working with git and markdown. It should fit well
into a development team without the need to learn or install ad-hoc servers or applications.
Jingo is very much inspired by the github wiki system (gollum), but tries to be more
a stand-alone and complete system than gollum is.

Think of jingo as "the github wiki, without github but with more features". "Jingo"
means "Jingo is not Gollum" for a reason.

There is a demo server running at http://jingo.cica.li:6067/wiki/home

Features
--------

- No database: uses a git repository as the document archive
- No user management: authentication provided via with Google logins or simple login
- Markdown for everything, [github flavored](http://github.github.com/github-flavored-markdown/)
- Uses [Codemirror](http://codemirror.net/) or [Markitup](http://markitup.jaysalvat.com/home/) as the markup editor, with a nice (ajax) preview (`features` key in the config file)
- Provides a "distraction free", almost full screen mode
- Inspired by the well known github [Gollum](https://github.com/github/gollum) wiki
- Show differences between document revisions
- Search through the content _and_ the page names
- Layout accepts custom sidebar and footer
- Gravatar support
- Can include IFRAMEs in the document (es: embed a Google Drive document)
- Can use custom CSS and JavaScript scripts
- White list for authorization on page reading and writing
- Detects unwritten pages (will appear in red)
- Automatically push to a remote

For code syntax highlighting, Jingo uses the `node-syntaxhighlighter` module. For the
list of supported languages, please refer to [this page](https://github.com/thlorenz/node-syntaxhighlighter/tree/master/lib/scripts).

Known limitations
-----------------

- The authentication is mandatory (no anonymous writing allowed). See also issue #4
- The repository is "flat" (no directories or namespaces)
- Authorization is only based on a regexp'ed white list with matches on the user email address
- There is one authorization level only (no "administrators" and "editors")
- At the moment there is no "restore previous revision", just a revision browser
- No scheduled pull or fetch from the remote is provided (because handling conflicts would be
  a bit too... _interesting_)

Please note that at the moment it is quite "risky" to have someone else, other than jingo itself,
have write access to the remote jingo is pushing to. The push operation is supposed to always be
successfull and there is no pull or fetch. You can of course manage to handle pull requests yourself.

Installation
------------

`npm install jingo` or download the whole thing and run "npm install"

Jingo needs a config file and to create a sample config file, just run `jingo -s`, redirect the
output on a file and then edit it. The config file contains all the available configuration keys.
Be sure to provide a valid server hostname (like wiki.mycompany.com) for Google Auth to be able
to get back to you.

If you define a `remote` to push to, then jingo will automatically issue a push to that remote every
`pushInterval` seconds. You can also specify a branch using the syntax "remotename branchnama". If you
don't specify a branch, that will be `master`.
Please note that before the `push`, a `pull` will also be issued (at the moment Jingo will not try
to resolve conflicts, though).

The basic command to run the wiki will then be

`jingo -c /path/to/config.yaml` (using `forever -w` is highly recommended, though)

Before running jingo you need to initialize its git repository somewhere (`git init` is enough).

If you define a remote to push to, be sure that the user who'll push has the right to do so.

If your documents reside in subdirectory of your repository, you need to specify its name using the
`docSubdir` configuration option. The `repository` path _must_ be an absolute path pointing to the
root of the repository.

If you want your wiki server to only listen to your `localhost`, set the configuration key `localOnly` to true.

Common problems
---------------

Sometimes upgrading your version of node.js could break the `iconv` module. Try updating it with `npm install iconv`.

Authentication and Authorization
--------------------------------

The _authorization_ section of the config file has two keys: anonRead and validMatches. If the
anonRead is true, then anyone can read anything.
If anonRead is false you need to authenticate also for reading and then the email of the user _must_
match at least one of the regular expressions provided via validMatches, which is a comma separated
list. There is no "anonWrite", though. To edit a page the user must be authenticated.

The authentication is mandatory to edit pages from the web interface, but jingo works on a git repository;
that means that you could skip the authentication altogether and edit pages with your editor and push
to the remote that jingo is serving.

You can enable two authentication methodologies: _Google logins_ or a simple, locally verified
username/password credentials match (called "alone").

If you use the _alone_ method, you can have _only one user_ accessing the wiki (thus the name).

The _Google Login_ doesn't need any configuration option: just enable it in the config file (it's enabled by default),
but assure yourself that the `baseUrl` configuration variable  points to something that Google can reach ("http://localhost:6067"
is fine but you could have Jingo proxied via another web server which listens on the :80, for example).

The _alone_ method uses a `username`, a `passwordHash` and optionally an `email`. The password is hashed
using a _non salted_ SHA-1 algorithm, which makes this method not the safest in the world but at least you don't have
a clear text password in the config file. To generate the hash, use the `--hash-string` program option: once
you get the hash, copy it in the config file.

You can enable both authentication options at the same time. The `alone` is disabled by default.

Customization
-------------

You can customize jingo in four different ways:

- add a left sidebar to every page: just add a file named `_sidebar.md` containing the markdown you
  want to display to the repository. You can edit or create the sidebar from jingo itself, visiting
  `/wiki/_sidebar` (note that the title of the page in this case is useless)
- add a footer to every page: the page you need to create is "_footer.md" and the same rules for the
  sidebar apply
- add a custom CSS file, included in every page as the last file. The name of the file must be `_style.css`
  and must reside in the repository. It is not possible to edit the file from jingo itself
- add a custom JavaScript file, included in every page as the last JavaScript file. The name of the file must
  be `_script.js` and must reside in the repository. It is not possible to edit the file from jingo itself

All those files are cached (thus, not re-read for every page load, but kept in memory). This means that for
every modification in _style.css and _script.js you need to restart the server (sorry, working on that).
This is not true for the footer and the sidebar but ONLY IF you edit those pages from jingo (which in that
case will clear the cache by itself).

jingo uses twitter Bootstrap and jQuery as its front-end components.

Editing
-------

To link to another Jingo wiki page, use the Jingo Page Link Tag.

    [[Jingo Works]]

The above tag will create a link to the corresponding page file named
`jingo-works.md`. The conversion is as follows:

  1. Replace any spaces (U+0020) with dashes (U+002D)
  2. Replace any slashes (U+002F) with dashes (U+002D)

If you'd like the link text to be something that doesn't map directly to the
page name, you can specify the actual page name after a pipe:

    [[How Jingo works|Jingo Works]]

The above tag will link to `jingo-works.md` using "How Jingo Works" as the link text.


text:
<?php
namespace Satooshi\Bundle\CoverallsV1Bundle\Entity;

use Satooshi\ProjectTestCase;

/**
 * @covers Satooshi\Bundle\CoverallsV1Bundle\Entity\SourceFile
 * @covers Satooshi\Bundle\CoverallsV1Bundle\Entity\Coveralls
 *
 * @author Kitamura Satoshi <with.no.parachute@gmail.com>
 */
class SourceFileTest extends ProjectTestCase
{
    protected function setUp()
    {
        $this->projectDir = realpath(__DIR__ . '/../../../..');

        $this->setUpDir($this->projectDir);

        $this->filename = 'test.php';
        $this->path     = $this->srcDir . DIRECTORY_SEPARATOR . $this->filename;

        $this->object = new SourceFile($this->path, $this->filename);
    }

    // getName()

    /**
     * @test
     */
    public function shouldHaveNameOnConstruction()
    {
        $this->assertEquals($this->filename, $this->object->getName());
    }

    // getSource()

    /**
     * @test
     */
    public function shouldHaveSourceOnConstruction()
    {
        $expected = trim(file_get_contents($this->path));

        $this->assertEquals($expected, $this->object->getSource());
    }

    // getCoverage()

    /**
     * @test
     */
    public function shouldHaveNullCoverageOnConstruction()
    {
        $expected = array_fill(0, 9, null);

        $this->assertEquals($expected, $this->object->getCoverage());
    }

    // getPath()

    /**
     * @test
     */
    public function shouldHavePathOnConstruction()
    {
        $this->assertEquals($this->path, $this->object->getPath());
    }

    // getFileLines()

    /**
     * @test
     */
    public function shouldHaveFileLinesOnConstruction()
    {
        $this->assertEquals(9, $this->object->getFileLines());
    }

    // toArray()

    /**
     * @test
     */
    public function shouldConvertToArray()
    {
        $expected = array(
            'name'     => $this->filename,
            'source'   => trim(file_get_contents($this->path)),
            'coverage' => array_fill(0, 9, null),
        );

        $this->assertEquals($expected, $this->object->toArray());
        $this->assertEquals(json_encode($expected), (string)$this->object);
    }

    // addCoverage()

    /**
     * @test
     */
    public function shouldAddCoverage()
    {
        $this->object->addCoverage(5, 1);

        $expected = array_fill(0, 9, null);
        $expected[5] = 1;

        $this->assertEquals($expected, $this->object->getCoverage());
    }

    // getMetrics()
    // reportLineCoverage()

    /**
     * @test
     */
    public function shouldReportLineCoverage0PercentWithoutAddingCoverage()
    {
        $metrics = $this->object->getMetrics();

        $this->assertEquals(0, $metrics->getStatements());
        $this->assertEquals(0, $metrics->getCoveredStatements());
        $this->assertEquals(0, $metrics->getLineCoverage());
        $this->assertEquals(0, $this->object->reportLineCoverage());
    }

    /**
     * @test
     */
    public function shouldReportLineCoverage100PercentAfterAddingCoverage()
    {
        $this->object->addCoverage(6, 1);

        $metrics = $this->object->getMetrics();

        $this->assertEquals(1, $metrics->getStatements());
        $this->assertEquals(1, $metrics->getCoveredStatements());
        $this->assertEquals(100, $metrics->getLineCoverage());
        $this->assertEquals(100, $this->object->reportLineCoverage());
    }
}

redpajama_set_name: RedPajamaGithub


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PID control
ftoffset = 13.4;
controlGripper('close', leftOrRight);
ft = getFTfromLCM();   %transformForceToGlobal

force_x = -(ft(1) - ftoffset);
torque_x = ft(4);
force_threshold = 1;
fprintf('force_x = %f, torque_x = %f\n', force_x, torque_x);
while abs(force_x) > force_threshold
  %grasp_pos(3) = 0.002 * force_x + grasp_pos(3);  %% or set directly to current pos
  controlGripper('open', leftOrRight);

  %% show current tip position
  if getJointAvailable
    q = getCurrentQfromLCM();
  else
    q = planner.getPrepareQ();
  end

  kinsol = r.doKinematics(q(1:dof,1));
  gripper_pt = [0.18,0,0]';
  currpos = r.forwardKin(kinsol,findLinkInd(r,sprintf('%s_gripper_palm_link', leftOrRight)), gripper_pt);
  grasp_pos
  currpos
  grasp_pos = currpos;
  grasp_pos(3) = grasp_pos(3) + 0.002 * force_x;

  % 3 Go grasp
  disp('3. Go to grasp pose');
  %  -1 Get Current joints
  if getJointAvailable
    q0 = getCurrentQfromLCM();
  else
    q0 = q_end(1:dof,1);
  end
  %  -2 Set destination to drawer open pos
  pos_final_xyz = grasp_pos;
  pos_final_orient = grasp_orient;  % (yaw, pitch, roll)
  keepSameOrient = true;
  %  -3 Create line plan
  [xtraj,snopt_info,infeasible_constraint,q_end] = ...
              planner.createLinePlanWOrient(q0, pos_final_xyz, pos_final_orient, 1, ...
              basefixed, torsofixed, keepSameOrient, 5);
  %  -4 Play it in viewer
  planner.v.playback(xtraj);
  mypause()
  %  -5 Publish
  if toPublish
    planner.publishTraj(xtraj,snopt_info);
    mypause()
  end

  controlGripper('close', leftOrRight);
  ft = getFTfromLCM();   %transformForceToGlobal
  force_x = -(ft(1) - ftoffset);
  fprintf('force_x = %f, torque_x = %f\n', force_x, torque_x);
end


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Suburb / Russia</title>
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&subset=cyrillic-ext" rel="stylesheet">
  <link rel="stylesheet" href="/public/normalize.css">
  <link rel="stylesheet" href="/public/style1.css">

<%= body %>


text:
// Copyright (c) PocketCampus.Org 2014-15
// See LICENSE file for more details
// File author: Solal Pirelli

// Design data for ViewModels

#if DEBUG
using PocketCampus.Common.Services.Design;
using PocketCampus.IsAcademia.Services.Design;
using ThinMvvm.Design;
#endif

namespace PocketCampus.IsAcademia.ViewModels.Design
{
    public sealed class Design
    {
#if DEBUG
        public MainViewModel Main { get; private set; }

        public Design()
        {
            Main = new MainViewModel( new DesignDataCache(), new DesignNavigationService(), new DesignSecureRequestHandler(), new DesignIsAcademiaService() );

            Main.OnNavigatedToAsync();
        }
#endif
    }
}


text:
package io.quarkus.arc.deployment;

import org.jboss.jandex.DotName;

import io.quarkus.builder.item.MultiBuildItem;

public final class ConfigInjectionStaticInitBuildItem extends MultiBuildItem {
    private final DotName declaringCandidate;

    public ConfigInjectionStaticInitBuildItem(final DotName declaringCandidate) {
        this.declaringCandidate = declaringCandidate;
    }

    public DotName getDeclaringCandidate() {
        return declaringCandidate;
    }
}


text: Self-contained Java test cases from my StackOverflow posts.


text:
package com.panjin.design.create.builder;

/**
 *
 *
 * @author panjin
 * @version $Id: BuilderTest.java 2016年12月23日 下午4:05:14 $
 */
public class BuilderTest {

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        PersonDirector pd = new PersonDirector();
        IPersonBuilder personBuilder = new ManBuilder();
        Person person = pd.constructPerson(personBuilder);
        System.out.println(person);
    }

}


text:
@class NSString, XCTSourceCodeContext;

@interface XCTSkippedTestContext : NSObject
{
    NSString *_summary;
    NSString *_explanation;
    NSString *_evaluatedExpression;
    NSString *_message;
    XCTSourceCodeContext *_sourceCodeContext;
}

- (void).cxx_destruct;
@property(readonly) XCTSourceCodeContext *sourceCodeContext; // @synthesize sourceCodeContext=_sourceCodeContext;
@property(readonly, copy) NSString *message; // @synthesize message=_message;
@property(readonly, copy) NSString *evaluatedExpression; // @synthesize evaluatedExpression=_evaluatedExpression;
@property(readonly, copy) NSString *explanation; // @synthesize explanation=_explanation;
@property(readonly, copy) NSString *summary; // @synthesize summary=_summary;
- (id)initWithError:(id)arg1 evaluatedExpression:(id)arg2 message:(id)arg3 sourceCodeContext:(id)arg4;
- (id)initWithException:(id)arg1 evaluatedExpression:(id)arg2 message:(id)arg3 sourceCodeContext:(id)arg4;
- (id)initWithExpectedValue:(_Bool)arg1 evaluatedExpression:(id)arg2 message:(id)arg3 sourceCodeContext:(id)arg4;
- (id)initWithExplanation:(id)arg1 evaluatedExpression:(id)arg2 message:(id)arg3 sourceCodeContext:(id)arg4;

@end


text:
System.register(['angular2/core', 'angular2/router'], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var core_1, router_1;
    var ClassroomService;
    return {
        setters:[
            function (core_1_1) {
                core_1 = core_1_1;
            },
            function (router_1_1) {
                router_1 = router_1_1;
            }],
        execute: function() {
            // export interface Room {
            //   name: string,
            //   secretCode: string
            // }
            // Use the @Injectable Decorator to define the following class as a injectable service
            ClassroomService = (function () {
                function ClassroomService(_router) {
                    var _this = this;
                    this._router = _router;
                    // the reason why we use errorState as a object and not a boolean is because we want to take advantage of the reference vs copy concept
                    // when we reference a (service) object in a component, we are reference the object instead of copying it
                    // therefore when the (service) object changes, the component property immediately changes and the one way binding in student join component is immediately reflected.
                    this.errorState = {
                        secretCodeError: false
                    };
                    this.studentConnections = {
                        number: 0,
                        list: ""
                    };
                    this.totalNumberOfReadyStudents = {
                        number: 0
                    };
                    this.isStudentReady = {
                        status: false
                    };
                    // ignore this silly error
                    //connect the socket.io client to our webserver (assuming it's running on the same port)
                    this.socket = io(window.location.host);
                    // ADD SOCKET EVENT LISTENERS
                    // We need this event listeners to be present the moment the component is created
                    // ================================== Both Instructor & Students ==================================
                    this.socket.on('connect', function () {
                        console.log('Connected to Chat Socket');
                    });
                    this.socket.on('disconnect', function () {
                        console.log('Disconnected from Chat Socket');
                        // just in case navigation
                        _this._router.navigate(['menu']);
                    });
                    // ================================== Instructor ==================================
                    this.socket.on('createSecretCode', function (room) {
                        console.log('Recieved Room Object:', room);
                        _this.room = room;
                        _this._router.navigate(['Instructor-dashboard']);
                    });
                    this.socket.on('updateNumberOfRoomConnections', function (studentConnections) {
                        console.log('Room connections changed, total number of students: ', studentConnections);
                        _this.studentConnections.number = studentConnections;
                    });
                    // ================================== Student ==================================
                    this.socket.on('secretCodeExist', function (correctSecretCodeWithObject) {
                        // we want to do the room entry logic here
                        if (correctSecretCodeWithObject.secretCodeExist) {
                            _this._router.navigate(['Student-dashboard']);
                            _this.errorState.secretCodeError = false;
                            // =>> added this shit in when we were sleepy
                            _this.room = correctSecretCodeWithObject.room;
                        }
                        else {
                            _this.errorState.secretCodeError = true;
                        }
                        console.log('status of secretCodeError', _this.errorState);
                    });
                    this.socket.on('startStudentReady', function () {
                        var audio = new Audio();
                        audio.src = "student_notification_sound.wav";
                        audio.load();
                        audio.play();
                        _this._router.navigate(['Student-ready']);
                    });
                    this.socket.on('studentsCloseClass', function () {
                        _this._router.navigate(['Menu']);
                        // when you close the class, you want to set the ready status back to false
                        _this.isStudentReady.status = false;
                        _this.totalNumberOfReadyStudents.number = 0;
                        // trying an alternative solution first
                        // this.studentConnections.number = 0
                    });
                    // ========================== Ready  =============================
                    this.socket.on('updateStudentReady', function (totalNumberOfReadyStudents) {
                        console.log("number of students are ready", totalNumberOfReadyStudents);
                        _this.totalNumberOfReadyStudents.number = totalNumberOfReadyStudents;
                    });
                    this.socket.on('RecievedYourLovelyReadyResponse', function () {
                        console.log('We received your lovely ready response my young padawan');
                        _this.isStudentReady.status = true;
                    });
                    this.socket.on('RecievedYourLovelyNotReadyResponse', function () {
                        console.log('We received your lovely not ready response my young padawan');
                        _this.isStudentReady.status = false;
                    });
                    this.socket.on('studentsEndReadySession', function () {
                        var audio = new Audio();
                        audio.src = "close_ready_notification.wav";
                        audio.load();
                        audio.play();
                        _this._router.navigate(['Student-dashboard']);
                        _this.isStudentReady.status = false;
                        _this.totalNumberOfReadyStudents.number = 0;
                    });
                    //update total ready students (need to send to server?)
                    // end of constructor braces
                }
                // ================================== Accessor (Getter) Functions ==================================
                // ================================== Instructor ==================================
                ClassroomService.prototype.getRoom = function () {
                    // console.log('look here',this.room)
                    return this.room;
                };
                ClassroomService.prototype.getStudentConnections = function () {
                    return this.studentConnections;
                };
                // ================================== Students ==================================
                ClassroomService.prototype.getErrorState = function () {
                    console.log(this.errorState);
                    return this.errorState;
                };
                // ================================== Ready ==================================
                ClassroomService.prototype.getTotalNumberOfReadyStudents = function () {
                    return this.totalNumberOfReadyStudents;
                };
                ClassroomService.prototype.getIsStudentReady = function () {
                    return this.isStudentReady;
                };
                // Menu Component
                // Instructor ClassName Component
                ClassroomService.prototype.submitClassName = function (className) {
                    console.log('My class name is: ', className);
                    this.socket.emit('submitClassName', className);
                };
                // Instructor Dashboard Component
                ClassroomService.prototype.instructorCallReady = function () {
                    console.log("instructor pressed ARE YOU READY");
                    this.socket.emit('instructorCallReady');
                };
                ClassroomService.prototype.closeClass = function () {
                    console.log('Closing Class: ');
                    this.socket.emit('closeClass');
                    // server sockets receive closeroom and then emits out to students to close their room as well
                    // considering not storing anything on the client side and removing room
                    // we don't necessarily need this because when someone joins the room in future, he would create a new room and the existing room stored on the client side will be overwritten
                    // this.room = {
                    //   name: null,
                    //   secretCode: null,
                    // };
                };
                // Instructor Ready Component
                ClassroomService.prototype.instructorEndsReadySession = function () {
                    this.socket.emit('instructorEndsReadySession');
                };
                // Student Profile Component
                ClassroomService.prototype.submitProfileName = function (profileName) {
                    console.log('My profile name is: ', profileName);
                    // console.log(this.user);
                    this.user = { name: profileName };
                    this.socket.emit('submitProfileName', profileName);
                };
                // Student Join Component
                ClassroomService.prototype.submitSecretCode = function (secretCode) {
                    console.log('Secret Code is: ', secretCode);
                    this.socket.emit('submitSecretCode', secretCode);
                };
                // Student Dashboard Component
                ClassroomService.prototype.leaveClass = function () {
                    console.log("I'm leaving the class");
                    this.socket.emit('studentLeaveClass');
                };
                // Student Ready Component
                ClassroomService.prototype.studentReady = function () {
                    console.log("student pressed i'm ready button");
                    this.socket.emit('studentReady');
                };
                ClassroomService.prototype.studentNotReady = function () {
                    console.log("student changed to not ready");
                    this.socket.emit('studentNotReady');
                };
                ClassroomService = __decorate([
                    core_1.Injectable(),
                    __metadata('design:paramtypes', [router_1.Router])
                ], ClassroomService);
                return ClassroomService;
            }());
            exports_1("ClassroomService", ClassroomService);
        }
    }
});

//# sourceMappingURL=classroom.service.js.map


text:
@implementation NVFundationSerialization

- (id) serialize:(id)object {
    return nil;
}

+ (NVDataModel*) serializeDictionary:(NSDictionary *)dictionary {
    return nil;
}

+ (NVListModel *) serializeArray:(NSArray *)array
{
    return nil;
}

+ (NVListModel *) serializeArray:(NSArray *)array withClass:(Class)classInstance
{
    return nil;
}

+ (NVDataModel*) serializeDictionary:(NSDictionary *)dictionary withClass:(Class)classInstance {

//    NSString* className = NSStringFromClass(classInstance);

    NVDataModel* dataModel = [[classInstance alloc] init];
    [dataModel conformsToProtocol:@protocol(NVFundationSerializedObjectProtocol)];

    dataModel = [[classInstance alloc] initWithDictionary:dictionary];
    return dataModel;
}

@end

@implementation NVFundationDeserialization

- (id) deserialize:(id)object {
    return nil;
}

@end


text:
package org.apache.flink.table.planner.plan.batch.table

import org.apache.flink.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.planner.runtime.utils.JavaUserDefinedAggFunctions.PandasAggregateFunction
import org.apache.flink.table.planner.utils.TableTestBase
import org.junit.Test

class PythonOverWindowAggregateTest extends TableTestBase {

  @Test
  def testPandasRangeOverWindowAggregate(): Unit = {
    val util = batchTestUtil()
    val sourceTable = util.addTableSource[(Int, Long, Int, Long)](
      "MyTable", 'a, 'b, 'c, 'rowtime.rowtime)
    val func = new PandasAggregateFunction

    val resultTable = sourceTable
      .window(
        Over
          partitionBy 'b
          orderBy 'rowtime
          preceding UNBOUNDED_RANGE
          as 'w)
      .select('b, func('a, 'c) over 'w)

    util.verifyExecPlan(resultTable)
  }

  @Test
  def testPandasRowsOverWindowAggregate(): Unit = {
    val util = batchTestUtil()
    val sourceTable = util.addTableSource[(Int, Long, Int, Long)](
      "MyTable", 'a, 'b, 'c, 'rowtime.rowtime)
    val func = new PandasAggregateFunction

    val resultTable = sourceTable
      .window(
        Over
          partitionBy 'b
          orderBy 'rowtime
          preceding 10.rows
          as 'w)
      .select('b, func('a, 'c) over 'w)

    util.verifyExecPlan(resultTable)
  }
}


text:
<?php

require __DIR__ . '/vendor/autoload.php';

class Redirector {

	/**
	 * Android URL
	 * @var string
	 */
	private $androidURL;

	/**
	 * iOS URL
	 * @var string
	 */
	private $iOSURL;

	/**
	 * Optional URL
	 * @var string
	 */
	private $optionalURL;

	/**
	 * Convenience Constructor
	 * @param string $androidURL  Android URI
	 * @param string $iOSURL      iOS URI
	 * @param string $optionalURL An optional URI
	 */
	public function __construct($androidURL = '', $iOSURL = '', $optionalURL = '') {

		if (strlen($androidURL) == 0 && strlen($iOSURL) == 0 && strlen($optionalURL) == 0) {
			throw new Exception("Debes especificar al menos una URL!");
		}

		if (strlen($androidURL) > 0) {
			$this->androidURL = $androidURL;
		}

		if (strlen($iOSURL) > 0) {
			$this->iOSURL = $iOSURL;
		}

		if (strlen($optionalURL) > 0) {
			$this->optionalURL = $optionalURL;
		}

	}

	/**
	 * Distributor Function
	 */
	public function distribute() {

		$detect = new Mobile_Detect;

		if ( $detect->isiOS() ) {

			$finalURL = strlen($this->iOSURL) > 0 ? $this->iOSURL : (
							strlen($this->optionalURL) > 0 ? $this->optionalURL : (
								$this->androidURL
							)
						);

			$this->redirect($finalURL);

		} else if ( $detect->isAndroidOS() ) {

			$finalURL = '';

			// To open de Market Place for Android devices, we must transform the original URL into a URL Scheme
			if (strlen($this->androidURL) > 0) {

				$urlQuery = parse_url($this->androidURL, PHP_URL_QUERY);
				$finalURL = "market://details?" . $urlQuery;

			} else {

				$finalURL = strlen($this->optionalURL) > 0 ? $this->optionalURL : $this->iOSURL;

			}

			$this->redirect($finalURL);

		} else {

			$finalURL = strlen($this->optionalURL) > 0 ? $this->optionalURL : (
							strlen($this->androidURL) > 0 ? $this->androidURL : (
								$this->iOSURL
							)
						);

			$this->redirect($finalURL);

		}
	}

	/**
	 * Redirector Function
	 * @param  strong $finalURL finalURL
	 */
	public function redirect($finalURL) {

		if ( $this->isValidURL($finalURL) === TRUE ) {
			header('Location: ' . $finalURL);
			exit;
		} else {
			throw new Exception("La URL especificada no es válida: " . $finalURL);
		}
	}

	/**
	 * TODO: Check if URL is valid
	 * @return boolean URL redirect
	 */
	public function isValidURL($URL) {
		return !filter_var($URL, FILTER_VALIDATE_URL) === FALSE;
	}

}


text:
'use strict';

const expect = require('../../chai').expect;
const EOL = require('os').EOL;
const commandOptions = require('../../factories/command-options');
const Task = require('../../../lib/models/task');
const RSVP = require('rsvp');
const td = require('testdouble');
const PortFinder = require('portfinder');

const Promise = RSVP.Promise;
const getPort = RSVP.denodeify(PortFinder.getPort);

const ServeCommand = require('../../../lib/commands/serve');

describe('serve command', function() {
  let tasks, options, command;

  beforeEach(function() {
    tasks = {
      Serve: Task.extend(),
    };

    options = commandOptions({
      tasks,
    });

    td.replace(tasks.Serve.prototype, 'run', td.function());

    command = new ServeCommand(options);
  });

  afterEach(function() {
    td.reset();
  });

  it('has correct default options', function() {
    return command.validateAndRun([
      '--port', '0',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.port).to.be.gte(4200, 'has correct port');
      expect(captor.value.liveReloadPort).to.be.within(7020, 65535, 'has correct liveReload port');
    });
  });

  it('setting --port without --live-reload-port', function() {
    return getPort().then(function(port) {
      return command.validateAndRun([
        '--port', `${port}`,
      ]).then(function() {
        let captor = td.matchers.captor();
        td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
        expect(captor.value.port).to.equal(port, 'has correct port');
        expect(captor.value.liveReloadPort).to.be.within(7020, 65535, 'has correct liveReload port');
      });
    });
  });

  it('setting both --port and --live-reload-port', function() {
    return getPort().then(function(port) {
      return command.validateAndRun([
        '--port', `${port}`,
        '--live-reload-port', '8005',
      ]).then(function() {
        let captor = td.matchers.captor();
        td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
        expect(captor.value.port).to.equal(port, 'has correct port');
        expect(captor.value.liveReloadPort).to.be.within(8005, 65535, 'has live reload port > port');
      });
    });
  });

  if (process.platform !== 'win32') {
    // This test fails on appveyor for an unknown reason. See last few comments
    // on PR https://github.com/ember-cli/ember-cli/pull/5391
    //
    // Works correctly on Travis and has been left for context as it does test
    // a valid code path.

    let testServer = function(opts, test) {
      let server = require('http').createServer(function() {});
      return new Promise(function(resolve) {
        server.listen(opts.port, opts.host, function() {
          resolve(test(opts, server));
        });
      }).finally(function() {
        return new Promise(function(resolve) {
          server.close(function() { resolve(); });
        });
      });
    };

    it('should throw error when -p PORT is taken', function() {
      return testServer({ port: '32773' }, function() {
        return expect(command.validateAndRun(['--port', '32773'])).to.be.rejected.then(err => {
          td.verify(tasks.Serve.prototype.run(), { ignoreExtraArgs: true, times: 0 });
          expect(err.message).to.contain('is already in use.');
        });
      });
    });
  }

  it('allows OS to choose port', function() {
    return command.validateAndRun([
      '--port', '0',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.port).to.be.within(7020, 65535, 'has correct port');
      expect(captor.value.liveReloadPort).to.be.gt(captor.value.port, 'has a liveReload port greater than port');
    });
  });

  it('has correct liveLoadPort', function() {
    return command.validateAndRun([
      '--port', '0',
      '--live-reload-port', '4001',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.liveReloadPort).to.be.gte(4001, 'has correct liveReload port');
    });
  });

  it('has correct liveReloadLoadHost', function() {
    return command.validateAndRun([
      '--port', '0',
      '--live-reload-host', '127.0.0.1',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.liveReloadHost).to.equal('127.0.0.1', 'has correct liveReload host');
    });
  });

  it('has correct liveLoadBaseUrl', function() {
    return command.validateAndRun([
      '--port', '0',
      '--live-reload-base-url', 'http://127.0.0.1:4200/',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.liveReloadBaseUrl).to.equal('http://127.0.0.1:4200/', 'has correct liveReload baseUrl');
    });
  });

  it('has correct proxy', function() {
    return command.validateAndRun([
      '--port', '0',
      '--proxy', 'http://localhost:3000/',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.proxy).to.equal('http://localhost:3000/', 'has correct port');
    });
  });

  it('has correct secure proxy option', function() {
    return command.validateAndRun([
      '--port', '0',
      '--secure-proxy', 'false',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.secureProxy).to.equal(false, 'has correct insecure proxy option');
    });
  });

  it('has correct default value for secure proxy', function() {
    return command.validateAndRun([
      '--port', '0',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.secureProxy).to.equal(true, 'has correct secure proxy option when not set');
    });
  });

  it('requires proxy URL to include protocol', function() {
    return expect(command.validateAndRun([
      '--port', '0',
      '--proxy', 'localhost:3000',
    ])).to.be.rejected.then(error => {
      expect(error.message).to.equal(
        `You need to include a protocol with the proxy URL.${EOL}Try --proxy http://localhost:3000`
      );
    });
  });

  it('has correct default value for transparent proxy', function() {
    return command.validateAndRun([
      '--port', '0',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.transparentProxy).to.equal(true, 'has correct transparent proxy option when not set');
    });
  });

  it('uses baseURL of correct environment', function() {
    options.project.config = function(env) {
      return { baseURL: env };
    };

    return command.validateAndRun([
      '--port', '0',
      '--environment', 'test',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.baseURL).to.equal('test', 'Uses the correct environment.');
    });
  });

  it('host alias does not conflict with help alias', function() {
    return command.validateAndRun([
      '--port', '0',
      '-H', 'localhost',
    ]).then(function() {
      let captor = td.matchers.captor();
      td.verify(tasks.Serve.prototype.run(captor.capture()), { times: 1 });
      expect(captor.value.host).to.equal('localhost', 'has correct hostname');
    });
  });
});


text:
[![Build Status](https://travis-ci.org/gergelyke/sequencify-browser.png)](https://travis-ci.org/gergelyke/sequencify-browser)

[![browser support](https://ci.testling.com/gergelyke/sequencify-browser.png)
](https://ci.testling.com/gergelyke/sequencify-browser)

## Sequencify-browser

A module for sequencing tasks and dependencies in the browser with browserify

```
npm install sequencify-browser
```

### Usage

```javascript
var sequencify = require('sequencify-browser');

var items = {
  a: {
    name: 'a',
    dep: []
    // other properties as needed
  },
  b: {
    name: 'b',
    dep: ['a']
  },
  c: {
    name: 'c',
    dep: ['a']
  },
  d: {
    name: 'd',
    dep: ['c']
  },
};

var names = ['d', 'b', 'c', 'a']; // The names of the items you want arranged, need not be all

var results = sequencify(items, names);

console.log(results.sequence);
// ['a','b','c','d'];
```

## Credits

The original repo for node can be found here: https://github.com/robrich/sequencify


text:
"""
requests.models
~~~~~~~~~~~~~~~

This module contains the primary objects that power Requests.
"""

import os
import socket
from datetime import datetime
from io import BytesIO

from .hooks import dispatch_hook, HOOKS
from .structures import CaseInsensitiveDict
from .status_codes import codes

from .auth import HTTPBasicAuth, HTTPProxyAuth
from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header
from .packages.urllib3.exceptions import MaxRetryError, LocationParseError
from .packages.urllib3.exceptions import TimeoutError
from .packages.urllib3.exceptions import SSLError as _SSLError
from .packages.urllib3.exceptions import HTTPError as _HTTPError
from .packages.urllib3 import connectionpool, poolmanager
from .packages.urllib3.filepost import encode_multipart_formdata
from .defaults import SCHEMAS
from .exceptions import (
    ConnectionError, HTTPError, RequestException, Timeout, TooManyRedirects,
    URLRequired, SSLError, MissingSchema, InvalidSchema, InvalidURL)
from .utils import (
    get_encoding_from_headers, stream_untransfer, guess_filename, requote_uri,
    stream_decode_response_unicode, get_netrc_auth, get_environ_proxies,
    to_key_val_list, DEFAULT_CA_BUNDLE_PATH, parse_header_links, iter_slices)
from .compat import (
    cookielib, urlparse, urlunparse, urljoin, urlsplit, urlencode, str, bytes,
    StringIO, is_py2, chardet, json, builtin_str)

REDIRECT_STATI = (codes.moved, codes.found, codes.other, codes.temporary_moved)
CONTENT_CHUNK_SIZE = 10 * 1024

class Request(object):
    """The :class:`Request <Request>` object. It carries out all functionality
    of Requests. Recommended interface is with the Requests functions.
    """

    def __init__(self,
        url=None,
        headers=dict(),
        files=None,
        method=None,
        data=dict(),
        params=dict(),
        auth=None,
        cookies=None,
        timeout=None,
        redirect=False,
        allow_redirects=False,
        proxies=None,
        hooks=None,
        config=None,
        prefetch=True,
        _poolmanager=None,
        verify=None,
        session=None,
        cert=None):

        #: Dictionary of configurations for this request.
        self.config = dict(config or [])

        #: Float describes the timeout of the request.
        #  (Use socket.setdefaulttimeout() as fallback)
        self.timeout = timeout

        #: Request URL.
        #: Accept objects that have string representations.
        try:
            self.url = unicode(url)
        except NameError:
            # We're on Python 3.
            self.url = str(url)
        except UnicodeDecodeError:
            self.url = url

        #: Dictionary of HTTP Headers to attach to the :class:`Request <Request>`.
        self.headers = dict(headers or [])

        #: Dictionary of files to multipart upload (``{filename: content}``).
        self.files = None

        #: HTTP Method to use.
        self.method = method

        #: Dictionary, bytes or file stream of request body data to attach to the
        #: :class:`Request <Request>`.
        self.data = None

        #: Dictionary or byte of querystring data to attach to the
        #: :class:`Request <Request>`. The dictionary values can be lists for representing
        #: multivalued query parameters.
        self.params = None

        #: True if :class:`Request <Request>` is part of a redirect chain (disables history
        #: and HTTPError storage).
        self.redirect = redirect

        #: Set to True if full redirects are allowed (e.g. re-POST-ing of data at new ``Location``)
        self.allow_redirects = allow_redirects

        # Dictionary mapping protocol to the URL of the proxy (e.g. {'http': 'foo.bar:3128'})
        self.proxies = dict(proxies or [])

        for proxy_type,uri_ref in list(self.proxies.items()):
            if not uri_ref:
                del self.proxies[proxy_type]

        # If no proxies are given, allow configuration by environment variables
        # HTTP_PROXY and HTTPS_PROXY.
        if not self.proxies and self.config.get('trust_env'):
            self.proxies = get_environ_proxies()

        self.data = data
        self.params = params
        self.files = files

        #: :class:`Response <Response>` instance, containing
        #: content and metadata of HTTP Response, once :attr:`sent <send>`.
        self.response = Response()

        #: Authentication tuple or object to attach to :class:`Request <Request>`.
        self.auth = auth

        #: CookieJar to attach to :class:`Request <Request>`.
        if isinstance(cookies, cookielib.CookieJar):
            self.cookies = cookies
        else:
            self.cookies = cookiejar_from_dict(cookies)

        #: True if Request has been sent.
        self.sent = False

        #: Event-handling hooks.
        self.hooks = {}

        for event in HOOKS:
            self.hooks[event] = []

        hooks = hooks or {}

        for (k, v) in list(hooks.items()):
            self.register_hook(event=k, hook=v)

        #: Session.
        self.session = session

        #: SSL Verification.
        self.verify = verify

        #: SSL Certificate
        self.cert = cert

        #: Prefetch response content
        self.prefetch = prefetch

        if headers:
            headers = CaseInsensitiveDict(self.headers)
        else:
            headers = CaseInsensitiveDict()

        # Add configured base headers.
        for (k, v) in list(self.config.get('base_headers', {}).items()):
            if k not in headers:
                headers[k] = v

        self.headers = headers
        self._poolmanager = _poolmanager

    def __repr__(self):
        return '<Request [%s]>' % (self.method)

    def _build_response(self, resp):
        """Build internal :class:`Response <Response>` object
        from given response.
        """

        def build(resp):

            response = Response()

            # Pass settings over.
            response.config = self.config

            if resp:

                # Fallback to None if there's no status_code, for whatever reason.
                response.status_code = getattr(resp, 'status', None)

                # Make headers case-insensitive.
                response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))

                # Set encoding.
                response.encoding = get_encoding_from_headers(response.headers)

                # Add new cookies from the server. Don't if configured not to
                if self.config.get('store_cookies'):
                    extract_cookies_to_jar(self.cookies, self, resp)

                # Save cookies in Response.
                response.cookies = self.cookies

                # Save cookies in Session.
                for cookie in self.cookies:
                    self.session.cookies.set_cookie(cookie)

                # No exceptions were harmed in the making of this request.
                response.error = getattr(resp, 'error', None)

            # Save original response for later.
            response.raw = resp
            if isinstance(self.full_url, bytes):
                response.url = self.full_url.decode('utf-8')
            else:
                response.url = self.full_url

            return response

        history = []

        r = build(resp)

        if r.status_code in REDIRECT_STATI and not self.redirect:

            while (('location' in r.headers) and
                   ((r.status_code is codes.see_other) or (self.allow_redirects))):

                r.content  # Consume socket so it can be released

                if not len(history) < self.config.get('max_redirects'):
                    raise TooManyRedirects()

                # Release the connection back into the pool.
                r.raw.release_conn()

                history.append(r)

                url = r.headers['location']
                data = self.data
                files = self.files

                # Handle redirection without scheme (see: RFC 1808 Section 4)
                if url.startswith('//'):
                    parsed_rurl = urlparse(r.url)
                    url = '%s:%s' % (parsed_rurl.scheme, url)

                # Facilitate non-RFC2616-compliant 'location' headers
                # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
                if not urlparse(url).netloc:
                    url = urljoin(r.url,
                                  # Compliant with RFC3986, we percent
                                  # encode the url.
                                  requote_uri(url))

                # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
                if r.status_code is codes.see_other:
                    method = 'GET'
                    data = None
                    files = None
                else:
                    method = self.method

                # Do what the browsers do if strict_mode is off...
                if (not self.config.get('strict_mode')):

                    if r.status_code in (codes.moved, codes.found) and self.method == 'POST':
                        method = 'GET'
                        data = None
                        files = None

                    if (r.status_code == 303) and self.method != 'HEAD':
                        method = 'GET'
                        data = None
                        files = None

                # Remove the cookie headers that were sent.
                headers = self.headers
                try:
                    del headers['Cookie']
                except KeyError:
                    pass

                request = Request(
                    url=url,
                    headers=headers,
                    files=files,
                    method=method,
                    params=self.session.params,
                    auth=self.auth,
                    cookies=self.cookies,
                    redirect=True,
                    data=data,
                    config=self.config,
                    timeout=self.timeout,
                    _poolmanager=self._poolmanager,
                    proxies=self.proxies,
                    verify=self.verify,
                    session=self.session,
                    cert=self.cert,
                    prefetch=self.prefetch,
                )

                request.send()
                r = request.response

            r.history = history

        self.response = r
        self.response.request = self

    @staticmethod
    def _encode_params(data):
        """Encode parameters in a piece of data.

        Will successfully encode parameters when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but abritrary
        if parameters are supplied as a dict.
        """

        if isinstance(data, (str, bytes)):
            return data
        elif hasattr(data, 'read'):
            return data
        elif hasattr(data, '__iter__'):
            result = []
            for k, vs in to_key_val_list(data):
                for v in isinstance(vs, list) and vs or [vs]:
                    if v is not None:
                        result.append(
                            (k.encode('utf-8') if isinstance(k, str) else k,
                             v.encode('utf-8') if isinstance(v, str) else v))
            return urlencode(result, doseq=True)
        else:
            return data

    def _encode_files(self, files):
        """Build the body for a multipart/form-data request.

        Will successfully encode files when passed as a dict or a list of
        2-tuples. Order is retained if data is a list of 2-tuples but abritrary
        if parameters are supplied as a dict.

        """
        if (not files) or isinstance(self.data, str):
            return None

        new_fields = []
        fields = to_key_val_list(self.data)
        files = to_key_val_list(files)

        for field, val in fields:
            if isinstance(val, list):
                for v in val:
                    new_fields.append((field, str(v)))
            else:
                new_fields.append((field, str(val)))

        for (k, v) in files:
            # support for explicit filename
            if isinstance(v, (tuple, list)):
                fn, fp = v
            else:
                fn = guess_filename(v) or k
                fp = v
            if isinstance(fp, str):
                fp = StringIO(fp)
            if isinstance(fp, bytes):
                fp = BytesIO(fp)
            new_fields.append((k, (fn, fp.read())))

        body, content_type = encode_multipart_formdata(new_fields)

        return body, content_type

    @property
    def full_url(self):
        """Build the actual URL to use."""

        if not self.url:
            raise URLRequired()

        url = self.url

        # Support for unicode domain names and paths.
        scheme, netloc, path, params, query, fragment = urlparse(url)

        if not scheme:
            raise MissingSchema("Invalid URL %r: No schema supplied" % url)

        if not scheme in SCHEMAS:
            raise InvalidSchema("Invalid scheme %r" % scheme)

        try:
            netloc = netloc.encode('idna').decode('utf-8')
        except UnicodeError:
            raise InvalidURL('URL has an invalid label.')

        if not path:
            path = '/'

        if is_py2:
            if isinstance(scheme, str):
                scheme = scheme.encode('utf-8')
            if isinstance(netloc, str):
                netloc = netloc.encode('utf-8')
            if isinstance(path, str):
                path = path.encode('utf-8')
            if isinstance(params, str):
                params = params.encode('utf-8')
            if isinstance(query, str):
                query = query.encode('utf-8')
            if isinstance(fragment, str):
                fragment = fragment.encode('utf-8')

        enc_params = self._encode_params(self.params)
        if enc_params:
            if query:
                query = '%s&%s' % (query, enc_params)
            else:
                query = enc_params

        url = (urlunparse([scheme, netloc, path, params, query, fragment]))

        if self.config.get('encode_uri', True):
            url = requote_uri(url)

        return url

    @property
    def path_url(self):
        """Build the path URL to use."""

        url = []

        p = urlsplit(self.full_url)

        # Proxies use full URLs.
        if p.scheme in self.proxies:
            return self.full_url

        path = p.path
        if not path:
            path = '/'

        url.append(path)

        query = p.query
        if query:
            url.append('?')
            url.append(query)

        return ''.join(url)

    def register_hook(self, event, hook):
        """Properly register a hook."""
        if isinstance(hook, (list, tuple, set)):
            self.hooks[event].extend(hook)
        else:
            self.hooks[event].append(hook)

    def deregister_hook(self, event, hook):
        """Deregister a previously registered hook.
        Returns True if the hook existed, False if not.
        """

        try:
            self.hooks[event].remove(hook)
            return True
        except ValueError:
            return False

    def send(self, anyway=False, prefetch=None):
        """Sends the request. Returns True if successful, False if not.
        If there was an HTTPError during transmission,
        self.response.status_code will contain the HTTPError code.

        Once a request is successfully sent, `sent` will equal True.

        :param anyway: If True, request will be sent, even if it has
        already been sent.

        :param prefetch: If not None, will override the request's own setting
        for prefetch.
        """

        # Build the URL
        url = self.full_url

        # Pre-request hook.
        r = dispatch_hook('pre_request', self.hooks, self)
        self.__dict__.update(r.__dict__)

        # Logging
        if self.config.get('verbose'):
            self.config.get('verbose').write('%s   %s   %s\n' % (
                datetime.now().isoformat(), self.method, url
            ))

        # Use .netrc auth if none was provided.
        if not self.auth and self.config.get('trust_env'):
            self.auth = get_netrc_auth(url)

        if self.auth:
            if isinstance(self.auth, tuple) and len(self.auth) == 2:
                # special-case basic HTTP auth
                self.auth = HTTPBasicAuth(*self.auth)

            # Allow auth to make its changes.
            r = self.auth(self)

            # Update self to reflect the auth changes.
            self.__dict__.update(r.__dict__)

        # Nottin' on you.
        body = None
        content_type = None

        # Multi-part file uploads.
        if self.files:
            (body, content_type) = self._encode_files(self.files)
        else:
            if self.data:

                body = self._encode_params(self.data)
                if isinstance(self.data, str) or isinstance(self.data, builtin_str) or hasattr(self.data, 'read'):
                    content_type = None
                else:
                    content_type = 'application/x-www-form-urlencoded'

        # Add content-type if it wasn't explicitly provided.
        if (content_type) and (not 'content-type' in self.headers):
            self.headers['Content-Type'] = content_type

        _p = urlparse(url)
        no_proxy = filter(lambda x: x.strip(), self.proxies.get('no', '').split(','))
        proxy = self.proxies.get(_p.scheme)

        if proxy and not any(map(_p.hostname.endswith, no_proxy)):
            conn = poolmanager.proxy_from_url(proxy)
            _proxy = urlparse(proxy)
            if '@' in _proxy.netloc:
                auth, url = _proxy.netloc.split('@', 1)
                self.proxy_auth = HTTPProxyAuth(*auth.split(':', 1))
                r = self.proxy_auth(self)
                self.__dict__.update(r.__dict__)
        else:
            # Check to see if keep_alive is allowed.
            try:
                if self.config.get('keep_alive'):
                    conn = self._poolmanager.connection_from_url(url)
                else:
                    conn = connectionpool.connection_from_url(url)
                    self.headers['Connection'] = 'close'
            except LocationParseError as e:
                raise InvalidURL(e)

        if url.startswith('https') and self.verify:

            cert_loc = None

            # Allow self-specified cert location.
            if self.verify is not True:
                cert_loc = self.verify

            # Look for configuration.
            if not cert_loc and self.config.get('trust_env'):
                cert_loc = os.environ.get('REQUESTS_CA_BUNDLE')

            # Curl compatibility.
            if not cert_loc and self.config.get('trust_env'):
                cert_loc = os.environ.get('CURL_CA_BUNDLE')

            if not cert_loc:
                cert_loc = DEFAULT_CA_BUNDLE_PATH

            if not cert_loc:
                raise Exception("Could not find a suitable SSL CA certificate bundle.")

            conn.cert_reqs = 'CERT_REQUIRED'
            conn.ca_certs = cert_loc
        else:
            conn.cert_reqs = 'CERT_NONE'
            conn.ca_certs = None

        if self.cert:
            if len(self.cert) == 2:
                conn.cert_file = self.cert[0]
                conn.key_file = self.cert[1]
            else:
                conn.cert_file = self.cert

        if not self.sent or anyway:

            # Skip if 'cookie' header is explicitly set.
            if 'cookie' not in self.headers:
                cookie_header = get_cookie_header(self.cookies, self)
                if cookie_header is not None:
                    self.headers['Cookie'] = cookie_header

            # Pre-send hook.
            r = dispatch_hook('pre_send', self.hooks, self)
            self.__dict__.update(r.__dict__)

            # catch urllib3 exceptions and throw Requests exceptions
            try:
                # Send the request.
                r = conn.urlopen(
                    method=self.method,
                    url=self.path_url,
                    body=body,
                    headers=self.headers,
                    redirect=False,
                    assert_same_host=False,
                    preload_content=False,
                    decode_content=False,
                    retries=self.config.get('max_retries', 0),
                    timeout=self.timeout,
                )
                self.sent = True

            except socket.error as sockerr:
                raise ConnectionError(sockerr)

            except MaxRetryError as e:
                raise ConnectionError(e)

            except (_SSLError, _HTTPError) as e:
                if isinstance(e, _SSLError):
                    raise SSLError(e)
                elif isinstance(e, TimeoutError):
                    raise Timeout(e)
                else:
                    raise Timeout('Request timed out.')

            # build_response can throw TooManyRedirects
            self._build_response(r)

            # Response manipulation hook.
            self.response = dispatch_hook('response', self.hooks, self.response)

            # Post-request hook.
            r = dispatch_hook('post_request', self.hooks, self)
            self.__dict__.update(r.__dict__)

            # If prefetch is True, mark content as consumed.
            if prefetch is None:
                prefetch = self.prefetch
            if prefetch:
                # Save the response.
                self.response.content

            if self.config.get('danger_mode'):
                self.response.raise_for_status()

            return self.sent

class Response(object):
    """The core :class:`Response <Response>` object. All
    :class:`Request <Request>` objects contain a
    :class:`response <Response>` attribute, which is an instance
    of this class.
    """

    def __init__(self):

        self._content = False
        self._content_consumed = False

        #: Integer Code of responded HTTP Status.
        self.status_code = None

        #: Case-insensitive Dictionary of Response Headers.
        #: For example, ``headers['content-encoding']`` will return the
        #: value of a ``'Content-Encoding'`` response header.
        self.headers = CaseInsensitiveDict()

        #: File-like object representation of response (for advanced usage).
        self.raw = None

        #: Final URL location of Response.
        self.url = None

        #: Resulting :class:`HTTPError` of request, if one occurred.
        self.error = None

        #: Encoding to decode with when accessing r.text.
        self.encoding = None

        #: A list of :class:`Response <Response>` objects from
        #: the history of the Request. Any redirect responses will end
        #: up here. The list is sorted from the oldest to the most recent request.
        self.history = []

        #: The :class:`Request <Request>` that created the Response.
        self.request = None

        #: A CookieJar of Cookies the server sent back.
        self.cookies = None

        #: Dictionary of configurations for this request.
        self.config = {}

    def __repr__(self):
        return '<Response [%s]>' % (self.status_code)

    def __bool__(self):
        """Returns true if :attr:`status_code` is 'OK'."""
        return self.ok

    def __nonzero__(self):
        """Returns true if :attr:`status_code` is 'OK'."""
        return self.ok

    @property
    def ok(self):
        try:
            self.raise_for_status()
        except RequestException:
            return False
        return True

    def iter_content(self, chunk_size=1, decode_unicode=False):
        """Iterates over the response data.  This avoids reading the content
        at once into memory for large responses.  The chunk size is the number
        of bytes it should read into memory.  This is not necessarily the
        length of each item returned as decoding can take place.
        """
        if self._content_consumed:
            # simulate reading small chunks of the content
            return iter_slices(self._content, chunk_size)

        def generate():
            while 1:
                chunk = self.raw.read(chunk_size)
                if not chunk:
                    break
                yield chunk
            self._content_consumed = True

        gen = stream_untransfer(generate(), self)

        if decode_unicode:
            gen = stream_decode_response_unicode(gen, self)

        return gen

    def iter_lines(self, chunk_size=10 * 1024, decode_unicode=None):
        """Iterates over the response data, one line at a time.  This
        avoids reading the content at once into memory for large
        responses.
        """

        pending = None

        for chunk in self.iter_content(
            chunk_size=chunk_size,
            decode_unicode=decode_unicode):

            if pending is not None:
                chunk = pending + chunk
            lines = chunk.splitlines()

            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
                pending = lines.pop()
            else:
                pending = None

            for line in lines:
                yield line

        if pending is not None:
            yield pending

    @property
    def content(self):
        """Content of the response, in bytes."""

        if self._content is False:
            # Read the contents.
            try:
                if self._content_consumed:
                    raise RuntimeError(
                        'The content for this response was already consumed')

                if self.status_code is 0:
                    self._content = None
                else:
                    self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()

            except AttributeError:
                self._content = None

        self._content_consumed = True
        # don't need to release the connection; that's been handled by urllib3
        # since we exhausted the data.
        return self._content

    @property
    def text(self):
        """Content of the response, in unicode.

        if Response.encoding is None and chardet module is available, encoding
        will be guessed.
        """

        # Try charset from content-type
        content = None
        encoding = self.encoding

        if not self.content:
            return str('')

        # Fallback to auto-detected encoding.
        if self.encoding is None:
            if chardet is not None:
                encoding = chardet.detect(self.content)['encoding']

        # Decode unicode from given encoding.
        try:
            content = str(self.content, encoding, errors='replace')
        except (LookupError, TypeError):
            # A LookupError is raised if the encoding was not found which could
            # indicate a misspelling or similar mistake.
            #
            # A TypeError can be raised if encoding is None
            #
            # So we try blindly encoding.
            content = str(self.content, errors='replace')

        return content

    @property
    def json(self):
        """Returns the json-encoded content of a response, if any."""
        try:
            return json.loads(self.text or self.content)
        except ValueError:
            return None

    @property
    def links(self):
        """Returns the parsed header links of the response, if any."""

        header = self.headers['link']

        # l = MultiDict()
        l = {}

        if header:
            links = parse_header_links(header)

            for link in links:
                key = link.get('rel') or link.get('url')
                l[key] = link

        return l

    @property
    def reason(self):
        """The HTTP Reason for the response."""
        return self.raw.reason

    def raise_for_status(self, allow_redirects=True):
        """Raises stored :class:`HTTPError` or :class:`URLError`, if one occurred."""

        if self.error:
            raise self.error

        http_error_msg = ''
        if 300 <= self.status_code < 400 and not allow_redirects:
            http_error_msg = '%s Redirection: %s' % (self.status_code, self.reason)

        elif 400 <= self.status_code < 500:
            http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)

        elif 500 <= self.status_code < 600:
            http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)

        if http_error_msg:
            http_error = HTTPError(http_error_msg)
            http_error.response = self
            raise http_error


text:
#region License

#endregion

using Spring.Objects.Factory;

namespace Spring.Context.Support
{
    /// <author>Mark Pollack</author>
    public class Logic : IObjectNameAware
    {

        private string objectName;
        private Assembler assembler;

        public Assembler Assembler
        {
            set { assembler = value; }
        }

        #region IObjectNameAware Members

        public string ObjectName
        {
            set { objectName = value; }
        }

        #endregion
    }
}


text:
package hu.akarnokd.misc;

import java.lang.annotation.*;

import io.reactivex.Observable;
import io.reactivex.functions.Function;

public class UseSiteTypeAnnot<T> {

    public <U, R> Observable<T> map(Function<@NN T, @NN R> mapper) {
        return null;
    }
}

@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@interface NN {
}


text:
import types
import itkBase

not_loaded = 'not loaded'

class LazyITKModule(types.ModuleType):

    """Subclass of ModuleType that implements a custom __getattribute__ method
    to allow lazy-loading of attributes from ITK sub-modules."""

    def __init__(self, name, lazy_attributes):
        types.ModuleType.__init__(self, name)
        self.__lazy_attributes = lazy_attributes
        for k in lazy_attributes:
            setattr(self, k, not_loaded)

    def __getattribute__(self, attr):
        value = types.ModuleType.__getattribute__(self, attr)
        if value is not_loaded:
            module = self.__lazy_attributes[attr]
            namespace = {}
            itkBase.LoadModule(module, namespace)
            # Load into 'namespace' first, then self.__dict__ (via setattr) to
            # prevent the warnings about overwriting the 'NotLoaded' values
            # already in self.__dict__ we would get if we just passed
            # self.__dict__ to itkBase.LoadModule.
            for k, v in namespace.items():
                setattr(self, k, v)
            value = namespace[attr]
        return value