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

package org.chromium.chrome.browser.media.ui;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.robolectric.Shadows.shadowOf;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowNotificationManager;

import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.chrome.browser.notifications.NotificationUmaTracker;
import org.chromium.components.browser_ui.media.MediaNotificationController;
import org.chromium.components.browser_ui.media.MediaNotificationInfo;
import org.chromium.components.browser_ui.media.MediaNotificationManager;
import org.chromium.services.media_session.MediaMetadata;

/**
 * JUnit tests for checking {@link MediaNotificationController} handles the listener service life
 * cycle correctly.
 */
@RunWith(BaseRobolectricTestRunner.class)
@Config(manifest = Config.NONE,
        // Remove this after updating to a version of Robolectric that supports
        // notification channel creation. crbug.com/774315
        sdk = Build.VERSION_CODES.N_MR1, shadows = {MediaNotificationTestShadowResources.class})
public class MediaNotificationServiceLifecycleTest extends MediaNotificationTestBase {
    @Test
    public void testServiceLifeCycle() {
        ensureMediaNotificationInfo();

        Intent intent = getController().mDelegate.createServiceIntent();

        assertNull(mService);
        mMockContext.startService(intent);
        verify(getController()).onServiceStarted(mService);
        assertNotNull(mService);
        verify(mService).onStartCommand(intent, 0, 0);

        mService.getImpl().stopListenerService();
        assertNull(mService);
    }

    @Test
    public void testProcessIntentFailureStopsService() {
        MediaNotificationController controller = getController();
        setUpService();

        MockListenerService service = mService;
        MockListenerServiceImpl impl = service.getImpl();
        doReturn(false).when(impl).processIntent(any(Intent.class));
        mMockContext.startService(new Intent());
        verify(service.getImpl()).stopListenerService();
        assertNull(getController());
        verify(controller).onServiceDestroyed();
    }

    @Test
    public void testProcessNullIntent() {
        setUpService();
        assertFalse(mService.getImpl().processIntent(null));
    }

    @Test
    public void testProcessIntentWhenManagerIsNull() {
        setUpService();
        MediaNotificationManager.setControllerForTesting(getNotificationId(), null);
        assertFalse(mService.getImpl().processIntent(new Intent()));
    }

    @Test
    public void testProcessIntentWhenNotificationInfoIsNull() {
        setUpService();
        getController().mMediaNotificationInfo = null;
        assertFalse(mService.getImpl().processIntent(new Intent()));
    }

    @Test
    public void testShowNotificationIsNoOpWhenInfoMatches() {
        doCallRealMethod().when(getController()).onServiceStarted(any(MockListenerService.class));
        setUpServiceAndClearInvocations();

        MediaNotificationInfo newInfo = mMediaNotificationInfoBuilder.build();
        getController().showNotification(newInfo);

        verify(getController()).showNotification(newInfo);
        verifyNoMoreInteractions(getController());
        verify(mMockForegroundServiceUtils, never()).startForegroundService(any(Intent.class));
        verify(mMockContext, never()).startService(any(Intent.class));
        verify(mMockUmaTracker, never()).onNotificationShown(anyInt(), any(Notification.class));
    }

    @Test
    public void testShowNotificationIsNoOpWhenInfoIsPausedAndFromAnotherTab() {
        doCallRealMethod().when(getController()).onServiceStarted(any(MockListenerService.class));
        mMediaNotificationInfoBuilder.setInstanceId(0);
        setUpServiceAndClearInvocations();

        mMediaNotificationInfoBuilder.setInstanceId(1).setPaused(true);
        MediaNotificationInfo newInfo = mMediaNotificationInfoBuilder.build();
        getController().showNotification(newInfo);

        verify(getController()).showNotification(newInfo);
        verifyNoMoreInteractions(getController());
        verify(mMockForegroundServiceUtils, never()).startForegroundService(any(Intent.class));
        verify(mMockContext, never()).startService(any(Intent.class));
        verify(mMockUmaTracker, never()).onNotificationShown(anyInt(), any(Notification.class));
    }

    @Test
    public void testShowNotificationWhenServiceNotCreated() {
        MediaNotificationInfo newInfo = mMediaNotificationInfoBuilder.build();
        getController().showNotification(newInfo);

        verify(getController(), times(1)).updateMediaSession();
        verify(getController(), times(1)).updateNotificationBuilder();
        verify(mMockContext, never()).startService(any(Intent.class));
        verify(mMockForegroundServiceUtils, times(1)).startForegroundService(any(Intent.class));
        verify(getController(), never()).updateNotification(anyBoolean(), eq(false));
    }

    @Test
    public void testShowNotificationWhenServiceAlreadyCreated() {
        doCallRealMethod().when(getController()).onServiceStarted(any(MockListenerService.class));
        setUpServiceAndClearInvocations();

        mMediaNotificationInfoBuilder.setPaused(true);
        MediaNotificationInfo newInfo = mMediaNotificationInfoBuilder.build();
        getController().showNotification(newInfo);

        verify(getController()).showNotification(newInfo);
        verify(mMockForegroundServiceUtils, never()).startForegroundService(any(Intent.class));
        verify(mMockContext, never()).startService(any(Intent.class));
        verify(getController()).updateNotification(anyBoolean(), eq(false));
        verify(mMockUmaTracker, never()).onNotificationShown(anyInt(), any(Notification.class));
    }

    @Test
    public void testShowNotificationBeforeServiceCreatedUpdatesNotificationInfoAndLogsUma() {
        doCallRealMethod().when(getController()).onServiceStarted(any(MockListenerService.class));

        // The initial call to |showNotification()| should update the notification info and request
        // to start the service.
        MediaNotificationInfo oldInfo = mMediaNotificationInfoBuilder.build();
        getController().showNotification(oldInfo);

        InOrder order = inOrder(getController(), mMockForegroundServiceUtils);

        assertEquals(oldInfo, getController().mMediaNotificationInfo);
        order.verify(getController(), times(1)).updateMediaSession();
        order.verify(getController(), times(1)).updateNotificationBuilder();
        order.verify(mMockForegroundServiceUtils, times(1))
                .startForegroundService(any(Intent.class));
        order.verify(getController(), never()).updateNotification(anyBoolean(), eq(false));

        // The second call to |showNotification()| should only update the notification info.
        mMediaNotificationInfoBuilder.setMetadata(new MediaMetadata("new title", "", ""));
        MediaNotificationInfo newInfo = mMediaNotificationInfoBuilder.build();
        getController().showNotification(newInfo);

        assertEquals(newInfo, getController().mMediaNotificationInfo);
        order.verify(getController(), times(1)).updateMediaSession();
        order.verify(getController(), times(1)).updateNotificationBuilder();
        order.verify(mMockForegroundServiceUtils, times(1))
                .startForegroundService(any(Intent.class));
        order.verify(getController(), never()).updateNotification(anyBoolean(), eq(false));

        verify(getController(), never()).onServiceStarted(any(MockListenerService.class));

        // Simulate the service has started.
        mMockContext.startService(getController().mDelegate.createServiceIntent());
        order.verify(getController(), times(1)).onServiceStarted(mService);
        order.verify(getController(), times(1)).updateNotification(anyBoolean(), eq(true));
        verify(mMockUmaTracker)
                .onNotificationShown(eq(NotificationUmaTracker.SystemNotificationType.MEDIA),
                        any(Notification.class));
    }

    @Test
    public void updateNotificationIsNoOpBeforeServiceCreated() {
        getController().mMediaNotificationInfo = mMediaNotificationInfoBuilder.build();
        getController().updateNotification(false, false);

        verify(getController()).updateNotification(anyBoolean(), eq(false));
        verify(getController(), never()).updateMediaSession();
        verify(getController(), never()).updateNotificationBuilder();
    }

    @Test
    public void updateNotificationIsNoOpWhenNotificiationInfoIsNull() {
        setUpService();
        getController().mService = mService;
        getController().mMediaNotificationInfo = null;
        getController().updateNotification(false, false);

        verify(getController()).updateNotification(anyBoolean(), eq(false));
        verify(getController(), never()).updateMediaSession();
        verify(getController(), never()).updateNotificationBuilder();

        verify(mMockForegroundServiceUtils, never()).stopForeground(eq(mService), anyInt());
        verify(mMockForegroundServiceUtils, never())
                .startForeground(eq(mService), anyInt(), any(Notification.class), anyInt());
    }

    @Test
    public void updateNotificationSetsServiceBackgroundWhenPausedAndSupportsSwipeAway() {
        mMediaNotificationInfoBuilder.setPaused(true);
        setUpService();
        getController().mService = mService;
        getController().mMediaNotificationInfo = mMediaNotificationInfoBuilder.build();
        getController().updateNotification(false, false);

        verify(mMockForegroundServiceUtils)
                .stopForeground(eq(mService), eq(Service.STOP_FOREGROUND_DETACH));
        assertEquals(1, getShadowNotificationManager().size());
    }

    @Test
    public void updateNotificationSetsServiceBackgroundWhenPausedButDoesntSupportSwipeAway() {
        mMediaNotificationInfoBuilder.setPaused(true).setActions(0);
        setUpService();
        getController().mService = mService;
        getController().mMediaNotificationInfo = mMediaNotificationInfoBuilder.build();
        getController().updateNotification(false, false);

        verify(mMockForegroundServiceUtils)
                .startForeground(
                        eq(mService), eq(getNotificationId()), any(Notification.class), eq(0));
    }

    @Test
    public void updateNotificationSetsServiceForegroundWhenPlaying() {
        mMediaNotificationInfoBuilder.setPaused(false);
        setUpService();
        getController().mService = mService;
        getController().mMediaNotificationInfo = mMediaNotificationInfoBuilder.build();
        getController().updateNotification(false, false);

        verify(mMockForegroundServiceUtils)
                .startForeground(
                        eq(mService), eq(getNotificationId()), any(Notification.class), eq(0));
    }

    private ShadowNotificationManager getShadowNotificationManager() {
        NotificationManager notificationManager =
                (NotificationManager) mMockContext.getSystemService(Context.NOTIFICATION_SERVICE);
        return shadowOf(notificationManager);
    }
}


text:
import socket
import subprocess
import logging
import os.path

SKYPY_PATH = os.path.dirname(os.path.abspath(__file__))
SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(SKYPY_PATH)))

WORKBENCH_ROOT = os.path.join(SRC_ROOT, 'sky', 'packages', 'workbench')
DART_SDK = os.path.join(SRC_ROOT, 'third_party', 'dart-sdk', 'dart-sdk', 'bin')
PUB = os.path.join(DART_SDK, 'pub')
EXAMPLES_ROOT = os.path.join(SRC_ROOT, 'examples')
SKY_ROOT = os.path.join(SRC_ROOT, 'sky')

class SkyServer(object):
    def __init__(self, port, root, package_root):
        self.port = port
        self.root = root
        self.package_root = package_root
        self.server = None

    @staticmethod
    def _port_in_use(port):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        return sock.connect_ex(('localhost', port)) == 0

    def start(self):
        if self._port_in_use(self.port):
            logging.warn(
                'Port %s already in use, assuming custom sky_server started.' %
                self.port)
            return

        args = [PUB,
                'run',
                'sky_tools:sky_server',
                '--route=/sky,%s' % SKY_ROOT,
                '--route=/examples,%s' % EXAMPLES_ROOT,
                str(self.port)]
        self.server = subprocess.Popen(args, cwd=WORKBENCH_ROOT)
        return self.server.pid

    def stop(self):
        if self.server:
            self.server.terminate()

    def __enter__(self):
        self.start()

    def __exit__(self, exc_type, exc_value, traceback):
        self.stop()

    def path_as_url(self, path):
        return self.url_for_path(self.port, self.root, path)

    @staticmethod
    def url_for_path(port, root, path):
        relative_path = os.path.relpath(path, root)
        return 'http://localhost:%s/%s' % (port, relative_path)

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// Test specific configuration
// ===========================
module.exports = {
  // MongoDB connection options
  mongo: {
    uri: 'mongodb://localhost/baristaweb-test'
  }
};


text:
package com.raulh82vlc.topratemovies.api;

import android.content.Context;

import com.raulh82vlc.topratemovies.models.FilmDetailsJSONEntity;
import com.raulh82vlc.topratemovies.models.FilmJSONEntity;

import java.util.List;

import retrofit.Callback;

/**
 * Created by Raul Hernandez Lopez on 22/02/2015.
 * declared calls with params
 */

public class WebServicesApiCalls {

    private Context mContext;
    private ApiFilmInterface mApiFilmInterface;

    public WebServicesApiCalls(Context ctx)
    {
        mContext = ctx;
        mApiFilmInterface = new WebServicesController(mContext).getFilmInterface();
    }

    /**
     * This was defined in the Interface
     * getFilmsTop
     *
     * @param fromFirst
     * @param toLast
     * @param oFilms
     *
     * output is Callback<List<FilmJSONEntity>> oFilms);
     *
     *  */
    public void getTopFilmsFromARange(Integer fromFirst, Integer toLast, Callback<List<FilmJSONEntity>> oFilms)
    {
        mApiFilmInterface.getFilmsTop(ApiConstans.TOKEN, ApiConstans.formatToRetrofit, fromFirst, toLast, ApiConstans.formatOfInfo, oFilms);
    }

    /**
     * This was defined in the Interface
     * getFilmsByName
     *
     * @param iMovieTitle
     * output is Callback<List<FilmDetailsJSONEntity>>
     *
     */
    public void getFilmsByName(String iMovieTitle, Callback<List<FilmDetailsJSONEntity>> oFilm)
    {
        mApiFilmInterface.getFilmsByName(ApiConstans.TOKEN, ApiConstans.formatToRetrofit, iMovieTitle, oFilm);
    }

}


text:
(function() {
	app = angular.module('home', ['ui.bootstrap', 'app.layout', 'app.services', 'ngResource', 'ngSanitize', 'angular-loading-bar', 'ui.bootstrap.accordion'])
	/**
	 * Resources
	 */
	.factory('resources', ['$resource', function($resource) {
		var service = {};
		service.resource = $resource("/api/home/:method"
			, null
			, { save: { method: 'PUT'}, create: {method: 'POST' }, remove:{method:'DELETE'}});
		return service;
	}])
	/**
	 * Home controller
	 */
	.controller('HomeController', ['$scope', '$window', '$http', 'resources'
	                                  , function($scope, $window, $http, resources) {

		$scope.baseName = "home";

	}]) // HomeController

} )();


text:
"""Library with functions required to generate LNS imitation data for one MIP."""

import collections as py_collections
import os
import pickle
from typing import Any, Dict, Optional, Sequence, Text

from absl import logging
import ml_collections
import numpy as np

from neural_lns import data_utils
from neural_lns import local_branching_expert
from neural_lns import mip_utils

# LP feature extraction needs to fully process the root node, so allow enough
# time for that.
MIN_SOLVE_TIME = 1800

# SCIP solving parameters
SCIP_SOLVING_PARAMS = ml_collections.ConfigDict({
    'seed': 42,
    'time_limit_seconds': 1800,
    'relative_gap': 0
})

def get_incumbent(
    instance_name: Text,
    dataset: Text,
    solution_index: int) -> Optional[mip_utils.MPSolutionResponse]:
  """Tries to retrieve a solution for the MIP from corresponding pickle file."""
  instance_path = os.path.join(dataset, instance_name)
  solutions = pickle.load(open(instance_path, 'rb'))

  if len(solutions) <= solution_index:
    raise ValueError(
        f'Fewer than {solution_index+1} solutions found for {instance_name}')
  else:
    solution = solutions[solution_index]

  return solution

def get_flipped_vars(mip: mip_utils.MPModel,
                     incumbent: mip_utils.MPSolutionResponse,
                     improved: mip_utils.MPSolutionResponse,
                     var_names: np.ndarray) -> np.ndarray:
  """Returns an array indicating which binary variables were flipped."""
  is_flipped = {}

  # Note that non-binary variables are always assigned a 0.
  for idx, variable in enumerate(mip.variable):
    if (mip_utils.is_var_binary(variable) and round(
        incumbent.variable_value[idx]) != round(improved.variable_value[idx])):
      is_flipped[variable.name] = 1.0
    else:
      is_flipped[variable.name] = 0.0

  # Make sure the array has the variables in the order in which they appear in
  # the features.
  is_flipped_reordered = np.zeros(len(var_names), dtype=np.bool)
  for idx, var_name in enumerate(var_names):
    if 'Constant' in var_name.decode():
      is_flipped_reordered[idx] = 0.0
    else:
      is_flipped_reordered[idx] = is_flipped[var_name.decode()]

  return is_flipped_reordered

def enhance_root_features(
    root_features: Dict[str, Any],
    incumbents: Sequence[Any],
    lp_sol: Optional[Any] = None
    ) -> Dict[str, Any]:
  """Adds incumbent var values and integer mask to the feature array.

  This accepts a list of up to NUM_PAST_INCUMBENTS past incumbents,
  sorted from most recent to least. Each incumbent will introduce two columns
  to the features: The first column represents the incumbent variable values,
  and the second one is a all-ones column indicating that the incumbent is
  present in the features.

  A final column is added to the end that masks out continuous variables.

  Args:
    root_features: Root features without incumbent information.
    incumbents: List of past incumbents, ordered by most recent first.
    lp_sol: solution to the LP relaxation of the LNS MIP solved by the expert.

  Returns:
    Updated features dict.
  """
  if len(incumbents) > data_utils.NUM_PAST_INCUMBENTS:
    raise ValueError(
        f'The number of past incumbents is not sufficient: {len(incumbents)}')

  # Fill columns corresponding to incumbents
  for idx, incumbent in enumerate(incumbents):
    column = data_utils.NUM_ROOT_VARIABLE_FEATURES + 2 * idx
    incumbent_values = np.array(
        [incumbent[var_name.decode()]
         for var_name in root_features['variable_names']],
        dtype=root_features['variable_features'].dtype)

    # Override features column corresponding to incumbent values.
    root_features['variable_features'][:, column] = incumbent_values

    # Override features column corresponding to incumbent presence indicator.
    root_features['variable_features'][:, column + 1] = np.ones(
        len(incumbent_values))

  if lp_sol is not None:
    lp_sol_values = np.array([
        lp_sol[var_name.decode()]
        for var_name in root_features['variable_names']
    ],
                             dtype=root_features['variable_features'].dtype)

    lp_sol_column_index = data_utils.NUM_ROOT_VARIABLE_FEATURES + 2 * len(
        incumbents)
    root_features['variable_features'][:, lp_sol_column_index] = lp_sol_values

  # The last column masks out the continuous variables.
  integer_values_mask = np.ones(len(root_features['variable_names']),
                                dtype=root_features['variable_features'].dtype)
  for idx, _ in enumerate(integer_values_mask):
    if idx not in root_features['all_integer_variable_indices']:
      integer_values_mask[idx] = 0.0

  root_features['variable_features'][:, -1] = integer_values_mask

  return root_features

def generate_data_for_instance(
    instance_name: Text,
    dataset: Text,
    neighbourhood_size: int = 20,
    percentage: bool = False,
    sequence_length: int = 10,
    add_incumbent_to_scip: bool = True,
    solution_index: int = 0,
    scip_params: ml_collections.ConfigDict = SCIP_SOLVING_PARAMS,
    num_var_features: int = data_utils.NUM_VARIABLE_FEATURES) -> int:
  """Generates data from which we learn to imitate the expert.

  This loads a MIP instance from a pickle file and generates the expert data.

  Args:
    instance_name: The name of the MIP instance.
    dataset: Dataset name that the instance belongs to.
    neighbourhood_size: Maximum Hamming dist to search.
    percentage: Whether neighbourhood_size should be treated as a percentage
                of total number of variables.
    sequence_length: How many consecutive improvements to do.
    add_incumbent_to_scip: Whether to feed SCIP the incumbent solution.
    solution_index: Which of the solutions to use as the first incumbent.
    scip_params: Dictionary of SCIP parameters to use.
    num_var_features: Number of features, NUM_VARIABLE_FEATURES or
                      NUM_VARIABLE_FEATURES_LP.

  Returns:
    status: 1 if expert data generation was successful, 0 otherwise.
  """
  mip = pickle.load(open(os.path.join(dataset, instance_name), 'rb'))
  if percentage:
    num_integer = 0
    for var in mip.variable:
      if var.is_integer:
        num_integer += 1
    neighbourhood_size = int(num_integer * neighbourhood_size / 100)

  try:
    incumbent = get_incumbent(instance_name, dataset, solution_index)
  except ValueError:
    logging.warning('No solution found for %s', instance_name)
    return 0

  root_features = data_utils.get_features(mip, scip_params)
  if root_features is None or root_features['variable_features'] is None:
    logging.warning('No root features found for %s', instance_name)
    return 0

  # Append dummy columns to the variable features, which is where we will put
  # the past incumbent solutions and the mask for assigned values at each step.
  num_extra_var_features = num_var_features - data_utils.NUM_ROOT_VARIABLE_FEATURES
  dummy_columns = np.zeros((root_features['variable_features'].shape[0],
                            num_extra_var_features),
                           dtype=root_features['variable_features'].dtype)

  if root_features is not None:
    root_features['variable_features'] = np.concatenate(
        [root_features['variable_features'], dummy_columns], axis=1)

    assert root_features['variable_features'].shape[
        1] == data_utils.NUM_VARIABLE_FEATURES

  status = 1
  past_incumbents = py_collections.deque([incumbent])

  for step in range(sequence_length):
    incumbent = past_incumbents[0]
    improved_sol = local_branching_expert.improve_solution(
        mip, incumbent, neighbourhood_size, scip_params,
        add_incumbent_to_scip=add_incumbent_to_scip)

    lp_sol = local_branching_expert.get_lns_lp_solution(
        mip, incumbent, neighbourhood_size, scip_params)

    if improved_sol is None:
      # In case of solver failure, print a warning and break.
      logging.warning('Solver failed for MIP %s at step %d ',
                      instance_name, step)
      status = 0
      break

    # Add features corresponding to the incumbent solution and integer mask.
    # NB This will overwrite the last column of the variable features.
    features = enhance_root_features(root_features, past_incumbents, lp_sol)

    # Figure out which variables were flipped between incumbent and improved.
    features['best_solution_labels'] = get_flipped_vars(
        mip, incumbent, improved_sol, features['variable_names'])

    # Add new incumbent to incumbent list, and prune to size if necessary
    past_incumbents.appendleft(improved_sol)
    if len(past_incumbents) > data_utils.NUM_PAST_INCUMBENTS:
      past_incumbents.pop()

  return status


text:
"""
Exception definitions.
"""

class CommandError(Exception):
    pass

class AuthorizationFailure(Exception):
    pass

class NoTokenLookupException(Exception):
    """This form of authentication does not support looking up
       endpoints from an existing token."""
    pass

class EndpointNotFound(Exception):
    """Could not find Service or Region in Service Catalog."""
    pass

class ClientException(Exception):
    """
    The base exception class for all exceptions this library raises.
    """
    def __init__(self, code, message=None, details=None):
        self.code = code
        self.message = message or self.__class__.message
        self.details = details

    def __str__(self):
        return "%s (HTTP %s)" % (self.message, self.code)

class BadRequest(ClientException):
    """
    HTTP 400 - Bad request: you sent some malformed data.
    """
    http_status = 400
    message = "Bad request"

class Unauthorized(ClientException):
    """
    HTTP 401 - Unauthorized: bad credentials.
    """
    http_status = 401
    message = "Unauthorized"

class Forbidden(ClientException):
    """
    HTTP 403 - Forbidden: your credentials don't give you access to this
    resource.
    """
    http_status = 403
    message = "Forbidden"

class NotFound(ClientException):
    """
    HTTP 404 - Not found
    """
    http_status = 404
    message = "Not found"

class Conflict(ClientException):
    """
    HTTP 409 - Conflict
    """
    http_status = 409
    message = "Conflict"

class OverLimit(ClientException):
    """
    HTTP 413 - Over limit: you're over the API limits for this time period.
    """
    http_status = 413
    message = "Over limit"

# NotImplemented is a python keyword.
class HTTPNotImplemented(ClientException):
    """
    HTTP 501 - Not Implemented: the server does not support this operation.
    """
    http_status = 501
    message = "Not Implemented"

# In Python 2.4 Exception is old-style and thus doesn't have a __subclasses__()
# so we can do this:
#     _code_map = dict((c.http_status, c)
#                      for c in ClientException.__subclasses__())
#
# Instead, we have to hardcode it:
_code_map = dict((c.http_status, c) for c in [BadRequest, Unauthorized,
                   Forbidden, NotFound, OverLimit, HTTPNotImplemented])

def from_response(response, body):
    """
    Return an instance of an ClientException or subclass
    based on an httplib2 response.

    Usage::

        resp, body = http.request(...)
        if resp.status != 200:
            raise exception_from_response(resp, body)
    """
    cls = _code_map.get(response.status, ClientException)
    if body:
        if hasattr(body, 'keys'):
            error = body[body.keys()[0]]
            message = error.get('message', None)
            details = error.get('details', None)
        else:
            # If we didn't get back a properly formed error message we
            # probably couldn't communicate with Keystone at all.
            message = "Unable to communicate with identity service: %s." % body
            details = None
        return cls(code=response.status, message=message, details=details)
    else:
        return cls(code=response.status)


text:
@interface ASBasicArticleListController()

@end

@implementation ASBasicArticleListController

- (instancetype)initWithTitle:(NSString *)title {
    self = [super init];
    if (self) {
        self.title = title;
        self.isLoaded = NO;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(moreData)];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    NSLog(@"y:%f", self.navigationController.navigationBar.frame.size.height);
//    NSLog(@"y:%f", scrollView.superview.superview.frame.origin.y);
//    NSLog(@"滑动:%f", scrollView.contentOffset.y);
}

- (void)loadData {
    //[self.tableView.mj_header beginRefreshing]
    self.isLoaded = YES;
}

- (void)moreData {
    //[self.tableView.mj_footer beginRefreshing];
}

- (void)loadIfNotLoaded {
    if (!self.isLoaded) {
        [self.tableView.mj_header beginRefreshing];
        [self loadData];
    }
}

@end


text:
<?php

namespace Amicale\AccueilBundle\Tests\Entity;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class CommandeTest extends WebTestCase
{
    public function testIndex()
    {
        $commande = new \Amicale\AccueilBundle\Entity\Commande();
        $result = $commande->add(1, 2);
        $this->assertEquals(7,$result);
        $result = $commande->add(2, 1);
        $this->assertEquals(0,$result);
    }
}


text:
<?php

namespace App\Http\Middleware;

use Closure;

class RefreshSpaceRelations
{
    public function handle($request, Closure $next)
    {
        if ($request->session()->has('space')) {
            $request->session()->get('space')->load('tags', 'earnings', 'spendings', 'recurrings', 'activities');
        }

        return $next($request);
    }
}


text:
'use strict';

var EventEmitter     = require('events').EventEmitter;
var TextOperation    = require('./text-operation');
var WrappedOperation = require('./wrapped-operation');
var Server           = require('./server');
var Selection        = require('./selection');
var util             = require('util');

function EditorSocketIOServer (document, operations, docId, mayWrite) {
  EventEmitter.call(this);
  Server.call(this, document, operations);
  this.users = {};
  this.docId = docId;
  this.mayWrite = mayWrite || function (_, cb) { cb(true); };
}

util.inherits(EditorSocketIOServer, Server);
extend(EditorSocketIOServer.prototype, EventEmitter.prototype);

function extend (target, source) {
  for (var key in source) {
    if (source.hasOwnProperty(key)) {
      target[key] = source[key];
    }
  }
}

EditorSocketIOServer.prototype.addClient = function (socket) {
  var self = this;
  socket
    .join(this.docId)
    .emit('doc', {
      str: this.document,
      revision: this.operations.length,
      clients: this.users
    })
    .on('operation', function (revision, operation, selection) {
      self.mayWrite(socket, function (mayWrite) {
        if (!mayWrite) {
          console.log("User doesn't have the right to edit.");
          return;
        }
        self.onOperation(socket, revision, operation, selection);
      });
    })
    .on('selection', function (obj) {
      self.mayWrite(socket, function (mayWrite) {
        if (!mayWrite) {
          console.log("User doesn't have the right to edit.");
          return;
        }
        self.updateSelection(socket, obj && Selection.fromJSON(obj));
      });
    })
    .on('disconnect', function () {
      console.log("Disconnect");
      socket.leave(self.docId);
      self.onDisconnect(socket);
      if (socket.manager.sockets.clients(self.docId).length === 0) {
        self.emit('empty-room');
      }
    });
};

EditorSocketIOServer.prototype.onOperation = function (socket, revision, operation, selection) {
  var wrapped;
  try {
    wrapped = new WrappedOperation(
      TextOperation.fromJSON(operation),
      selection && Selection.fromJSON(selection)
    );
  } catch (exc) {
    console.error("Invalid operation received: " + exc);
    return;
  }

  try {
    var clientId = socket.id;
    var wrappedPrime = this.receiveOperation(revision, wrapped);
    console.log("new operation: " + wrapped);
    this.getClient(clientId).selection = wrappedPrime.meta;
    socket.emit('ack');
    socket.broadcast['in'](this.docId).emit(
      'operation', clientId,
      wrappedPrime.wrapped.toJSON(), wrappedPrime.meta
    );
  } catch (exc) {
    console.error(exc);
  }
};

EditorSocketIOServer.prototype.updateSelection = function (socket, selection) {
  var clientId = socket.id;
  if (selection) {
    this.getClient(clientId).selection = selection;
  } else {
    delete this.getClient(clientId).selection;
  }
  socket.broadcast['in'](this.docId).emit('selection', clientId, selection);
};

EditorSocketIOServer.prototype.setName = function (socket, name) {
  var clientId = socket.id;
  this.getClient(clientId).name = name;
  socket.broadcast['in'](this.docId).emit('set_name', clientId, name);
};

EditorSocketIOServer.prototype.getClient = function (clientId) {
  return this.users[clientId] || (this.users[clientId] = {});
};

EditorSocketIOServer.prototype.onDisconnect = function (socket) {
  var clientId = socket.id;
  delete this.users[clientId];
  socket.broadcast['in'](this.docId).emit('client_left', clientId);
};

module.exports = EditorSocketIOServer;


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

/**
 * @constructor
 * @param {!WebInspector.ASTService} astService
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!Array<!WebInspector.SASSProcessor.EditOperation>} editOperations
 */
WebInspector.SASSProcessor = function(astService, map, editOperations)
{
    this._astService = astService;
    this._map = map;
    this._editOperations = editOperations;
}

WebInspector.SASSProcessor.prototype = {
    /**
     * @return {!Promise<?WebInspector.SourceMap.EditResult>}
     */
    _mutate: function()
    {
        /** @type {!Set<!WebInspector.SASSSupport.Rule>} */
        var changedCSSRules = new Set();
        for (var editOperation of this._editOperations) {
            var rules = editOperation.perform();
            changedCSSRules.addAll(rules);
        }

        // Reparse new texts, make sure changes result in anticipated AST trees.
        var promises = [];
        for (var ast of this._map.models().values()) {
            if (!ast.document.hasChanged())
                continue;
            var promise;
            if (ast.document.url === this._map.compiledURL())
                promise = this._astService.parseCSS(ast.document.url, ast.document.newText().value());
            else
                promise = this._astService.parseSCSS(ast.document.url, ast.document.newText().value());
            promises.push(promise);
        }

        return Promise.all(promises)
            .then(this._onFinished.bind(this, changedCSSRules));
    },

    /**
     * @param {!Set<!WebInspector.SASSSupport.Rule>} changedCSSRules
     * @param {!Array<!WebInspector.SASSSupport.AST>} changedModels
     * @return {?WebInspector.SourceMap.EditResult}
     */
    _onFinished: function(changedCSSRules, changedModels)
    {
        var nodeMapping = new Map();
        var map = this._map.rebase(changedModels, nodeMapping);
        if (!map)
            return null;

        var cssEdits = [];
        for (var rule of changedCSSRules) {
            var oldRange = rule.styleRange;
            var newRule = nodeMapping.get(rule);
            var newText = newRule.document.text.extract(newRule.styleRange);
            cssEdits.push(new WebInspector.SourceEdit(newRule.document.url, oldRange, newText));
        }

        /** @type {!Map<string, string>} */
        var newSASSSources = new Map();
        for (var model of changedModels) {
            if (model.document.url === map.compiledURL())
                continue;
            newSASSSources.set(model.document.url, model.document.text.value());
        }
        return new WebInspector.SourceMap.EditResult(map, cssEdits, newSASSSources);
    }
}

/**
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!WebInspector.SASSSupport.Property} cssProperty
 * @return {?WebInspector.SASSSupport.Property}
 */
WebInspector.SASSProcessor._toSASSProperty = function(map, cssProperty)
{
    var sassName = map.toSourceNode(cssProperty.name);
    return sassName ? sassName.parent : null;
}

/**
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!WebInspector.SASSSupport.Property} sassProperty
 * @return {!Array<!WebInspector.SASSSupport.Property>}
 */
WebInspector.SASSProcessor._toCSSProperties = function(map, sassProperty)
{
    return map.toCompiledNodes(sassProperty.name).map(name => name.parent);
}

/**
 * @param {!WebInspector.ASTService} astService
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!Array<!WebInspector.TextRange>} ranges
 * @param {!Array<string>} newTexts
 * @return {!Promise<?WebInspector.SourceMap.EditResult>}
 */
WebInspector.SASSProcessor.processCSSEdits = function(astService, map, ranges, newTexts)
{
    console.assert(ranges.length === newTexts.length);
    var cssURL = map.compiledURL();
    var cssText = map.compiledModel().document.text;
    for (var i = 0; i < ranges.length; ++i)
        cssText = new WebInspector.Text(cssText.replaceRange(ranges[i], newTexts[i]));
    return astService.parseCSS(cssURL, cssText.value())
        .then(onCSSParsed);

    /**
     * @param {!WebInspector.SASSSupport.AST} newCSSAST
     * @return {!Promise<?WebInspector.SourceMap.EditResult>}
     */
    function onCSSParsed(newCSSAST)
    {
        if (newCSSAST.rules.length !== map.compiledModel().rules.length)
            return Promise.resolve(/** @type {?WebInspector.SourceMap.EditResult} */(null));
        //TODO(lushnikov): only diff changed styles.
        var cssDiff = WebInspector.SASSSupport.diffModels(map.compiledModel(), newCSSAST);
        var edits = WebInspector.SASSProcessor._editsFromCSSDiff(cssDiff, map);

        // Determine AST trees which will change and clone them.
        var changedURLs = new Set(edits.map(edit => edit.sassURL));
        changedURLs.add(map.compiledURL());
        var clonedModels = [];
        for (var url of changedURLs)
            clonedModels.push(map.modelForURL(url).clone());

        // Rebase map and edits onto a cloned AST trees.
        var nodeMapping = new Map();
        var rebasedMap = /** @type {!WebInspector.ASTSourceMap} */(map.rebase(clonedModels, nodeMapping));
        console.assert(rebasedMap);
        var rebasedEdits = edits.map(edit => edit.rebase(rebasedMap, nodeMapping));

        return new WebInspector.SASSProcessor(astService, rebasedMap, rebasedEdits)._mutate();
    }
}

/**
 * @param {!WebInspector.SASSSupport.ASTDiff} cssDiff
 * @param {!WebInspector.ASTSourceMap} map
 * @return {!Array<!WebInspector.SASSProcessor.EditOperation>}
 */
WebInspector.SASSProcessor._editsFromCSSDiff = function(cssDiff, map)
{
    var T = WebInspector.SASSSupport.PropertyChangeType;
    var operations = [];
    for (var i = 0; i < cssDiff.changes.length; ++i) {
        var change = cssDiff.changes[i];
        var operation = null;
        if (change.type === T.ValueChanged || change.type === T.NameChanged)
            operation = WebInspector.SASSProcessor.SetTextOperation.fromCSSChange(change, map);
        else if (change.type === T.PropertyToggled)
            operation = WebInspector.SASSProcessor.TogglePropertyOperation.fromCSSChange(change, map);
        else if (change.type === T.PropertyRemoved)
            operation = WebInspector.SASSProcessor.RemovePropertyOperation.fromCSSChange(change, map);
        else if (change.type === T.PropertyAdded)
            operation = WebInspector.SASSProcessor.InsertPropertiesOperation.fromCSSChange(change, map);
        if (!operation) {
            WebInspector.console.error("Operation ignored: " + change.type);
            continue;
        }

        var merged = false;
        for (var j = 0; !merged && j < operations.length; ++j)
            merged = operations[j].merge(operation);
        if (!merged)
            operations.push(operation);
    }
    return operations;
}

/**
 * @constructor
 * @param {!WebInspector.ASTSourceMap} map
 * @param {string} sassURL
 */
WebInspector.SASSProcessor.EditOperation = function(map, sassURL)
{
    this.map = map;
    this.sassURL = sassURL;
}

WebInspector.SASSProcessor.EditOperation.prototype = {
    /**
     * @param {!WebInspector.SASSProcessor.EditOperation} other
     * @return {boolean}
     */
    merge: function(other)
    {
        return false;
    },

    /**
     * @return {!Array<!WebInspector.SASSSupport.Rule>}
     */
    perform: function()
    {
        return [];
    },

    /**
     * @param {!WebInspector.ASTSourceMap} newMap
     * @param {!Map<!WebInspector.SASSSupport.Node, !WebInspector.SASSSupport.Node>} nodeMapping
     * @return {!WebInspector.SASSProcessor.EditOperation}
     */
    rebase: function(newMap, nodeMapping)
    {
        return this;
    },
}

/**
 * @constructor
 * @extends {WebInspector.SASSProcessor.EditOperation}
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!WebInspector.SASSSupport.TextNode} sassNode
 * @param {string} newText
 */
WebInspector.SASSProcessor.SetTextOperation = function(map, sassNode, newText)
{
    WebInspector.SASSProcessor.EditOperation.call(this, map, sassNode.document.url);
    this._sassNode = sassNode;
    this._newText = newText;
}

/**
 * @param {!WebInspector.SASSSupport.PropertyChange} change
 * @param {!WebInspector.ASTSourceMap} map
 * @return {?WebInspector.SASSProcessor.SetTextOperation}
 */
WebInspector.SASSProcessor.SetTextOperation.fromCSSChange = function(change, map)
{
    var oldProperty = /** @type {!WebInspector.SASSSupport.Property} */(change.oldProperty());
    var newProperty = /** @type {!WebInspector.SASSSupport.Property} */(change.newProperty());
    console.assert(oldProperty && newProperty, "SetTextOperation must have both oldProperty and newProperty");
    var newValue = null;
    var sassNode = null;
    if (change.type === WebInspector.SASSSupport.PropertyChangeType.NameChanged) {
        newValue = newProperty.name.text;
        sassNode = map.toSourceNode(oldProperty.name);
    } else {
        newValue = newProperty.value.text;
        sassNode = map.toSourceNode(oldProperty.value);
    }
    if (!sassNode)
        return null;
    return new WebInspector.SASSProcessor.SetTextOperation(map, sassNode, newValue);
}

WebInspector.SASSProcessor.SetTextOperation.prototype = {
    /**
     * @override
     * @param {!WebInspector.SASSProcessor.EditOperation} other
     * @return {boolean}
     */
    merge: function(other)
    {
        if (!(other instanceof WebInspector.SASSProcessor.SetTextOperation))
            return false;
        return this._sassNode === other._sassNode;
    },

    /**
     * @override
     * @return {!Array<!WebInspector.SASSSupport.Rule>}
     */
    perform: function()
    {
        this._sassNode.setText(this._newText);
        var nodes = this.map.toCompiledNodes(this._sassNode);
        for (var node of nodes)
            node.setText(this._newText);

        var cssRules = nodes.map(textNode => textNode.parent.parent);
        return cssRules;
    },

    /**
     * @override
     * @param {!WebInspector.ASTSourceMap} newMap
     * @param {!Map<!WebInspector.SASSSupport.Node, !WebInspector.SASSSupport.Node>} nodeMapping
     * @return {!WebInspector.SASSProcessor.SetTextOperation}
     */
    rebase: function(newMap, nodeMapping)
    {
        var sassNode = /** @type {?WebInspector.SASSSupport.TextNode} */(nodeMapping.get(this._sassNode)) || this._sassNode;
        return new WebInspector.SASSProcessor.SetTextOperation(newMap, sassNode, this._newText);
    },

    __proto__: WebInspector.SASSProcessor.EditOperation.prototype
}

/**
 * @constructor
 * @extends {WebInspector.SASSProcessor.EditOperation}
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!WebInspector.SASSSupport.Property} sassProperty
 * @param {boolean} newDisabled
 */
WebInspector.SASSProcessor.TogglePropertyOperation = function(map, sassProperty, newDisabled)
{
    WebInspector.SASSProcessor.EditOperation.call(this, map, sassProperty.document.url);
    this._sassProperty = sassProperty;
    this._newDisabled = newDisabled;
}

/**
 * @param {!WebInspector.SASSSupport.PropertyChange} change
 * @param {!WebInspector.ASTSourceMap} map
 * @return {?WebInspector.SASSProcessor.TogglePropertyOperation}
 */
WebInspector.SASSProcessor.TogglePropertyOperation.fromCSSChange = function(change, map)
{
    var oldCSSProperty = /** @type {!WebInspector.SASSSupport.Property} */(change.oldProperty());
    console.assert(oldCSSProperty, "TogglePropertyOperation must have old CSS property");
    var sassProperty = WebInspector.SASSProcessor._toSASSProperty(map, oldCSSProperty);
    if (!sassProperty)
        return null;
    var newDisabled = change.newProperty().disabled;
    return new WebInspector.SASSProcessor.TogglePropertyOperation(map, sassProperty, newDisabled);
}

WebInspector.SASSProcessor.TogglePropertyOperation.prototype = {
    /**
     * @override
     * @param {!WebInspector.SASSProcessor.EditOperation} other
     * @return {boolean}
     */
    merge: function(other)
    {
        if (!(other instanceof WebInspector.SASSProcessor.TogglePropertyOperation))
            return false;
        return this._sassProperty === other._sassProperty;
    },

    /**
     * @override
     * @return {!Array<!WebInspector.SASSSupport.Rule>}
     */
    perform: function()
    {
        this._sassProperty.setDisabled(this._newDisabled);
        var cssProperties = WebInspector.SASSProcessor._toCSSProperties(this.map, this._sassProperty);
        for (var property of cssProperties)
            property.setDisabled(this._newDisabled);

        var cssRules = cssProperties.map(property => property.parent);
        return cssRules;
    },

    /**
     * @override
     * @param {!WebInspector.ASTSourceMap} newMap
     * @param {!Map<!WebInspector.SASSSupport.Node, !WebInspector.SASSSupport.Node>} nodeMapping
     * @return {!WebInspector.SASSProcessor.TogglePropertyOperation}
     */
    rebase: function(newMap, nodeMapping)
    {
        var sassProperty = /** @type {?WebInspector.SASSSupport.Property} */(nodeMapping.get(this._sassProperty)) || this._sassProperty;
        return new WebInspector.SASSProcessor.TogglePropertyOperation(newMap, sassProperty, this._newDisabled);
    },

    __proto__: WebInspector.SASSProcessor.EditOperation.prototype
}

/**
 * @constructor
 * @extends {WebInspector.SASSProcessor.EditOperation}
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!WebInspector.SASSSupport.Property} sassProperty
 */
WebInspector.SASSProcessor.RemovePropertyOperation = function(map, sassProperty)
{
    WebInspector.SASSProcessor.EditOperation.call(this, map, sassProperty.document.url);
    this._sassProperty = sassProperty;
}

/**
 * @param {!WebInspector.SASSSupport.PropertyChange} change
 * @param {!WebInspector.ASTSourceMap} map
 * @return {?WebInspector.SASSProcessor.RemovePropertyOperation}
 */
WebInspector.SASSProcessor.RemovePropertyOperation.fromCSSChange = function(change, map)
{
    var removedProperty = /** @type {!WebInspector.SASSSupport.Property} */(change.oldProperty());
    console.assert(removedProperty, "RemovePropertyOperation must have removed CSS property");
    var sassProperty = WebInspector.SASSProcessor._toSASSProperty(map, removedProperty);
    if (!sassProperty)
        return null;
    return new WebInspector.SASSProcessor.RemovePropertyOperation(map, sassProperty);
}

WebInspector.SASSProcessor.RemovePropertyOperation.prototype = {
    /**
     * @override
     * @param {!WebInspector.SASSProcessor.EditOperation} other
     * @return {boolean}
     */
    merge: function(other)
    {
        if (!(other instanceof WebInspector.SASSProcessor.RemovePropertyOperation))
            return false;
        return this._sassProperty === other._sassProperty;
    },

    /**
     * @override
     * @return {!Array<!WebInspector.SASSSupport.Rule>}
     */
    perform: function()
    {
        var cssProperties = WebInspector.SASSProcessor._toCSSProperties(this.map, this._sassProperty);
        var cssRules = cssProperties.map(property => property.parent);
        this._sassProperty.remove();
        for (var cssProperty of cssProperties) {
            cssProperty.remove();
            this.map.removeMapping(cssProperty.name, this._sassProperty.name);
            this.map.removeMapping(cssProperty.value, this._sassProperty.value);
        }

        return cssRules;
    },

    /**
     * @override
     * @param {!WebInspector.ASTSourceMap} newMap
     * @param {!Map<!WebInspector.SASSSupport.Node, !WebInspector.SASSSupport.Node>} nodeMapping
     * @return {!WebInspector.SASSProcessor.RemovePropertyOperation}
     */
    rebase: function(newMap, nodeMapping)
    {
        var sassProperty = /** @type {?WebInspector.SASSSupport.Property} */(nodeMapping.get(this._sassProperty)) || this._sassProperty;
        return new WebInspector.SASSProcessor.RemovePropertyOperation(newMap, sassProperty);
    },

    __proto__: WebInspector.SASSProcessor.EditOperation.prototype
}

/**
 * @constructor
 * @extends {WebInspector.SASSProcessor.EditOperation}
 * @param {!WebInspector.ASTSourceMap} map
 * @param {!WebInspector.SASSSupport.Property} sassAnchor
 * @param {boolean} insertBefore
 * @param {!Array<string>} propertyNames
 * @param {!Array<string>} propertyValues
 * @param {!Array<boolean>} disabledStates
 */
WebInspector.SASSProcessor.InsertPropertiesOperation = function(map, sassAnchor, insertBefore, propertyNames, propertyValues, disabledStates)
{
    console.assert(propertyNames.length === propertyValues.length && propertyValues.length === disabledStates.length);
    WebInspector.SASSProcessor.EditOperation.call(this, map, sassAnchor.document.url);
    this._sassAnchor = sassAnchor;
    this._insertBefore = insertBefore;
    this._nameTexts = propertyNames;
    this._valueTexts = propertyValues;
    this._disabledStates = disabledStates;
}

/**
 * @param {!WebInspector.SASSSupport.PropertyChange} change
 * @param {!WebInspector.ASTSourceMap} map
 * @return {?WebInspector.SASSProcessor.InsertPropertiesOperation}
 */
WebInspector.SASSProcessor.InsertPropertiesOperation.fromCSSChange = function(change, map)
{
    var insertBefore = false;
    var cssAnchor = null;
    var sassAnchor = null;
    if (change.oldPropertyIndex) {
        cssAnchor = change.oldRule.properties[change.oldPropertyIndex - 1].name;
        sassAnchor = map.toSourceNode(cssAnchor);
    } else {
        insertBefore = true;
        cssAnchor = change.oldRule.properties[0].name;
        sassAnchor = map.toSourceNode(cssAnchor);
    }
    if (!sassAnchor)
        return null;
    var insertedProperty = /** @type {!WebInspector.SASSSupport.Property} */(change.newProperty());
    console.assert(insertedProperty, "InsertPropertiesOperation must have inserted CSS property");
    var names = [insertedProperty.name.text];
    var values = [insertedProperty.value.text];
    var disabledStates = [insertedProperty.disabled];
    return new WebInspector.SASSProcessor.InsertPropertiesOperation(map, sassAnchor.parent, insertBefore, names, values, disabledStates);
}

WebInspector.SASSProcessor.InsertPropertiesOperation.prototype = {
    /**
     * @override
     * @param {!WebInspector.SASSProcessor.EditOperation} other
     * @return {boolean}
     */
    merge: function(other)
    {
        if (!(other instanceof WebInspector.SASSProcessor.InsertPropertiesOperation))
            return false;
        if (this._sassAnchor !== other._sassAnchor || this._insertBefore !== other._insertBefore)
            return false;
        var names = new Set(this._nameTexts);
        for (var i = 0; i < other._nameTexts.length; ++i) {
            var nameText = other._nameTexts[i];
            if (names.has(nameText))
                continue;
            this._nameTexts.push(nameText);
            this._valueTexts.push(other._valueTexts[i]);
            this._disabledStates.push(other._disabledStates[i]);
        }
        return true;
    },

    /**
     * @override
     * @return {!Array<!WebInspector.SASSSupport.Rule>}
     */
    perform: function()
    {
        var cssRules = [];
        var sassRule = this._sassAnchor.parent;
        var newSASSProperties = sassRule.insertProperties(this._nameTexts, this._valueTexts, this._disabledStates, this._sassAnchor, this._insertBefore);
        var cssAnchors = WebInspector.SASSProcessor._toCSSProperties(this.map, this._sassAnchor);
        for (var cssAnchor of cssAnchors) {
            var cssRule = cssAnchor.parent;
            cssRules.push(cssRule);
            var newCSSProperties = cssRule.insertProperties(this._nameTexts, this._valueTexts, this._disabledStates, cssAnchor, this._insertBefore);
            for (var i = 0; i < newCSSProperties.length; ++i) {
                this.map.addMapping(newCSSProperties[i].name, newSASSProperties[i].name);
                this.map.addMapping(newCSSProperties[i].value, newSASSProperties[i].value);
            }
        }
        return cssRules;
    },

    /**
     * @override
     * @param {!WebInspector.ASTSourceMap} newMap
     * @param {!Map<!WebInspector.SASSSupport.Node, !WebInspector.SASSSupport.Node>} nodeMapping
     * @return {!WebInspector.SASSProcessor.InsertPropertiesOperation}
     */
    rebase: function(newMap, nodeMapping)
    {
        var sassAnchor = /** @type {?WebInspector.SASSSupport.Property} */(nodeMapping.get(this._sassAnchor)) || this._sassAnchor;
        return new WebInspector.SASSProcessor.InsertPropertiesOperation(newMap, sassAnchor, this._insertBefore, this._nameTexts, this._valueTexts, this._disabledStates);
    },

    __proto__: WebInspector.SASSProcessor.EditOperation.prototype
}


text:
require_relative '../helper'

describe Geotrigger::Device do

  let :dev do
    s = Geotrigger::AGO::Session.new client_id: CONF[:client_id],
                                     type: :device

    # can't use this because Geotrigger doesn't know it yet
    #
    ago_did = s.device_data['deviceId']

    # make a call to Geotrigger so it learns of new device
    #
    at = s.access_token
    r = HTTPClient.new.get Geotrigger::Session::BASE_URL % 'device/list',
                           nil,
                           'Authorization' => "Bearer #{at}"

    gt_did = JSON.parse(r.body)['devices'][0]['deviceId']

    # assert ids are the same
    #
    ago_did.should eq gt_did

    Geotrigger::Device.new client_id: CONF[:client_id],
                   client_secret: CONF[:client_secret],
                   device_id: ago_did
  end

  it 'fetches tags' do
    ts = dev.tags
    ts.should_not be nil
    ts.should be_a Array
    ts.first.should be_a Geotrigger::Tag
    ts.first.name.should eq dev.default_tag
  end

  it 'knows the default tag' do
    dev.default_tag =~ /^device:\S+$/
  end

  it 'updates' do
    dev.properties = {'foo' => 'bar'}
    dev.trackingProfile = 'adaptive'
    dev.save
    dev.properties.should eq({'foo' => 'bar'})
    dev.trackingProfile.should eq 'adaptive'
  end

  it 'adds tags' do
    ts = dev.tags
    ts.length.should eq 1
    dev.add_tags 'foo', 'bar'
    dev.save
    ts = dev.tags
    ts.length.should eq 3
  end

  it 'sets tags' do
    ts = dev.tags
    ts.length.should eq 1
    dev.tags = dev.default_tag, 'fu', 'bat'
    dev.save
    ts = dev.tags
    ts.length.should eq 3
  end

  it 'removes tags' do
    dev.tags = dev.default_tag, 'fizz', 'buzz'
    dev.save
    sleep 3
    ts = dev.tags
    ts.length.should eq 3
    dev.remove_tags 'fizz', 'buzz'
    dev.save
    ts = dev.tags
    ts.length.should eq 1
  end

end


text:
class MyApplication : public QApplication
{
public:
	MyApplication(int& argc, char** argv): QApplication(argc, argv) { }
	virtual ~MyApplication() { }

	// reimplemented from QApplication so we can throw exceptions in slots
	virtual bool notify(QObject* receiver, QEvent* event) {
		try {
			return QApplication::notify(receiver, event);
		} catch(std::exception& e) {
			  qCritical() << "Exception thrown:" << e.what();
		}
		return false;
	}
};

int main(int argc, char *argv[])
{
	MyApplication a(argc, argv);
	WrfAnalysisPlatform w;
	w.show();

	return a.exec();
}


text: {{'scheduler.jobs' | translate}}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Jap. Bot. 43: 281 (1968)

#### Original name
Sphaeria melastomatum Lév., 1845

### Remarks
null


text:
<component name="libraryTable">
  <library name="Maven: mysql:mysql-connector-java:5.1.39">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/mysql/mysql-connector-java/5.1.39/mysql-connector-java-5.1.39-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
require 'spec_helper'

describe User do
  it "has a valid factory" do
    expect(create(:user)).to be_valid
  end

  it "is invalid without a first name" do
    expect(build(:user, first_name: nil)).to_not be_valid
  end

  it "is invalid without a last name" do
    expect(build(:user, last_name: nil)).to_not be_valid
  end

  it "is invalid without an username" do
    expect(build(:user, username: nil)).to_not be_valid
  end

  it "is invalid without a password" do
    expect(build(:user, password: nil)).to_not be_valid
  end

  it "is invalid when password and confirmation don't match" do
    expect(build(:user, password: 'acbd1234',
                        password_confirmation: '1234abcd')).to_not be_valid
  end

  it "is invalid with a short password" do
    short_password = "a" * 5
    expect(build(:user, password: short_password,
                        password_confirmation: short_password)).to_not be_valid
  end

  it "is invalid with a duplicate username" do
    create(:user, username: 'foo')
    expect(build(:user, username: 'FOO')).to_not be_valid
  end

  it "has an encrypted password" do
    expect(build(:user).encrypted_password).to_not be_blank
  end

  it "returns full name as a string" do
    expect(build(:user, first_name: 'John',
                        last_name: 'Doe').name).to eq 'John Doe'
  end
end


text:
from __future__ import unicode_literals

from django import forms
from django.template import Template, Context
from django.utils.unittest import TestCase

from .exceptions import BootstrapError

RADIO_CHOICES = (
    ('1', 'Radio 1'),
    ('2', 'Radio 2'),
)

MEDIA_CHOICES = (
    ('Audio', (
        ('vinyl', 'Vinyl'),
        ('cd', 'CD'),
    )
    ),
    ('Video', (
        ('vhs', 'VHS Tape'),
        ('dvd', 'DVD'),
    )
    ),
    ('unknown', 'Unknown'),
)

class TestForm(forms.Form):
    """
    Form with a variety of widgets to test bootstrap3 rendering.
    """
    subject = forms.CharField(
        max_length=100,
        help_text='my_help_text',
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'placeholdertest'}),
    )
    message = forms.CharField(required=False, help_text='my_help_text')
    sender = forms.EmailField()
    secret = forms.CharField(initial=42, widget=forms.HiddenInput)
    cc_myself = forms.BooleanField(required=False, help_text='You will get a copy in your mailbox.')
    select1 = forms.ChoiceField(choices=RADIO_CHOICES)
    select2 = forms.MultipleChoiceField(
        choices=RADIO_CHOICES,
        help_text='Check as many as you like.',
    )
    select3 = forms.ChoiceField(choices=MEDIA_CHOICES)
    select4 = forms.MultipleChoiceField(
        choices=MEDIA_CHOICES,
        help_text='Check as many as you like.',
    )
    category1 = forms.ChoiceField(choices=RADIO_CHOICES, widget=forms.RadioSelect)
    category2 = forms.MultipleChoiceField(
        choices=RADIO_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text='Check as many as you like.',
    )
    category3 = forms.ChoiceField(widget=forms.RadioSelect, choices=MEDIA_CHOICES)
    category4 = forms.MultipleChoiceField(
        choices=MEDIA_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        help_text='Check as many as you like.',
    )

    def clean(self):
        cleaned_data = super(TestForm, self).clean()
        raise forms.ValidationError("This error was added to show the non field errors styling.")
        return cleaned_data

def render_template(text, **context_args):
    """
    Create a template ``text`` that first loads bootstrap3.
    """
    template = Template("{% load bootstrap3 %}" + text)
    if not 'form' in context_args:
        context_args['form'] = TestForm()
    return template.render(Context(context_args))

def render_formset(formset=None, **context_args):
    """
    Create a template that renders a formset
    """
    context_args['formset'] = formset
    return render_template('{% bootstrap_formset formset %}', **context_args)

def render_form(form=None, **context_args):
    """
    Create a template that renders a form
    """
    if form:
        context_args['form'] = form
    return render_template('{% bootstrap_form form %}', **context_args)

def render_form_field(field, **context_args):
    """
    Create a template that renders a field
    """
    form_field = 'form.%s' % field
    return render_template('{% bootstrap_field ' + form_field + ' %}', **context_args)

def render_field(field, **context_args):
    """
    Create a template that renders a field
    """
    context_args['field'] = field
    return render_template('{% bootstrap_field field %}', **context_args)

class SettingsTest(TestCase):

    def test_settings(self):
        from .bootstrap import BOOTSTRAP3
        self.assertTrue(BOOTSTRAP3)

class TemplateTest(TestCase):

    def test_empty_template(self):
        res = render_template('')
        self.assertEqual(res.strip(), '')

    def test_text_template(self):
        res = render_template('some text')
        self.assertEqual(res.strip(), 'some text')

    def test_bootstrap_template(self):
        template = Template(('{% extends "bootstrap3/bootstrap3.html" %}{% block bootstrap3_content %}test_bootstrap3_content{% endblock %}'))
        res = template.render(Context({}))
        self.assertIn('test_bootstrap3_content', res)

    def test_javascript_without_jquery(self):
        res = render_template('{% bootstrap_javascript jquery=0 %}')
        self.assertIn('bootstrap', res)
        self.assertNotIn('jquery', res)

    def test_javascript_with_jquery(self):
        res = render_template('{% bootstrap_javascript jquery=1 %}')
        self.assertIn('bootstrap', res)
        self.assertIn('jquery', res)

class FormSetTest(TestCase):

    def test_illegal_formset(self):
        with self.assertRaises(BootstrapError):
            render_formset(formset='illegal')

class FormTest(TestCase):

    def test_illegal_form(self):
        with self.assertRaises(BootstrapError):
            render_form(form='illegal')

    def test_field_names(self):
        form = TestForm()
        res = render_form(form)
        for field in form:
            self.assertIn('name="%s"' % field.name, res)

    def test_exclude(self):
        form = TestForm()
        res = render_template('{% bootstrap_form form exclude="cc_myself" %}', form=form)
        self.assertNotIn('cc_myself', res)

    def test_layout_horizontal(self):
        form = TestForm()
        res = render_template('{% bootstrap_form form layout="horizontal" %}', form=form)
        self.assertIn('col-md-2', res)
        self.assertIn('col-md-4', res)

    def test_buttons_tag(self):
        form = TestForm()
        res = render_template('{% buttons layout="horizontal" %}{% endbuttons %}', form=form)
        self.assertIn('col-md-2', res)
        self.assertIn('col-md-4', res)

class FieldTest(TestCase):

    def test_illegal_field(self):
        with self.assertRaises(BootstrapError):
            render_field(field='illegal')

    def test_show_help(self):
        res = render_form_field('subject')
        self.assertIn('my_help_text', res)
        self.assertNotIn('my_help_text', res)
        res = render_template('{% bootstrap_field form.subject show_help=0 %}')
        self.assertNotIn('my_help_text', res)

    def test_subject(self):
        res = render_form_field('subject')
        self.assertIn('type="text"', res)
        self.assertIn('placeholder="placeholdertest"', res)

    def test_required_field(self):
        required_field = render_form_field('subject')
        self.assertIn('required', required_field)
        not_required_field = render_form_field('message')
        self.assertNotIn('required', not_required_field)
        # Required field with required=0
        form_field = 'form.subject'
        rendered = render_template('{% bootstrap_field ' + form_field + ' set_required=0 %}')
        self.assertNotIn('required', rendered)

class IconTest(TestCase):

    def test_icon(self):
        res = render_template('{% bootstrap_icon "star" %}')
        self.assertEqual(res.strip(), '')

class MessagesTest(TestCase):

    def test_messages(self):
        class FakeMessage(object):
            """
            Follows the `django.contrib.messages.storage.base.Message` API.
            """
            def __init__(self, message, tags):
                self.tags = tags
                self.message = message

            def __str__(self):
                return self.message

        messages = [FakeMessage("hello", "warning")]
        res = render_template('{% bootstrap_messages messages %}', messages=messages)
        expected = """

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        hello

"""
        self.assertEqual(res.strip(), expected.strip())

        messages = [FakeMessage("hello", "error")]
        res = render_template('{% bootstrap_messages messages %}', messages=messages)
        expected = """

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        hello

        """
        self.assertEqual(res.strip(), expected.strip())

        messages = [FakeMessage("hello", None)]
        res = render_template('{% bootstrap_messages messages %}', messages=messages)
        expected = """

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        hello

"""
        self.assertEqual(res.strip(), expected.strip())


text:
package tabou.http;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.net.ServerSocket;
import java.net.Socket;
import tabou.log.TabouLog;
import static tabou.log.TabouLog.Log;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;

public class Servletd {
    static private final int DEFAULT_PROXY_PORT = 8080;
    private ServerSocket serverSocket;

    public static void usage() {
        System.err.println("usage: java tabou.http.EchoHttp [-p port no]");
        System.exit(-1);
    }
    public static void main(String[] args) throws Exception{
        TabouLog.init();
        int localPort = DEFAULT_PROXY_PORT;  /* port no       */
        Servletd servletd = new Servletd();
        int argi = 0;
        for (; argi < args.length; argi++) {
            char[] chars = args[argi].toCharArray();
            if (chars[0] != '-') {
                break;
            }
            if (chars.length != 2) {
                System.err.println("invalid option:" + args[argi]);
                usage();
            }
            char c = chars[1];
            switch (c) {
            case 'p':
                localPort = Integer.parseInt(args[++argi]);  /*port no       */
                break;
            default:
                System.err.println("invalid option:" + c);
                usage();
            }
        }
        servletd.accrpt(localPort);
    }
    public void accrpt(int localPort) throws IOException{
        this.serverSocket = new ServerSocket(localPort);
        while (true) {
            Log.info("wait:*."+ localPort  +" ...");
            Socket requestSocket = this.serverSocket.accept();
            Log.info("accept:" + requestSocket.getInetAddress());
            try{
                request(requestSocket);
            }catch(Exception e){
                Log.log(Level.WARNING,e.toString(),e);
            }finally{
                requestSocket.close();
            }
            Log.info("close");
        }
    }
    public void close() throws IOException{
        this.serverSocket.close();
    }
    public void request(Socket requestSocket) throws ServletException,IOException{
        requestSocket.setSoTimeout(1000 * 100);

        ServletInputStreamImpl servletInputStream = new ServletInputStreamImpl(new BufferedInputStream(requestSocket.getInputStream()));
        ServletOutputStream servletOutputStream = new ServletOutputStreamImpl(requestSocket.getOutputStream());
        String firstLine = servletInputStream.readLine();
        Log.info(firstLine);
        int contentLength = 0;
        while(true){
            String line = servletInputStream.readLine();
            if(line == null){
                break;
            }else if(line.equals("")){
                break;
            }
            Log.info(line);
            int index = line.indexOf(':');
            String tagName = line.substring(0,index).toUpperCase();
            String value   = line.substring(index +1).trim();
            if(tagName.equals("CONTENT-LENGTH")){
                contentLength = Integer.parseInt(value);
            }
        }

        for(int i = 0;i < contentLength;i++){
            int c = servletInputStream.read();
            if(c < 0){
                break;
            }
//            byteArrayOutputStream.write(c);
        }
        HelloServlet httpServlet         = new HelloServlet();
        ServletContext servletContext    = new ServletContextImpl();
        HttpServletRequestImpl request   = new HttpServletRequestImpl(servletContext);
        HttpServletResponseImpl response = new HttpServletResponseImpl();
        response.setHeader("Connection","close");
        response.setStream(servletOutputStream);
        httpServlet.doGet(request,response);
        response.getWriter().close();
        servletOutputStream.close();
        servletInputStream.close();
    }
}


text:
package queryservice

import (
	"io"

	"golang.org/x/net/context"

	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/vt/vttablet/tabletserver/querytypes"

	querypb "github.com/youtube/vitess/go/vt/proto/query"
)

// QueryService is the interface implemented by the tablet's query service.
// All streaming methods accept a callback function that will be called for
// each response. If the callback returns an error, that error is returned
// back by the function, except in the case of io.EOF in which case the stream
// will be terminated with no error. Streams can also be terminated by canceling
// the context.
// This API is common for both server and client implementations. All functions
// must be safe to be called concurrently.
type QueryService interface {
	// Transaction management

	// Begin returns the transaction id to use for further operations
	Begin(ctx context.Context, target *querypb.Target) (int64, error)

	// Commit commits the current transaction
	Commit(ctx context.Context, target *querypb.Target, transactionID int64) error

	// Rollback aborts the current transaction
	Rollback(ctx context.Context, target *querypb.Target, transactionID int64) error

	// Prepare prepares the specified transaction.
	Prepare(ctx context.Context, target *querypb.Target, transactionID int64, dtid string) (err error)

	// CommitPrepared commits the prepared transaction.
	CommitPrepared(ctx context.Context, target *querypb.Target, dtid string) (err error)

	// RollbackPrepared rolls back the prepared transaction.
	RollbackPrepared(ctx context.Context, target *querypb.Target, dtid string, originalID int64) (err error)

	// CreateTransaction creates the metadata for a 2PC transaction.
	CreateTransaction(ctx context.Context, target *querypb.Target, dtid string, participants []*querypb.Target) (err error)

	// StartCommit atomically commits the transaction along with the
	// decision to commit the associated 2pc transaction.
	StartCommit(ctx context.Context, target *querypb.Target, transactionID int64, dtid string) (err error)

	// SetRollback transitions the 2pc transaction to the Rollback state.
	// If a transaction id is provided, that transaction is also rolled back.
	SetRollback(ctx context.Context, target *querypb.Target, dtid string, transactionID int64) (err error)

	// ConcludeTransaction deletes the 2pc transaction metadata
	// essentially resolving it.
	ConcludeTransaction(ctx context.Context, target *querypb.Target, dtid string) (err error)

	// ReadTransaction returns the metadata for the sepcified dtid.
	ReadTransaction(ctx context.Context, target *querypb.Target, dtid string) (metadata *querypb.TransactionMetadata, err error)

	// Query execution
	Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]interface{}, transactionID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, error)
	StreamExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]interface{}, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error
	ExecuteBatch(ctx context.Context, target *querypb.Target, queries []querytypes.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) ([]sqltypes.Result, error)

	// Combo methods, they also return the transactionID from the
	// Begin part. If err != nil, the transactionID may still be
	// non-zero, and needs to be propagated back (like for a DB
	// Integrity Error)
	BeginExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]interface{}, options *querypb.ExecuteOptions) (*sqltypes.Result, int64, error)
	BeginExecuteBatch(ctx context.Context, target *querypb.Target, queries []querytypes.BoundQuery, asTransaction bool, options *querypb.ExecuteOptions) ([]sqltypes.Result, int64, error)

	// Messaging methods.
	MessageStream(ctx context.Context, target *querypb.Target, name string, callback func(*sqltypes.Result) error) error
	MessageAck(ctx context.Context, target *querypb.Target, name string, ids []*querypb.Value) (count int64, err error)

	// SplitQuery is a MapReduce helper function
	// This version of SplitQuery supports multiple algorithms and multiple split columns.
	// See the documentation of SplitQueryRequest in 'proto/vtgate.proto' for more information.
	SplitQuery(ctx context.Context, target *querypb.Target, query querytypes.BoundQuery, splitColumns []string, splitCount int64, numRowsPerQueryPart int64, algorithm querypb.SplitQueryRequest_Algorithm) ([]querytypes.QuerySplit, error)

	// UpdateStream streams updates from the provided position or timestamp.
	UpdateStream(ctx context.Context, target *querypb.Target, position string, timestamp int64, callback func(*querypb.StreamEvent) error) error

	// StreamHealth streams health status.
	StreamHealth(ctx context.Context, callback func(*querypb.StreamHealthResponse) error) error

	// HandlePanic will be called if any of the functions panic.
	HandlePanic(err *error)

	// Close must be called for releasing resources.
	Close(ctx context.Context) error
}

type resultStreamer struct {
	done chan struct{}
	ch   chan *sqltypes.Result
	err  error
}

func (rs *resultStreamer) Recv() (*sqltypes.Result, error) {
	select {
	case <-rs.done:
		return nil, rs.err
	case qr := <-rs.ch:
		return qr, nil
	}
}

// ExecuteWithStreamer performs a StreamExecute, but returns a *sqltypes.ResultStream to iterate on.
// This function should only be used for legacy code. New usage should directly use StreamExecute.
func ExecuteWithStreamer(ctx context.Context, conn QueryService, target *querypb.Target, sql string, bindVariables map[string]interface{}, options *querypb.ExecuteOptions) sqltypes.ResultStream {
	rs := &resultStreamer{
		done: make(chan struct{}),
		ch:   make(chan *sqltypes.Result),
	}
	go func() {
		defer close(rs.done)
		rs.err = conn.StreamExecute(ctx, target, sql, bindVariables, options, func(qr *sqltypes.Result) error {
			select {
			case <-ctx.Done():
				return io.EOF
			case rs.ch <- qr:
			}
			return nil
		})
		if rs.err == nil {
			rs.err = io.EOF
		}
	}()
	return rs
}


text:
/***************************************************************************/
/* RSC IDENTIFIER: POLAR STEREOGRAPHIC
 *
 *
 * ABSTRACT
 *
 *    This component provides conversions between geodetic (latitude and
 *    longitude) coordinates and Polar Stereographic (easting and northing)
 *    coordinates.
 *
 * ERROR HANDLING
 *
 *    This component checks parameters for valid values.  If an invalid
 *    value is found the error code is combined with the current error code
 *    using the bitwise or.  This combining allows multiple error codes to
 *    be returned. The possible error codes are:
 *
 *          POLAR_NO_ERROR           : No errors occurred in function
 *          POLAR_LAT_ERROR          : Latitude outside of valid range
 *                                      (-90 to 90 degrees)
 *          POLAR_LON_ERROR          : Longitude outside of valid range
 *                                      (-180 to 360 degrees)
 *          POLAR_ORIGIN_LAT_ERROR   : Latitude of true scale outside of valid
 *                                      range (-90 to 90 degrees)
 *          POLAR_ORIGIN_LON_ERROR   : Longitude down from pole outside of valid
 *                                      range (-180 to 360 degrees)
 *          POLAR_EASTING_ERROR      : Easting outside of valid range,
 *                                      depending on ellipsoid and
 *                                      projection parameters
 *          POLAR_NORTHING_ERROR     : Northing outside of valid range,
 *                                      depending on ellipsoid and
 *                                      projection parameters
 *          POLAR_RADIUS_ERROR       : Coordinates too far from pole,
 *                                      depending on ellipsoid and
 *                                      projection parameters
 *          POLAR_A_ERROR            : Semi-major axis less than or equal to zero
 *          POLAR_INV_F_ERROR        : Inverse flattening outside of valid range
 *								  	                  (250 to 350)
 *
 *
 * REUSE NOTES
 *
 *    POLAR STEREOGRAPHIC is intended for reuse by any application that
 *    performs a Polar Stereographic projection.
 *
 *
 * REFERENCES
 *
 *    Further information on POLAR STEREOGRAPHIC can be found in the
 *    Reuse Manual.
 *
 *
 *    POLAR STEREOGRAPHIC originated from :
 *                                U.S. Army Topographic Engineering Center
 *                                Geospatial Information Division
 *                                7701 Telegraph Road
 *                                Alexandria, VA  22310-3864
 *
 *
 * LICENSES
 *
 *    None apply to this component.
 *
 *
 * RESTRICTIONS
 *
 *    POLAR STEREOGRAPHIC has no restrictions.
 *
 *
 * ENVIRONMENT
 *
 *    POLAR STEREOGRAPHIC was tested and certified in the following
 *    environments:
 *
 *    1. Solaris 2.5 with GCC, version 2.8.1
 *    2. Window 95 with MS Visual C++, version 6
 *
 *
 * MODIFICATIONS
 *
 *    Date              Description
 *    ----              -----------
 *    06-11-95          Original Code
 *    03-01-97          Original Code
 *
 *
 */

package gov.nasa.worldwind.geom.coords;

/**
 * Ported to Java from the NGA GeoTrans polarst.c and polarst.h code.
 *
 * @author Garrett Headley - Feb 12, 2007 4:48:11 PM
 * @version $Id: PolarCoordConverter.java 10395 2009-04-22 00:14:01Z patrickmurris $
 */
public class PolarCoordConverter
{
    private static final long POLAR_NO_ERROR = 0x0000;
    private static final long POLAR_LAT_ERROR = 0x0001;
    private static final long POLAR_LON_ERROR = 0x0002;
    private static final long POLAR_ORIGIN_LAT_ERROR = 0x0004;
    private static final long POLAR_ORIGIN_LON_ERROR = 0x0008;
    public static final long POLAR_EASTING_ERROR = 0x0010;
    public static final long POLAR_NORTHING_ERROR = 0x0020;
    private static final long POLAR_A_ERROR = 0x0040;
    private static final long POLAR_INV_F_ERROR = 0x0080;
    public static final long POLAR_RADIUS_ERROR = 0x0100;

    private static final double PI = 3.14159265358979323;
    private static final double PI_OVER_2 = PI / 2.0;
    private static final double PI_Over_4 = PI / 4.0;
    private static final double TWO_PI = 2.0 * PI;

    /* Ellipsoid Parameters, default to WGS 84  */
    private double Polar_a = 6378137.0;                    /* Semi-major axis of ellipsoid in meters  */
    private double Polar_f = 1 / 298.257223563;            /* Flattening of ellipsoid  */
    private double es = 0.08181919084262188000;            /* Eccentricity of ellipsoid    */
    private double es_OVER_2 = .040909595421311;           /* es / 2.0 */
    private double Southern_Hemisphere = 0;                /* Flag variable */
    private double mc = 1.0;
    private double tc = 1.0;
    private double e4 = 1.0033565552493;
    private double Polar_a_mc = 6378137.0;                 /* Polar_a * mc */
    private double two_Polar_a = 12756274.0;               /* 2.0 * Polar_a */

    /* Polar Stereographic projection Parameters */
    private double Polar_Origin_Lat = ((PI * 90) / 180);   /* Latitude of origin in radians */
    private double Polar_Origin_Long = 0.0;                /* Longitude of origin in radians */
    private double Polar_False_Easting = 0.0;              /* False easting in meters */
    private double Polar_False_Northing = 0.0;             /* False northing in meters */

    /* Maximum variance for easting and northing values for WGS 84. */
    private double Polar_Delta_Easting = 12713601.0;
    private double Polar_Delta_Northing = 12713601.0;

    private double Easting;
    private double Northing;
    private double Latitude;
    private double Longitude;

    PolarCoordConverter()
    {
    }

    /**
     * The function setPolarStereographicParameters receives the ellipsoid parameters and Polar Stereograpic projection
     * parameters as inputs, and sets the corresponding state variables.  If any errors occur, error code(s) are
     * returned by the function, otherwise POLAR_NO_ERROR is returned.
     *
     * @param a                        Semi-major axis of ellipsoid, in meters
     * @param f                        Flattening of ellipsoid
     * @param Latitude_of_True_Scale   Latitude of true scale, in radians
     * @param Longitude_Down_from_Pole Longitude down from pole, in radians
     * @param False_Easting            Easting (X) at center of projection, in meters
     * @param False_Northing           Northing (Y) at center of projection, in meters
     * @return error code
     */
    public long setPolarStereographicParameters(double a, double f, double Latitude_of_True_Scale,
                                                       double Longitude_Down_from_Pole, double False_Easting, double False_Northing)

    {
        double es2;
        double slat, clat;
        double essin;
        double one_PLUS_es, one_MINUS_es;
        double pow_es;
        double inv_f = 1 / f;
        final double epsilon = 1.0e-2;
        long Error_Code = POLAR_NO_ERROR;

        if (a <= 0.0)
        { /* Semi-major axis must be greater than zero */
            Error_Code |= POLAR_A_ERROR;
        }
        if ((inv_f < 250) || (inv_f > 350))
        { /* Inverse flattening must be between 250 and 350 */
            Error_Code |= POLAR_INV_F_ERROR;
        }
        if ((Latitude_of_True_Scale < -PI_OVER_2) || (Latitude_of_True_Scale > PI_OVER_2))
        { /* Origin Latitude out of range */
            Error_Code |= POLAR_ORIGIN_LAT_ERROR;
        }
        if ((Longitude_Down_from_Pole < -PI) || (Longitude_Down_from_Pole > TWO_PI))
        { /* Origin Longitude out of range */
            Error_Code |= POLAR_ORIGIN_LON_ERROR;
        }

        if (Error_Code == POLAR_NO_ERROR)
        { /* no errors */

            Polar_a = a;
            two_Polar_a = 2.0 * Polar_a;
            Polar_f = f;

            if (Longitude_Down_from_Pole > PI)
                Longitude_Down_from_Pole -= TWO_PI;
            if (Latitude_of_True_Scale < 0)
            {
                Southern_Hemisphere = 1;
                Polar_Origin_Lat = -Latitude_of_True_Scale;
                Polar_Origin_Long = -Longitude_Down_from_Pole;
            } else
            {
                Southern_Hemisphere = 0;
                Polar_Origin_Lat = Latitude_of_True_Scale;
                Polar_Origin_Long = Longitude_Down_from_Pole;
            }
            Polar_False_Easting = False_Easting;
            Polar_False_Northing = False_Northing;

            es2 = 2 * Polar_f - Polar_f * Polar_f;
            es = Math.sqrt(es2);
            es_OVER_2 = es / 2.0;

            if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10)
            {
                slat = Math.sin(Polar_Origin_Lat);
                essin = es * slat;
                pow_es = Math.pow((1.0 - essin) / (1.0 + essin), es_OVER_2);
                clat = Math.cos(Polar_Origin_Lat);
                mc = clat / Math.sqrt(1.0 - essin * essin);
                Polar_a_mc = Polar_a * mc;
                tc = Math.tan(PI_Over_4 - Polar_Origin_Lat / 2.0) / pow_es;
            } else
            {
                one_PLUS_es = 1.0 + es;
                one_MINUS_es = 1.0 - es;
                e4 = Math.sqrt(Math.pow(one_PLUS_es, one_PLUS_es) * Math.pow(one_MINUS_es, one_MINUS_es));
            }
        }

        /* Calculate Radius */
        convertGeodeticToPolarStereographic(0, Polar_Origin_Long);

        Polar_Delta_Northing = Northing * 2; // Increased range for accepted easting and northing values
        Polar_Delta_Northing = Math.abs(Polar_Delta_Northing) + epsilon;
        Polar_Delta_Easting = Polar_Delta_Northing;

        return (Error_Code);
    }

    /**
     * The function Convert_Geodetic_To_Polar_Stereographic converts geodetic coordinates (latitude and longitude) to
     * Polar Stereographic coordinates (easting and northing), according to the current ellipsoid and Polar
     * Stereographic projection parameters. If any errors occur, error code(s) are returned by the function, otherwise
     * POLAR_NO_ERROR is returned.
     *
     * @param Latitude  latitude, in radians
     * @param Longitude Longitude, in radians
     * @return error code
     */
    public long convertGeodeticToPolarStereographic(double Latitude, double Longitude)
    {
        double dlam;
        double slat;
        double essin;
        double t;
        double rho;
        double pow_es;
        long Error_Code = POLAR_NO_ERROR;

        if ((Latitude < -PI_OVER_2) || (Latitude > PI_OVER_2))
        {   /* Latitude out of range */
            Error_Code |= POLAR_LAT_ERROR;
        }
        if ((Latitude < 0) && (Southern_Hemisphere == 0))
        {   /* Latitude and Origin Latitude in different hemispheres */
            Error_Code |= POLAR_LAT_ERROR;
        }
        if ((Latitude > 0) && (Southern_Hemisphere == 1))
        {   /* Latitude and Origin Latitude in different hemispheres */
            Error_Code |= POLAR_LAT_ERROR;
        }
        if ((Longitude < -PI) || (Longitude > TWO_PI))
        {  /* Longitude out of range */
            Error_Code |= POLAR_LON_ERROR;
        }

        if (Error_Code == POLAR_NO_ERROR)
        {  /* no errors */

            if (Math.abs(Math.abs(Latitude) - PI_OVER_2) < 1.0e-10)
            {
                Easting = 0.0;
                Northing = 0.0;
            } else
            {
                if (Southern_Hemisphere != 0)
                {
                    Longitude *= -1.0;
                    Latitude *= -1.0;
                }
                dlam = Longitude - Polar_Origin_Long;
                if (dlam > PI)
                {
                    dlam -= TWO_PI;
                }
                if (dlam < -PI)
                {
                    dlam += TWO_PI;
                }
                slat = Math.sin(Latitude);
                essin = es * slat;
                pow_es = Math.pow((1.0 - essin) / (1.0 + essin), es_OVER_2);
                t = Math.tan(PI_Over_4 - Latitude / 2.0) / pow_es;

                if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10)
                    rho = Polar_a_mc * t / tc;
                else
                    rho = two_Polar_a * t / e4;

                if (Southern_Hemisphere != 0)
                {
                    Easting = -(rho * Math.sin(dlam) - Polar_False_Easting);
                    //Easting *= -1.0;
                    Northing = rho * Math.cos(dlam) + Polar_False_Northing;
                } else
                    Easting = rho * Math.sin(dlam) + Polar_False_Easting;
                    Northing = -rho * Math.cos(dlam) + Polar_False_Northing;
            }
        }
        return (Error_Code);
    }

    public double getEasting()
    {
        return Easting;
    }

    public double getNorthing()
    {
        return Northing;
    }

    /**
     *  The function Convert_Polar_Stereographic_To_Geodetic converts Polar
     *  Stereographic coordinates (easting and northing) to geodetic
     *  coordinates (latitude and longitude) according to the current ellipsoid
     *  and Polar Stereographic projection Parameters. If any errors occur, the
     *  code(s) are returned by the function, otherwise POLAR_NO_ERROR
     *  is returned.
     *
     *  @param Easting Easting (X), in meters
     *  @param Northing Northing (Y), in meters
     *  @return error code
     */
    public long convertPolarStereographicToGeodetic (double Easting, double Northing)
    {
        double dy = 0, dx = 0;
        double rho = 0;
        double t;
        double PHI, sin_PHI;
        double tempPHI = 0.0;
        double essin;
        double pow_es;
        double delta_radius;
        long Error_Code = POLAR_NO_ERROR;
        double min_easting = Polar_False_Easting - Polar_Delta_Easting;
        double max_easting = Polar_False_Easting + Polar_Delta_Easting;
        double min_northing = Polar_False_Northing - Polar_Delta_Northing;
        double max_northing = Polar_False_Northing + Polar_Delta_Northing;

        if (Easting > max_easting || Easting < min_easting)
        { /* Easting out of range */
            Error_Code |= POLAR_EASTING_ERROR;
        }
        if (Northing > max_northing || Northing < min_northing)
        { /* Northing out of range */
            Error_Code |= POLAR_NORTHING_ERROR;
        }

        if (Error_Code == POLAR_NO_ERROR)
        {
            dy = Northing - Polar_False_Northing;
            dx = Easting - Polar_False_Easting;

            /* Radius of point with origin of false easting, false northing */
            rho = Math.sqrt(dx * dx + dy * dy);

            delta_radius = Math.sqrt(Polar_Delta_Easting * Polar_Delta_Easting + Polar_Delta_Northing * Polar_Delta_Northing);

            if(rho > delta_radius)
            { /* Point is outside of projection area */
                Error_Code |= POLAR_RADIUS_ERROR;
            }
        }

        if (Error_Code == POLAR_NO_ERROR)
        { /* no errors */
            if ((dy == 0.0) && (dx == 0.0))
            {
                Latitude = PI_OVER_2;
                Longitude = Polar_Origin_Long;

            }
            else
            {
                if (Southern_Hemisphere != 0)
                {
                    dy *= -1.0;
                    dx *= -1.0;
                }

                if (Math.abs(Math.abs(Polar_Origin_Lat) - PI_OVER_2) > 1.0e-10)
                    t = rho * tc / (Polar_a_mc);
                else
                    t = rho * e4 / (two_Polar_a);
                PHI = PI_OVER_2 - 2.0 * Math.atan(t);
                while (Math.abs(PHI - tempPHI) > 1.0e-10)
                {
                    tempPHI = PHI;
                    sin_PHI = Math.sin(PHI);
                    essin =  es * sin_PHI;
                    pow_es = Math.pow((1.0 - essin) / (1.0 + essin), es_OVER_2);
                    PHI = PI_OVER_2 - 2.0 * Math.atan(t * pow_es);
                }
                Latitude = PHI;
                Longitude = Polar_Origin_Long + Math.atan2(dx, -dy);

                if (Longitude > PI)
                    Longitude -= TWO_PI;
                else if (Longitude < -PI)
                    Longitude += TWO_PI;

                if (Latitude > PI_OVER_2)  /* force distorted values to 90, -90 degrees */
                    Latitude = PI_OVER_2;
                else if (Latitude < -PI_OVER_2)
                    Latitude = -PI_OVER_2;

                if (Longitude > PI)  /* force distorted values to 180, -180 degrees */
                    Longitude = PI;
                else if (Longitude < -PI)
                    Longitude = -PI;

            }
            if (Southern_Hemisphere != 0)
            {
                Latitude *= -1.0;
                Longitude *= -1.0;
            }

        }
        return (Error_Code);
    }

    /**
     * @return Latitude in radians.
     */
    public double getLatitude()
    {
        return Latitude;
    }

    /**
     * @return Longitude in radians.
     */
    public double getLongitude()
    {
        return Longitude;
    }

}


text:
package mystem_wrapper

import (
	"bytes"
	"encoding/json"
	"fmt"
	"os/exec"
	"strings"
)

type MyStem struct {
	path string
	args []string

	InputCharFilter *strings.Replacer
}

type Word struct {
	Analysis []struct {
		Lex      string   `json:"lex"`
		Grammeme Grammeme `json:"gr"`
	} `json:"analysis"`
	Text string `json:"text"`
}

func New(path string, args []string) *MyStem {
	m := &MyStem{}
	m.path = path
	m.args = args

	// append c flag
	m.args = append(m.args, "-c", "--format", "json")

	// make replacer
	m.InputCharFilter = strings.NewReplacer(
		"«", "'",
		"»", "'",
		"—", "-",
		"_", "-",
		"\r\n", " ",
		"\r", " ",
		"\n", " ",
		"\t", " ",
	)

	return m
}

func (m *MyStem) Transform(inputTexts []string) (transformedTexts []string, err error) {
	sentences, err := m.Sentences(inputTexts)
	if err != nil {
		return
	}

	for _, sentence := range sentences {
		sentenceText := ""
		for _, word := range sentence {
			if len(word.Analysis) != 0 {
				sentenceText = fmt.Sprintf("%s%s", sentenceText, word.Analysis[0].Lex)
			} else {
				sentenceText = fmt.Sprintf("%s%s", sentenceText, word.Text)
			}
		}

		transformedTexts = append(transformedTexts, sentenceText)
	}
	return
}

func (m *MyStem) Sentences(inputTexts []string) ([][]Word, error) {
	var inputBuffer, outBuffer bytes.Buffer

	for i := range inputTexts {
		// filter bad chars
		text := strings.TrimSpace(m.InputCharFilter.Replace(inputTexts[i]))
		if text == "" {
			text = " "
		}

		// one text = one line
		if i == len(inputTexts)-1 {
			inputBuffer.Write([]byte(text))
		} else {
			inputBuffer.Write(append([]byte(text), '\n'))
		}
	}

	// run proc
	proc := exec.Command(m.path, m.args...)
	proc.Stdin = &inputBuffer
	proc.Stdout = &outBuffer
	err := proc.Start()
	if err != nil {
		return nil, fmt.Errorf("error running mystem: %s", err)
	}
	proc.Wait()
	if err != nil {
		return nil, fmt.Errorf("error waiting mystem: %s", err)
	}

	// parse output
	outByteTexts := bytes.Split(outBuffer.Bytes(), []byte("\n"))
	// remove always empty last string from mystem's output
	outByteTexts = outByteTexts[0 : len(outByteTexts)-1]
	if len(outByteTexts) != len(inputTexts) {
		return nil, fmt.Errorf("error: len(inputTexts)(%d) != len(outByteTexts)(%d) res: %s",
			len(inputTexts),
			len(outByteTexts),
			outBuffer.Bytes(),
		)
	}

	//parse every word into sentences
	var result [][]Word
	for i := range outByteTexts {
		var (
			words         []Word
			filteredWords []Word
		)

		err := json.Unmarshal(outByteTexts[i], &words)
		if err != nil {
			return nil, fmt.Errorf("error while decoding json: %s res: %s",
				err,
				outByteTexts[i],
			)
		}

		for wi := range words {
			if words[wi].Text == "\n" {
				continue
			}

			filteredWords = append(filteredWords, words[wi])
		}

		result = append(result, filteredWords)
	}

	return result, nil
}