text:
class SigninClient;
class TokenWebData;

class MutableProfileOAuth2TokenServiceDelegate
    : public ProfileOAuth2TokenServiceDelegate,
      public WebDataServiceConsumer,
      public network::NetworkConnectionTracker::NetworkConnectionObserver {
 public:
  using FixRequestErrorCallback = base::RepeatingCallback<bool()>;

  MutableProfileOAuth2TokenServiceDelegate(
      SigninClient* client,
      AccountTrackerService* account_tracker_service,
      network::NetworkConnectionTracker* network_connection_tracker,
      scoped_refptr<TokenWebData> token_web_data,
      signin::AccountConsistencyMethod account_consistency,
      bool revoke_all_tokens_on_load,
      FixRequestErrorCallback fix_request_error_callback);

  MutableProfileOAuth2TokenServiceDelegate(
      const MutableProfileOAuth2TokenServiceDelegate&) = delete;
  MutableProfileOAuth2TokenServiceDelegate& operator=(
      const MutableProfileOAuth2TokenServiceDelegate&) = delete;

  ~MutableProfileOAuth2TokenServiceDelegate() override;

  // Overridden from ProfileOAuth2TokenServiceDelegate.
  std::unique_ptr<OAuth2AccessTokenFetcher> CreateAccessTokenFetcher(
      const CoreAccountId& account_id,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      OAuth2AccessTokenConsumer* consumer) override;

  std::string GetTokenForMultilogin(
      const CoreAccountId& account_id) const override;
  bool RefreshTokenIsAvailable(const CoreAccountId& account_id) const override;
  std::vector<CoreAccountId> GetAccounts() const override;
  scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory()
      const override;
  void LoadCredentials(const CoreAccountId& primary_account_id,
                       bool is_syncing) override;
  void UpdateCredentials(const CoreAccountId& account_id,
                         const std::string& refresh_token) override;
  void RevokeAllCredentials() override;
  void RevokeCredentials(const CoreAccountId& account_id) override;
  void ExtractCredentials(ProfileOAuth2TokenService* to_service,
                          const CoreAccountId& account_id) override;
  void Shutdown() override;

  // Overridden from NetworkConnectionTracker::NetworkConnectionObserver.
  void OnConnectionChanged(network::mojom::ConnectionType type) override;

  bool FixRequestErrorIfPossible() override;

  // Returns the account's refresh token used for testing purposes.
  std::string GetRefreshTokenForTest(const CoreAccountId& account_id) const;

 private:
  friend class MutableProfileOAuth2TokenServiceDelegateTest;

  class RevokeServerRefreshToken;

  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           PersistenceDBUpgrade);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           FetchPersistentError);
  FRIEND_TEST_ALL_PREFIXES(
      MutableProfileOAuth2TokenServiceDelegateTest,
      PersistenceLoadCredentialsEmptyPrimaryAccountId_DiceEnabled);
  FRIEND_TEST_ALL_PREFIXES(
      MutableProfileOAuth2TokenServiceDelegateTest,
      LoadCredentialsClearsTokenDBWhenNoPrimaryAccount_DiceDisabled);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           RevokeAllCredentialsDuringLoad);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           PersistenceLoadCredentials);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           RevokeOnUpdate);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           DelayedRevoke);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           DiceMigrationWithMissingHostedDomain);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           DiceMigrationHostedDomainPrimaryAccount);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           ShutdownDuringRevoke);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           RevokeRetries);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           UpdateInvalidToken);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           LoadInvalidToken);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           GetAccounts);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           CanonicalizeAccountId);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           CanonAndNonCanonAccountId);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           ShutdownService);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           ClearTokensOnStartup);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           InvalidateTokensForMultilogin);
  FRIEND_TEST_ALL_PREFIXES(MutableProfileOAuth2TokenServiceDelegateTest,
                           ExtractCredentials);

  // WebDataServiceConsumer implementation:
  void OnWebDataServiceRequestDone(
      WebDataServiceBase::Handle handle,
      std::unique_ptr<WDTypedResult> result) override;

  // Loads credentials into in memory stucture.
  void LoadAllCredentialsIntoMemory(
      const std::map<std::string, std::string>& db_tokens);

  // Updates the in-memory representation of the credentials.
  void UpdateCredentialsInMemory(const CoreAccountId& account_id,
                                 const std::string& refresh_token);

  // Sets refresh token in error.
  void InvalidateTokenForMultilogin(
      const CoreAccountId& failed_account) override;

  // Persists credentials for |account_id|. Enables overriding for
  // testing purposes, or other cases, when accessing the DB is not desired.
  void PersistCredentials(const CoreAccountId& account_id,
                          const std::string& refresh_token);

  // Clears credentials persisted for |account_id|. Enables overriding for
  // testing purposes, or other cases, when accessing the DB is not desired.
  void ClearPersistedCredentials(const CoreAccountId& account_id);

  // Revokes the refresh token on the server.
  void RevokeCredentialsOnServer(const std::string& refresh_token);

  // Cancels any outstanding fetch for tokens from the web database.
  void CancelWebTokenFetch();

  std::string GetRefreshToken(const CoreAccountId& account_id) const;

  // Creates a new AccountStatus and adds it to the AccountStatusMap.
  // The account must not be already in the map.
  void AddAccountStatus(const CoreAccountId& account_id,
                        const std::string& refresh_token,
                        const GoogleServiceAuthError& error);

  // Called at when tokens are loaded. Performs housekeeping tasks and notifies
  // the observers.
  void FinishLoadingCredentials();

  // Deletes the credential locally and notifies observers through
  // OnRefreshTokenRevoked(). If |revoke_on_server| is true, the token is also
  // revoked on the server.
  void RevokeCredentialsImpl(const CoreAccountId& account_id,
                             bool revoke_on_server);

  // In memory refresh token store mapping account_id to refresh_token.
  std::map<CoreAccountId, std::string> refresh_tokens_;

  // Handle to the request reading tokens from database.
  WebDataServiceBase::Handle web_data_service_request_;

  // The primary account id of this service's profile during the loading of
  // credentials.  This member is empty otherwise.
  CoreAccountId loading_primary_account_id_;

  std::vector<std::unique_ptr<RevokeServerRefreshToken>> server_revokes_;

  // Used to verify that certain methods are called only on the thread on which
  // this instance was created.
  THREAD_CHECKER(thread_checker_);

  raw_ptr<SigninClient> client_;
  raw_ptr<AccountTrackerService> account_tracker_service_;
  raw_ptr<network::NetworkConnectionTracker> network_connection_tracker_;
  scoped_refptr<TokenWebData> token_web_data_;
  signin::AccountConsistencyMethod account_consistency_;

  // Revokes all the tokens after loading them. Secondary accounts will be
  // completely removed, and the primary account will be kept in authentication
  // error state.
  bool revoke_all_tokens_on_load_;

  // Callback function that attempts to correct request errors.  Best effort
  // only.  Returns true if the error was fixed and retry should be reattempted.
  FixRequestErrorCallback fix_request_error_callback_;
};

#endif  // COMPONENTS_SIGNIN_INTERNAL_IDENTITY_MANAGER_MUTABLE_PROFILE_OAUTH2_TOKEN_SERVICE_DELEGATE_H_


text:
Divvy Data Challenge
====================

This repository contains my entry to the Divvy [Data Challenge](https://divvybikes.com/datachallenge). As a Divvy member and civic data enthusiast, I enjoyed digging into the dataset. My entry is an interactive map that shows trip statistics at the station-level upon hovering over a station.

Visualization
-------------

I constructed the visualization using [D3.js](http://d3js.org/) for the interactive charts and [MapBox](https://www.mapbox.com/tour/) for the map tiles. Station-level statistics are grouped by the `from_station_name`. In my exploration, I found that most stations averaged an equal number of inbound trips and outbound trips, though the pattern is time-of-day specific in many stations as you can see by hovering over a station located near a commuter rail terminal such as Union Station.

Analysis
--------

Analysis and preparation of the data was completed using Python and the [pandas](http://pandas.pydata.org/) library. In the notebooks directory of this repository, you'll find several IPython [notebooks](http://ipython.org/notebook) that show the code used to generate the CSV files used in the visualization and some of the observations below. To use the IPython notebooks, download this repository and a copy of the Divvy [data](https://divvybikes.com/datachallenge) which is larger than the recommended filesize on GitHub. Place unzipped Divvy directory into the data directory, and then launch an IPython notebook instance from inside the notebooks directory.

Observations
------------

In my exploration of the dataset, I discovered some interesting facts about how people are using the system.

* Total Trips: 760,000 or more than 4,000 per day
* Median Subscriber Age: 33 years
* Median Estimated Trip Distance: 1.4 miles, I used the Manhattan Distance function to approximate distance between two points
* Longest trip: 19 miles, from Lincoln and Eastwood to 55th and Shore Dr in an impressive 41 minutes
* Trip Duration 75th percentile: 22.5 minutes, well under the 30 minute time limit

Next
----

I've only scratched the surface of this extremely rich dataset. I'd love to spend more time working with it or discuss further, send me a message or submit a pull request if you have any other ideas or want to contribute.

redpajama_set_name: RedPajamaGithub


text:
from django.db import models

from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext_noop

from oscar.core.compat import AUTH_USER_MODEL
from document_manager.models import Document
from django.contrib.staticfiles.templatetags.staticfiles import static
# Create your models here.

class CustomerDocument(Document):

	user = models.ForeignKey(
		AUTH_USER_MODEL,
		on_delete=models.CASCADE,
	)

class CustomerProfile(models.Model):

	# Las opciones que describen el estado del perfil
	DEFAULT_AVATAR = static('img/default-avatar.jpg')
	MALE = 'M'
	FEMALE = 'F'
	OTHER = ''
	GENDER_CHOICES = (
		(MALE, ugettext_noop('Male')),
		(FEMALE, ugettext_noop('Female')),
		(OTHER, ugettext_noop('Other'))
	)
	APPRENTICE = 0
	CANDIDATE = 1
	MENTOR = 2
	PROFILE_STATUS_CHOICES = (
		(APPRENTICE, ugettext_noop('Apprentice')),
		(CANDIDATE, ugettext_noop('Mentor Candidate')),
		(MENTOR, ugettext_noop('Mentor'))
	)

	INCOMPLETE = 0
	COMPLETE = 1

	VALIDATION_STATUS_CHOICES = (
		(INCOMPLETE, ugettext_noop('Incomplete')),
		(COMPLETE, ugettext_noop('Complete')),
	)

	user = models.OneToOneField(
		AUTH_USER_MODEL,
		unique=True,
		db_index=True,
		null= False,
		related_name='customer_profile',
		verbose_name=_("Users"),
		help_text='Relacionar los datos del perfil con el usuario'
	)

	avatar = models.CharField(max_length=250, blank=True, help_text="Avatar")

	birth_date = models.DateField(blank=True, null=True, help_text='Fecha de nacimietno')

	status = models.IntegerField(
		null=False, default=APPRENTICE,
		choices=PROFILE_STATUS_CHOICES,
		help_text='Estado del perfíl de usuario'
	)

	validation_status = models.IntegerField(
		null=False, default=INCOMPLETE,
		choices=VALIDATION_STATUS_CHOICES,
		help_text='Estado de datos de perfil'
	)
	gender = models.CharField(
		blank=True,help_text="Genero", choices=GENDER_CHOICES, max_length=1, default=OTHER
	)

	about_me = models.CharField(max_length=250, blank=True,
									help_text="Acerca del mentor, pequeña description")

	phone = models.CharField(max_length=75, blank=True,
							 help_text='Teléfono de contacto')

	occupation = models.CharField(max_length=100, blank=True,
								  help_text='Ocupación del mentor, profesión u oficio')
	educational_name = models.CharField(max_length=100, blank=True,
										help_text='Nombre de la institución educativa del mentor')
	work_name = models.CharField(max_length=250, blank=True,
								 help_text='Nombre del llugar de trabajo')

	emergency_contact_name = models.CharField(max_length=250, blank=True,
											  help_text='Nombre de contacto en caso de emergencia')
	emergency_contact_email = models.CharField(max_length=250, blank=True,
											   help_text='Correo del contacto en caso de emergencia')
	emergency_contact_relationship = models.CharField(max_length=250, blank=True,
													  help_text='Relación con el contacto en caso de emergencia')
	emergency_contact_phone = models.CharField(max_length=250, blank=True,
											   help_text='Teléfono del contacto en caso de emergencia')

	country_name = models.CharField(max_length=250, blank=True,
									help_text='Nombre del país residencia del mentor')
	state_name = models.CharField(max_length=250, blank=True,
								  help_text='Estado de residencia del mentor')
	address_field_one = models.CharField(max_length=250, blank=True,
										 help_text='Campo para datos de dirección')
	address_field_two = models.CharField(max_length=250, blank=True,
										 help_text='Campo para datos de dirección extendido')
	postal_code = models.CharField(max_length=250, blank=True,
								   help_text='Código postal de residencia del mentor')
	outdoor_number = models.CharField(max_length=250, blank=True,
									  help_text='Número exterior de residencia del mentor')
	internal_number = models.CharField(max_length=250, blank=True,
									   help_text='Número interior de residencia del mentor')

	location_latitude = models.DecimalField(max_digits=18, decimal_places=10, null=True,
											help_text='Almacena la latitud en la ubicación del mentor')
	location_longitude = models.DecimalField(max_digits=18, decimal_places=10, null=True,
											 help_text='Almacena la longitud en la ubicación del mentor')

	created_at = models.DateTimeField(default=timezone.now,
									  help_text='Fecha de creación del registro')
	modified_at = models.DateTimeField(default=timezone.now,
									   help_text='Fecha de actualización del registro')

	@property
	def is_aprentice(self):
		return int(self.status) == self.APPRENTICE

	@property
	def is_active_mentor(self):

		return True if int(self.status) == self.MENTOR else False

	@property
	def is_candidate(self):

		return int(self.status) == self.CANDIDATE

	@property
	def is_mentor(self):
		return int(self.status) > self.APPRENTICE

	def get_user_status(self):
		return self.PROFILE_STATUS_CHOICES[self.status]

	@property
	def is_profile_complete(self):
		return True if int(self.validation_status) == self.COMPLETE else False

	@property
	def get_avatar(self):
		return self.DEFAULT_AVATAR if not self.avatar else self.avatar

from oscar.apps.customer.models import *


text:
//The MIT License (MIT) Copyright (c) <2013> <Jonathan Salvador>
//
//Permission is hereby granted, free of charge, to any person obtaining a
//copy of this software and associated documentation files (the
//"Software"), to deal in the Software without restriction, including
//without limitation the rights to use, copy, modify, merge, publish,
//distribute, sublicense, and/or sell copies of the Software, and to
//permit persons to whom the Software is furnished to do so, subject to
//the following conditions:
//
//The above copyright notice and this permission notice shall be included
//in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//  FlipClockView.m
//  FlipClock
//
//  Created by Jonathan Salvador on 11/25/12.
//  Copyright (c) 2012 Jonathan Salvador. All rights reserved.
//

#import "FlipClockView.h"
#import "DigitFont.h"
#import "Constants.h"
#import "ServicesProvider.h"
#import "VersionUtil.h"

@implementation FlipClockView

//static NSString *moduleName;
static NSString * const moduleName = @"com.Goondaba.FlipClock";
static NSString * const isMilitary_str  = @"isMilitary";
static NSString * const hasSeconds_str  = @"hasSeconds";
static NSString * const font_str        = @"selectedFont";
CGFloat frameRate = 30.0f;

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview{

    self = [super initWithFrame:frame isPreview:isPreview];
    if (self) {
        [self setAnimationTimeInterval:(1.0/frameRate)];

        // Register our default values
        [[self getDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
                                    @"NO", isMilitary_str,
                                    @"YES", hasSeconds_str,
                                    @(kDigitFontTypeHelveticaRegular), font_str,
                                    nil]];
    }
    return self;
}

- (void)startAnimation{
    [super startAnimation];

    //Deal with prefs
    ScreenSaverDefaults *defaults = [self getDefaults];

    //create the quartz composition view
    myClockView = [[ClockView alloc] initWithFrame: NSMakeRect(0, 0, NSWidth(self.frame), NSHeight(self.frame))];
    //make sure it resizes with the screensaver view
    [myClockView setAutoresizingMask:(NSViewWidthSizable|NSViewHeightSizable)];

    [self addSubview:myClockView];

    [myClockView drawClockWithMilitary:[defaults integerForKey:isMilitary_str]
                            andSeconds:[defaults integerForKey:hasSeconds_str]
                           andFontType:[defaults integerForKey:font_str]
                             isPreview:self.isPreview];
}

- (void)stopAnimation{
    [super stopAnimation];

    //
    if(myClockView != nil){
        [myClockView removeFromSuperview];
        myClockView = nil;
    }
}

- (void)drawRect:(NSRect)rect
{
    [super drawRect:rect];
}

- (void)animateOneFrame
{
    return;
}

- (BOOL)hasConfigureSheet{
    return YES;
}

- (NSWindow*)configureSheet{

    ScreenSaverDefaults *defaults = [self getDefaults];

    if (!configSheet)
    {
        if (![NSBundle loadNibNamed:@"ConfigureSheet" owner:self])
        {
            NSLog( @"Failed to load configure sheet." );
            NSBeep();
        }
    }

    currentVersionField.cell.title = [NSString stringWithFormat:@"v%@", [VersionUtil currentVersion]];
    updateButton.hidden = ([[ServicesProvider instance].feedService latestVersion] == nil);

    //set sheet options to defaults
    [militaryBox setState:[defaults integerForKey:isMilitary_str]];
    [secondsBox  setState:[defaults integerForKey:hasSeconds_str]];

    NSMutableArray *listOfFonts = [NSMutableArray new];
    for (NSInteger i=0; i < kDigitFontTypeCount; i++) {
        [listOfFonts addObject:[DigitFont fontNameForType:i]];
    }

    [fontPopUp removeAllItems];
    [fontPopUp addItemsWithTitles:listOfFonts];
    [fontPopUp selectItemAtIndex:[defaults integerForKey:font_str]];

    return configSheet;
}

#pragma mark -- Methods for ConfigureSheet

/**
 *  Helper method to grab some default settings
 *
 *  @return The defaults
 */
- (ScreenSaverDefaults*)getDefaults{
    return [ScreenSaverDefaults defaultsForModuleWithName:moduleName];
}

/**
 *  Saves the settings when the cancel button is clicked
 *
 *  @param sender The cancel button
 */
- (IBAction)cancelClick:(id)sender{

    ScreenSaverDefaults *defaults = [self getDefaults];

    // Update our defaults
    [defaults setInteger:[militaryBox state]   forKey:isMilitary_str];
    [defaults setInteger:[secondsBox state]    forKey:hasSeconds_str];
    [defaults setInteger:[fontPopUp indexOfSelectedItem]    forKey:font_str];

    // Save the settings to disk
    [defaults synchronize];

    // Close the sheet
    [[NSApplication sharedApplication] endSheet:configSheet];
}

-(IBAction)openGithubTapped:(id)sender {

    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:kGithubURLString]];
}

@end


text:
<?php

namespace DrakeES;

class RobotsTxt
{

    private $userAgent;
    private $robotsTxt;
    private $parsed;

    /*
        Sets short name of user agent, e.g. "Googlebot".
        This will be non-case-sensitively matched against any "User-agent" record
        the value of which starts with the name, e.g. the values "googlebot" and "gOOglebot@^%$&#^"
        will both match against the name "Googlebot"
        but "mygooglebot" will not.
    */
    public function setUserAgent($userAgent)
    {
        $this->updateInputData('userAgent', $userAgent);
    }

    /*
        Sets the content of robots.txt to be parsed.
    */
    public function setRobotsTxt($robotsTxt)
    {
        $this->updateInputData('robotsTxt', $robotsTxt);
    }

    /*
        Tells whether or not the given $path is allowed to be crawled.
        Returns FALSE if not allowed;
        If allowed and Crawl-delay is set, returns Crawl-delay (integer number).
        If allowed and Crawl-delay is not set, returns TRUE.
    */
    public function isAllowed($path = '/')
    {
        $parsed = $this->getParsed();
        foreach ($parsed['disallow'] as $disallow) {
            $disallow = preg_quote($disallow, '/');
            $last = substr($disallow, -1);
            if ($last !== '*' && $last !== '$') {
                $disallow .= '*';
            }
            $disallow = str_replace(array('\*', '\$'), array('*', '$'), $disallow);
            $disallow = str_replace('*', '(.*)?', $disallow);
            if (preg_match('/^' . $disallow . '/i', $path)) {
                return false;
            }
        }
        return $parsed['delay'] ? $parsed['delay'] : true;
    }

    private function updateInputData($name, $value)
    {
        if ($this->$name === $value) {
            // Already there - nothing to update;
            return;
        }
        $this->$name = $value;
        // Flush the parsed data (if any) so that it is parsed again with the new data when required
        $this->parsed = null;
    }

    private function getParsed()
    {
        if ($this->parsed === null) {
            $this->parse();
        }
        return $this->parsed;
    }

    private function parse()
    {
        $isCatchAll = false;
        $userAgentMatch = false;
        $rules = [
                'disallow' => [],
                'delay' => 0
            ];
        $rules = [
            'catchAll' => $rules,
            'userAgentMatch' => $rules
        ];
        $readingRules = false;
        $stackKey = null;
        // Split robots.txt in lines and walk it line by line:
        foreach (preg_split('/$\R?^/m', $this->robotsTxt) as $line) {
            if (preg_match("/^User\-agent:\s*([^#\s]+)/", $line, $m)) {
                if ($readingRules) {
                    if ($userAgentMatch) {
                        // We've parsed what interests us already and
                        // currently must be in a completely unrelevant group.
                        // Quit the loop.
                        break;
                    } else {
                        $readingRules = false;
                    }
                }
                if (
                        !($isCatchAll = ($m[1] === '*'))
                            &&
                        !$userAgentMatch
                            &&
                        stripos($m[1], $this->userAgent) === 0
                    ) {
                    $userAgentMatch = true;
                    $stackKey = 'userAgentMatch';
                }
            }
            if (!$userAgentMatch && !$isCatchAll) {
                continue; // nothing of our current interest in the current line
            } elseif ($stackKey === null) {
                $stackKey = 'catchAll';
            }
            if (preg_match("/^disallow:\s*([^#\s]+)/i", $line, $m)) {
                $rules[$stackKey]['disallow'][] = $m[1];
                $readingRules = true;
            } elseif (preg_match("/^crawl\-delay:\s*(\d+)/i", $line, $m)) {
                $rules[$stackKey]['delay'] = (int)$m[1];
                $readingRules = true;
            }
        }
        $this->parsed = $userAgentMatch ? $rules['userAgentMatch'] : $rules['catchAll'];
    }

}


text:
""" Extract features in time domain like simple amplitudes, signal differentiation or polynomial fit """

import numpy
import warnings
import logging
from pySPACE.missions.nodes.base_node import BaseNode
from pySPACE.missions.nodes.decorators import BooleanParameter, NoOptimizationParameter, NormalParameter, \
    QNormalParameter, ChoiceParameter, QUniformParameter
from pySPACE.resources.data_types.feature_vector import FeatureVector

@BooleanParameter("absolute")
class TimeDomainFeaturesNode(BaseNode):
    """ Use the samples of the time series as features

    This node uses the values of the channels at certain points of time
    within the window directly as features.

    **Parameters**

        :datapoints:
            The indices of the data points that are used as features. If None,
            all data points are used.

            (*optional, default: None*)

        :absolute:
            If True, the absolute value of each amplitude value is used.
            Recommended for classification using only the EMG signal.

            (*optional, default: False*)

    **Exemplary Call**

    .. code-block:: yaml

        -
            node : Time_Domain_Features
            parameters :
                datapoints : [-4,-3,-2,-1] # means last 4 samples

    :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de)
    :Created: 2008/08/26
    :Revised: 2009/07/16
    """
    def __init__(self,
                 datapoints = None,
                 absolute = False,
                 **kwargs):
        super(TimeDomainFeaturesNode, self).__init__(**kwargs)

        self.set_permanent_attributes(datapoints=datapoints,
                                      absolute=absolute,
                                      feature_names=[])

    def _execute(self, x):
        """ Extract the TD features from the given data x """
        y = x.view(numpy.ndarray)
        if self.datapoints == "None":
            self.datapoints = None
        if self.datapoints is None or self.datapoints == 0:
            self.datapoints = range(y.shape[0])
        # Mapping from data point index to relative time to onset
        def indexToTime(index):
            if index >= 0:
                return float(index) / x.sampling_frequency
            else:
                return (x.shape[0] + float(index)) / x.sampling_frequency
        # We project onto the data points that should be used as features
        y = y[self.datapoints,:]
        if self.absolute:
            y = numpy.fabs(y)
        y = y.T
        # Use all remaining values as features
        features = y.reshape((1, y.shape[0] * y.shape[1]))
        # If not already done, we determine the name of the features
        if self.feature_names == []:
            for channel_name in x.channel_names:
                for index in self.datapoints:
                    self.feature_names.append("TD_%s_%.3fsec" %
                                                    (channel_name,
                                                     indexToTime(index)))
        # Create and return the feature vector
        feature_vector = \
            FeatureVector(numpy.atleast_2d(features).astype(numpy.float64),
                          self.feature_names)
        return feature_vector

@NoOptimizationParameter("absolute")
class CustomChannelWiseFeatureNode(TimeDomainFeaturesNode):
    """ Use the result of a transformation of the time series as features.

    This node applies a given transformation to the data of each individual
    data channel. The result is consequently used as features.

    **Parameters**

        :feature_function:
            A string that defines the transformation of the univariate time
            series. This string will be evaluated in a
            ``eval('lambda x:' + feature_function)``
            statement. Therefore, ``'x'`` has to be used as placeholder for the
            input data. The output has to be array-like, dimensions do not
            matter. Note that numpy can directly be used. To use other external
            libraries, use, e.g., the following syntax:
            ``"__import__('statsmodels.tsa.api').tsa.api.AR(x).fit(maxlag=3).params[1:]"``

    **Note**

        The *datapoints* parameter provided by the TimeDomainFeaturesNode can
        also be used here. The *absolute* parameter, however, is not supported.
        If the absolute value shall be computed, this can be done in the
        *feature_function*.

    **Exemplary Call**

    .. code-block:: yaml

        -
            node : Custom_Features
            parameters :
                feature_function : "numpy.dot(x,x)"

    :Author: David Feess (david.feess@dfki.de)
    :Created: 2012/07/29
    """
    def __init__(self, feature_function, **kwargs):
        super(CustomChannelWiseFeatureNode, self).__init__(**kwargs)

        if 'absolute' in kwargs.keys():
            warnings.warn("Custom_Features does not support 'absolute'!")

        ### Place to define abbreviations. The feature_function strings are
        ### matched with some patterns (using regexp) and then replaced by the
        ### actual string that describes the functions. Add your stuff here!
        import re
        # check if an abbreviation is used:
        # AR[p]:
        if re.match("AR\[([1-9])+\]",feature_function)!=None:
            p = feature_function.strip('AR[]')
            feature_function = "__import__('statsmodels.tsa.api').tsa.api.AR(x).fit(maxlag="+p+").params[1:]"
        # ARMA[p,q]: (note that ARMA is extremely slow)
        if re.match("ARMA\[([1-9])+,([1-9])+\]",feature_function)!=None:
            (p,q) = feature_function.strip('ARMA[]').split(',')
            feature_function = "__import__('statsmodels.tsa.api').tsa.api.ARMA(x).fit(order=("+p+","+q+")).params[1:]"

        self.set_permanent_attributes(feature_function = feature_function, #str
                                      feat_func = None) # the actual function

    def _execute(self, x):
        """ Extract the TD features from the given data x """
        y=x.view(numpy.ndarray)
        if self.datapoints == "None":
            self.datapoints = None
        if self.datapoints == None or self.datapoints == 0:
            self.datapoints = range(y.shape[0])
        # We project onto the data points that should be used as features
        y = y[self.datapoints,:]

        # generate feat_func from string representation if not done yet
        if self.feat_func == None:
            self.feat_func = eval("lambda x: numpy.atleast_1d(" +
                                                self.feature_function +
                                                                ").flatten()")

        # initialize 2D array for transformation results
        nr_feats_per_channel = len(self.feat_func(y[:,0]))
        res = numpy.zeros((nr_feats_per_channel,y.shape[1]))

        # eval fet_func for each channel
        for curr_chan in range(y.shape[1]):
            try:
                res[:,curr_chan] = self.feat_func(y[:,curr_chan])
            except: # pass zeros as features
                res[:,curr_chan] = numpy.zeros_like(res[:,curr_chan])
                warnings.warn("Feature Function failed or delivered wrong " +
                              "dimensions for channel %s in window: %s. "
                               % (x.channel_names[curr_chan],x.tag) +
                               "Wrote zeros in the feature vector instead.")

        # flatten, such that feats from one channel stay grouped together
        features = res.flatten('F')

        # Feature names
        if self.feature_names == []:
            for channel_name in x.channel_names:
                for i in range(nr_feats_per_channel):
                    self.feature_names.append("CustomFeature1_%s_%d" %
                                                            (channel_name, i))

        # Create and return the feature vector
        feature_vector = \
            FeatureVector(numpy.atleast_2d(features).astype(numpy.float64),
                          self.feature_names)
        return feature_vector

# TODO: These two nodes need memory optimization ...
class TimeDomainDifferenceFeatureNode(BaseNode):
    """ Use differences between channels and/or times as features.

    This node uses differences between channels (Inter_Channel) at the same
    time and between different times (Intra_Channel) on the same channel as
    features.

    **Parameters**

        :datapoints:
            The indices of the data points that are used. If None, all
            data points are used.

            (*Optional, default: None*)

        :moving_window_length:
            If this parameter is greater than one, then not the data point x[i]
            is used but the average of the k=*moving_window_length* elements
            around x[i], i.e. avg([x[i-k/2],...,x[i+k/2]).

            (*Optional, default: 1*)

    **Known issues**
        In the current version this produces to much data, even just for one
        choice.

    **Exemplary Call**

    .. code-block:: yaml

        -
            node : Time_Domain_Difference_Features
            parameters :
                datapoints : None
                moving_window_length : 1

    :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de)
    :Created: 2008/08/26
    :Revised: 2009/07/16
    """
    def __init__(self,
                datapoints = None,
                moving_window_length = 1,
                **kwargs):
        super(TimeDomainDifferenceFeatureNode, self).__init__(**kwargs)

        self.set_permanent_attributes(datapoints = datapoints,
                            moving_window_length = moving_window_length,
                                   feature_names = []) #bug: should be feature_names

    def _execute(self, x):
        """
        Extract the TD features from the given data x
        """
        #TODO: Shorten maybe this code
        if self.datapoints == "None":
            self.datapoints = None
        if self.datapoints == None:
            self.datapoints = range(x.shape[0])
        y=x.view(numpy.ndarray)
        #From each selected channel we extract the specified datapoints
        indices = []
        for datapoint in self.datapoints:
            indices.append(range(max(0, datapoint - \
               self.moving_window_length / 2), min(x.shape[0], datapoint + \
               (self.moving_window_length + 1) / 2)))

        channel_features = dict()
        for channel_name in x.channel_names:
            channel_index = x.channel_names.index(channel_name)
            for number, index_range in enumerate(indices):
                channel_features[(channel_name, number)] = \
                                  numpy.mean(y[index_range, channel_index])

        # Mapping from datapoint index to relative time to onset
        def indexToTime(index):
            if index >= 0:
                return float(index) / x.sampling_frequency
            else:
                return (x.end_time - x.start_time)/ 1000.0 \
                           + float(index) / x.sampling_frequency

        features = []
        for channel1, number1 in  channel_features.iterkeys():
            for channel2, number2 in  channel_features.iterkeys():
                if channel1 == channel2 and number1 > number2:
                    features.append(channel_features[(channel1, number1)] - \
                                        channel_features[(channel2, number2)])
                elif number1 == number2 and channel1 != channel2:
                    features.append(channel_features[(channel1, number1)] - \
                                        channel_features[(channel2, number2)])

        if self.feature_names == []:
            for channel1, number1 in  channel_features.iterkeys():
                for channel2, number2 in  channel_features.iterkeys():
                    if channel1 == channel2 and number1 > number2:
                        self.feature_names.append( \
                            "TDIntraChannel_%s_%.3fsec_%.3fsec" % (channel1,
                                  indexToTime(number1), indexToTime(number2)))
                    elif number1 == number2 and channel1 != channel2:
                        self.feature_names.append( \
                            "TDInterChannel_%s-%s_%.3fsec" % (channel1,
                                              channel2, indexToTime(number1)))

        feature_vector = \
         FeatureVector(numpy.atleast_2d(features).astype(numpy.float64),
         self.feature_names)

        return feature_vector

class SimpleDifferentiationFeatureNode(BaseNode):
    """ Use differences between successive times on the same channel.

    This node uses differences between successive times on the same channel
    of the time series as features to simulate differentiation.

    **Parameters**

        :datapoints:
            The indices of the data points that are used. If None, all
            data points are used.

            (*Optional, default: None*)

        :moving_window_length:
            If this parameter is greater than one, then not the data point x[i]
            is used but the average of the k=*moving_window_length* elements
            around x[i], i.e. avg([x[i-k/2],...,x[i+k/2]).

            (*Optional, default: 1*)

    **Known Issues**
        .. todo:: new node with same result as a new time series

    **Exemplary Call**

    .. code-block:: yaml

        -
            node : Derivative_Features
            parameters :
                datapoints : None
                moving_window_length : 1

    :Author: Mario Krell (Mario.Krell@dfki.de)
    """
    # Simple copy of the TimeDifferenceFeatureNode with slight change at the
    # end. More complex would be a short time regression between more than two
    # points. Yet the possiblity to make it a "real" differentiation is in
    # comment.
    def __init__(self,
                datapoints = None,
                moving_window_length = 1,
                **kwargs):
        super(SimpleDifferentiationFeatureNode, self).__init__(**kwargs)
        self.set_permanent_attributes(datapoints = datapoints,
                            moving_window_length = moving_window_length)

    def _execute(self, x):
        """
        Extract the TD features from the given data x
        """
        if self.datapoints == "None":
            self.datapoints = None
        if self.datapoints == None:
            self.datapoints = range(x.shape[0])
        y=x.view(numpy.ndarray)
        # From each selected channel we extract the specified data points
        indices = []
        for datapoint in self.datapoints:
            indices.append(range(max(0,
                                     int(datapoint - self.moving_window_length / 2)),
                                     int(min(x.shape[0], datapoint + (self.moving_window_length + 1) / 2))
            ))

        channel_features = dict()
        for channel_name in x.channel_names:
            channel_index = x.channel_names.index(channel_name)
            for number, index_range in enumerate(indices):
                channel_features[(channel_name, number)] = \
                                  numpy.mean(y[index_range, channel_index])

        # Mapping from datapoint index to relative time to onset
        def indexToTime(index):
            if index >= 0:
                return float(index) / x.sampling_frequency
            else:
                return (x.end_time - x.start_time)/ 1000.0 \
                                         + float(index) / x.sampling_frequency

        features = []
        feature_names = []
        for channel1, number1 in  channel_features.iterkeys():
            # intuitive derivative quotient
            number2 = number1 + 1
            if (channel1, number2) in  channel_features.iterkeys():
                features.append(channel_features[(channel1, number2)] - \
                    channel_features[(channel1, number1)])#*sampling_frequency
                feature_names.append("Df2_%s_%.3fsec" %
                                             (channel1, indexToTime(number1)))
            # Method taken frome http://www.holoborodko.com/pavel/?page_id=245
            # f'(x)=\\frac{2(f(x+h)-f(x-h))-(f(x+2h)-f(x-2h))}{8h}
            # Further smoothing functions are available, but seemingly not
            # necessary, because we have already a smoothing of the signal
            # when doing the subsampling.
            number3 = number1 + 4
            number = number1 + 2
            if (channel1, number3) in  channel_features.iterkeys():
                features.append(2.0 * (channel_features[(channel1, number+1)]\
                 - channel_features[(channel1, number-1)]) - \
                 (channel_features[(channel1, number+2)] - channel_features[(\
                 channel1, number-2)]))#*8*sampling_frequency
                feature_names.append("Df5_%s_%.3fsec" %
                                              (channel1, indexToTime(number)))
        feature_vector = \
         FeatureVector(numpy.atleast_2d(features).astype(numpy.float64),
         feature_names)
        features = []
        feature_names = []
        channel_features = dict()
        return feature_vector

@ChoiceParameter("coefficients_used", choices=[[0], [1], [0, 1]])
@QUniformParameter("stepsize", min_value=0, max_value=1000, q=20)
@QUniformParameter("segment_width", min_value=0, max_value=500, q=100)
class LocalStraightLineFeatureNode(BaseNode):
    """ Fit straight lines to channel segments and uses coefficients as features.

    Fit first order polynomials (straight lines) to subsegments of the
    channels and use the learned coefficients as features.

    **Parameters**

        :segment_width:
            The width of the segments (in milliseconds) to which straight lines
            are fitted.

            .. note:: segment_width is rounded such that it becomes a multiple
                      of the sampling interval.

        :stepsize:
            The time (in milliseconds) the segments are shifted. Extracted
            segments are [0, segment_width], [stepsize, segment_width+stepsize],
            [2*stepsize, segment_width+2*stepsize], ...

            .. note:: stepsize is rounded such that it becomes a multiple
                      of the sampling interval.

        :coefficients_used:
            List of the coefficients of the straight line that are actually used
            as features. The offset of the straight line is the coefficient 0 and
            the slope is coefficient 1. Per default, both are used as features.

            (*optional, default: [0, 1]*)

    **Exemplary Call**

    .. code-block:: yaml

        -
            node : Local_Straightline_Features
            parameters :
                  segment_width : 1000
                  stepsize : 1000

    .. todo::
        Check if segment width and stepsize make sense in relation to data.
        Program should not crash for bad choice (e.g., 400 and 200 on default data)?

    :Author: Jan Hendrik Metzen (jhm@informatik.uni-bremen.de)
    :Created: 2011/01/04
    :Refactored: 2012/01/18
    """
    input_types=["TimeSeries"]
    def __init__(self, segment_width, stepsize, coefficients_used=[0, 1],
                 *args, **kwargs):
        super(LocalStraightLineFeatureNode, self).__init__(*args, **kwargs)

        assert len(coefficients_used) <= 2 and \
                    len(set(coefficients_used).difference([0,1])) == 0, \
                        "Only the coefficients 0 (offset) and 1 (slope) are " \
                        "supported!"

        # Externally, coefficient 0 denotes the offset and coefficient 1
        # denotes the slope. polyfit handles this the other way around.
        coefficients_used = 1 - numpy.array(coefficients_used)

        self.set_permanent_attributes(segment_width = segment_width,
                                      stepsize = stepsize,
                                      coefficients_used = coefficients_used)

    def _execute(self, data):
        # Convert window_width and step size from milliseconds to data points
        segment_width = self.segment_width / 1000.0 * data.sampling_frequency
        segment_width = int(round(segment_width))

        stepsize = self.stepsize / 1000.0 * data.sampling_frequency
        stepsize = int(round(stepsize))
        if stepsize <= 0:
            stepsize = 1000
            self._log("Too small stepsize used! Changed to 1000.",
                level=logging.ERROR)

        sample_width = int(1000 / data.sampling_frequency)

        # The subwindows of the time series to which a straight line is fitted
        num_windows = \
            data.shape[1] * ((data.shape[0] - segment_width) / stepsize + 1)
        windows = numpy.zeros((segment_width, num_windows))

        feature_names = []
        counter = 0
        data_array = data.view(numpy.ndarray)
        for channel_index, channel_name in enumerate(data.channel_names):
            start = 0 # Start of segment (index)
            while start + segment_width <= data.shape[0]:
                # Compute and round start and end of segment
                end = start + segment_width

                # calculate sub-windows
                windows[:, counter] = \
                                    data_array[start:end, channel_index]

                #coefficients_used is inverted (see __init__)
                #feature name consists of start and end time
                if 0 in self.coefficients_used:
                    feature_names.append("LSFOffset_%s_%.3fsec_%.3fsec" \
                                            % (channel_name,
                                               float(start * sample_width)/1000.0,
                                               float(end * sample_width)/1000.0))
                if 1 in self.coefficients_used:
                    feature_names.append("LSFSlope_%s_%.3fsec_%.3fsec" \
                                            % (channel_name,
                                               float(start * sample_width)/1000.0,
                                               float(end * sample_width)/1000.0))

                # Move to next segment
                start = start + stepsize
                counter += 1
        assert counter == windows.shape[1]

        # Compute the local straight line features
        coeffs = numpy.polyfit(range(windows.shape[0]), windows, 1)
        coeffs =  coeffs[self.coefficients_used].flatten('F')

        feature_vector = \
            FeatureVector(numpy.atleast_2d(coeffs).astype(numpy.float64),
                          feature_names)

        return feature_vector

_NODE_MAPPING = {"Time_Domain_Features": TimeDomainFeaturesNode,
                "TDF": TimeDomainFeaturesNode,
                "Time_Domain_Difference_Features": TimeDomainDifferenceFeatureNode,
                "Derivative_Features": SimpleDifferentiationFeatureNode,
                "Local_Straightline_Features" : LocalStraightLineFeatureNode,
                "Custom_Features": CustomChannelWiseFeatureNode}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <meta http-equiv="Content-Style-Type" content="text/css" />
    <meta name="description" content="Returns the total of all valid, non-blank values in field." />

    <title>Sum</title>

    <link rel="StyleSheet" href="../css/webworks.css" type="text/css" media="all" />
    <link rel="StyleSheet" href="../css/print.css" type="text/css" media="print" />

      FileMaker Pro 13 Help

      Contents
      Next >
      < Previous

      Home >
      Reference >
      Functions reference >
      Aggregate functions >
      Sum

Sum

Purpose

Returns the total of all valid, non-blank values in field.

Format

Sum(field{;field...})

Parameters

field - any related field, repeating field, or set of non-repeating fields; or an expression that returns a field, repeating field, or set of non-repeating fields.

Parameters in curly braces { } are optional.

Data type returned

number

Originated in

FileMaker Pro 6.0 or earlier

Description

Field can be any of the following:

                 •

a repeating field (repeatingField).

                 •

a field in matching related records specified by (table::field), whether or not these records appear in a portal.

                 •

several non-repeating fields in a record (field1;field2;field3...).

                 •

corresponding repetitions of repeating fields in a record (repeatingField1;repeatingField2;repeatingField3), if the result is returned in a repeating field with at least the same number of repeats.

                 •

several fields in the first matching record specified by (table::field1;table::field2;...). You can include fields from different tables (table 1::field A;table 2::field B...).

Examples

An Invoice table has a portal showing line items.

Sum(LineItems::ExtendedPrice) totals the amounts for all items on the invoice.

A TimeBilling table has a portal showing time worked on a project. Hours is a time field.

Sum(Hours::BillableHours) returns the total number of billable hours on a project. Thus, if the portal shows 40 hours and 15:30 hours, the total billable hours are 55:30, or 55 1/2 hours.

 In the following examples:

                 •

Field1 contains two repetitions with values of 1 and 2.

                 •

Field2 contains four repetitions with values of 5, 6, 7, and 8.

                 •

Field3 contains 6.

If the calculation result isn't a repeating field:

                 •

Sum(Field2) returns 26.

                 •

Sum(Field1;Field2;Field3) returns 12.

If the calculation result is a repeating field:

                 •

Sum(Field2) returns a repeating field with 26 in the first repetition.

                 •

Sum(Field1;Field2;Field3) returns a repeating field with 12, 8, 7, 8.

        Note  When a referenced field is a repeating field, the Sum function returns the sum of the first repetition field, then the sum of the second repetition field, and so on.

Related topics

Functions reference (category list)

Functions reference (alphabetical list)

About formulas

About functions

Defining calculation fields

Using operators in formulas

Was this topic helpful? Send feedback.


text:
package client

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"strconv"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
)

// ErrPodInfoNotAvailable may be returned when the requested pod info is not available.
var ErrPodInfoNotAvailable = errors.New("no pod info available")

// PodInfoGetter is an interface for things that can get information about a pod's containers.
// Injectable for easy testing.
type PodInfoGetter interface {
	// GetPodInfo returns information about all containers which are part
	// Returns an api.PodInfo, or an error if one occurs.
	GetPodInfo(host, podNamespace, podID string) (api.PodInfo, error)
}

// HTTPPodInfoGetter is the default implementation of PodInfoGetter, accesses the kubelet over HTTP.
type HTTPPodInfoGetter struct {
	Client *http.Client
	Port   uint
}

// GetPodInfo gets information about the specified pod.
func (c *HTTPPodInfoGetter) GetPodInfo(host, podNamespace, podID string) (api.PodInfo, error) {
	request, err := http.NewRequest(
		"GET",
		fmt.Sprintf(
			"http://%s/podInfo?podID=%s&podNamespace=%s",
			net.JoinHostPort(host, strconv.FormatUint(uint64(c.Port), 10)),
			podID,
			podNamespace),
		nil)
	if err != nil {
		return nil, err
	}
	response, err := c.Client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	if response.StatusCode == http.StatusNotFound {
		return nil, ErrPodInfoNotAvailable
	}
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	// Check that this data can be unmarshalled
	info := api.PodInfo{}
	err = json.Unmarshal(body, &info)
	if err != nil {
		return nil, err
	}
	return info, nil
}

// FakePodInfoGetter is a fake implementation of PodInfoGetter. It is useful for testing.
type FakePodInfoGetter struct {
	data api.PodInfo
	err  error
}

// GetPodInfo is a fake implementation of PodInfoGetter.GetPodInfo.
func (c *FakePodInfoGetter) GetPodInfo(host, podNamespace string, podID string) (api.PodInfo, error) {
	return c.data, c.err
}


text:
// ==========================================================================
//                               journaled_set
// ==========================================================================
// Copyright (c) 2006-2013, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Rene Rahn <rene.rahn@fu-berlin.de>
// ==========================================================================

#ifndef EXTRAS_INCLUDE_SEQAN_JOURNALED_SET_JOURNALED_SET_BASE_H_
#define EXTRAS_INCLUDE_SEQAN_JOURNALED_SET_JOURNALED_SET_BASE_H_

namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// ----------------------------------------------------------------------------
// Spec JournaledSet
// ----------------------------------------------------------------------------

/*!
 * @class JournaledSet
 * @extends StringSet
 * @headerfile <seqan/journaled_set.h>
 *
 * @signature template <typename TString>
 *            class StringSet<TString, Owner<JournaledSet> >;
 * @tparam TString The string type. Types: @link String @endlink, @link JournaledString @endlink
 *
 * @brief A @link StringSet @endlink storing the strings as members.  It can store a global reference sequence to which all members can
 * be journaled if they are of type @link JournaledString @endlink.
 *
 * The strings are internally stored in a <tt>String<TString></tt> object and the character position type is a @link
 * Pair @endlink <tt>(seqNo, seqOfs)</tt> where seqNo identifies the string within the string set and seqOfs identifies
 * the position within this string.
 *
 * The global reference is of type <tt>Host<TString></tt>. Only strings of type @link JournaledString @endlink or
 * <tt>Host<</tt>@link JournaledString @endlink<tt>></tt> can be used for the advanced functionality supported by
 * this string set.
 */

/**
.Spec.Journaled Set:
..summary:A string set storing the string as members. It can store a global reference sequence to which
all members can be journaled if they are of type @Spec.Journaled String@.
..cat:Sequences
..signature:StringSet<TString, Owner<JournaledSet> >
..param.TString:The string type.
...type:Class.String
...type:Spec.Journaled String
..remarks:The strings are internally stored in a $String<TString>$ object and the character position type is a
@Class.Pair@ $(seqNo,seqOfs)$ where seqNo identifies the string within the stringset and seqOfs identifies the position within this string.
..remarks:The global reference is of type $Host<TString>$. Only strings of type @Spec.Journaled String@ or $Host<$@Spec.Journaled String@>$
can be used for the advanced functionality supported by this string set.
..include:seqan/journal_set.h
 */

struct JournaledSet_;
typedef Tag<JournaledSet_> JournaledSet;

// ----------------------------------------------------------------------------
// Class JournalTraceBuffer
// ----------------------------------------------------------------------------

template <typename TString>
class JournalTraceBuffer;

/*!
 * @defgroup JoinStrategiesTags Join Strategies Tags
 * @brief Tags used for selecting journaling strategies when joining a JournaledString to a global reference sequence.
 *
 *
 * @tag JoinStrategiesTags#JournaledManhattan
 * @headerfile <seqan/sequence_journaled.h>
 * @brief Constructs a @link JournaledString @endlink based on Manhattan distance.
 *
 * This strategy is very fast on the cost of memory.
 *
 * @signature typedef Tag<JournaledManhattan_> JournaledManhattan.
 *
 *
 * @tag JoinStrategiesTags#JournaledCompact
 * @headerfile <seqan/sequence_journaled.h>
 * @brief Computes an optimal alignment to construct a @link JournaledString @endlink.
 *
 * This strategy is slow but depending on the scoring function minimizes the memory requirements for the computed @link
 * JournaledSet @endlink.
 *
 * @signature typedef Tag<JournaledCompact_> JournaledCompact;
 */

/**
.Tag.Join Strategies
..cat:Alignments
..summary:Tags used for selecting journaling strategies when joining a @Spec.Journaled String@ to a global reference sequence.
..tag
...JournaledManhatten:Constructs @Spec.Journaled String@ based on Manhatten distance.
....remarks:This strategy is very fast on the cost of memory.
...JournaledCompact:Computes an optimal alignment to construct @Spec.Journaled String@.
....remarks:This strategy is slow but depending on the scoring function minimizes the memory requirements for the computed @Spec.Journaled String@ (default).
..see:Function.join
..include:seqan/align.h
*/

// ----------------------------------------------------------------------------
// Tag JournaledManhatten
// ----------------------------------------------------------------------------

struct JournaledManhatten_;
typedef Tag<JournaledManhatten_> JournaledManhatten;

// ----------------------------------------------------------------------------
// Tag JournaledCompact
// ----------------------------------------------------------------------------

struct JournaledCompact_;
typedef Tag<JournaledCompact_> JournaledCompact;

// ----------------------------------------------------------------------------
// Spec GlobalAlign
// ----------------------------------------------------------------------------

/*!
 * @class GlobalAlign
 * @extends JoinConfig
 *
 * @headerfile <seqan/journaled_set.h>
 * @brief Selects a global alignment method to join a @link JournaledString @endlink to a global reference sequence.
 *
 * @signature template <[typename TStrategy]>
 *            struct GlobalAlign;
 *
 * @tparam TStrategy The strategy used to compute the journal (can be one of @link JoinStrategiesTags#JournaledCompact
 *                   @endlink and @link JoinStrategiesTags#JournaledManhattan @endlink, defaults to @link
 *                   JoinStrategiesTags#JournaledManhattan @endlink).
 *
 * If @link JoinStrategiesTags#JournaledManhattan @endlink is selected, then the resulting @link JournaledString
 * @endlink consists of one insertion node covering the complete joined sequence.
 */

/**
.Spec.GlobalAlign:
..summary:Selects a global alignment method to join a @Spec.Journaled String@ to a global reference sequence.
..cat:Sequences
..general:Class.JoinConfig
..signature:GlobalAlign<TStrategyTag>
..param.TStrategyTag:The strategy used to compute the journal.
...type:Tag.Join Strategies.tag.JournaledManhatten
...type:Tag.Join Strategies.tag.GlobalChain
..default:Tag.Join Strategies.tag.JournaledManhatten
..remarks:If @Tag.Join Strategies.tag.JournaledManhatten@ is selected, then the resulting @Spec.Journaled String@ consists
of one insertion node covering the complete joined sequence.
..see:Spec.GlobalChain
..include:seqan/journal_set.h
 */

template <typename TSpec = JournaledManhatten>
struct GlobalAlign{};

// ----------------------------------------------------------------------------
// Spec GlobalChain
// ----------------------------------------------------------------------------

/*!
 * @class GlobalChain
 * @extends JoinConfig
 *
 * @headerfile <seqan/journaled_set.h>
 * @brief Selects an anchor-based method to join a @link JournaledString @endlink to a global reference sequence.
 *
 * @signature template <[typename TStrategy]>
 *            struct GlobalChain;
 *
 * @tparam TStrategy The strategy used to compute the journal (can be one of @link JoinStrategiesTags#JournaledCompact
 *                   @endlink and @link JoinStrategiesTags#JournaledManhattan @endlink, defaults to @link
 *                   JoinStrategiesTags#JournaledManhattan @endlink).
 *
 * The @link JoinStrategiesTags#JournaledManhattan @endlink strategy fills the gaps between the anchors with a single
 * insertion node whil the corresponding part of the reference sequence is deleted.
 */

/**
.Spec.GlobalChain:
..summary:Selects an anchor based method to join a @Spec.Journaled String@ to a global reference sequence.
..cat:Sequences
..general:Class.JoinConfig
..signature:GlobalChain<TStrategyTag>
..param.TStrategyTag:The strategy used to compute the journal.
...type:Tag.Join Strategies.tag.JournaledManhatten
...type:Tag.Join Strategies.tag.JournaledCompact
..default:Tag.Join Strategies.tag.JournaledManhatten
..remarks:The @Tag.Join Strategies.tag.JournaledManhatten@ strategy fills the gaps between the anchors with a single insertion node,
while the corresponding part of the reference sequence is deleted.
..see:Spec.GlobalAlign
..include:seqan/journal_set.h
 */

template <typename TSpec = JournaledManhatten>
struct GlobalChain{};

// ----------------------------------------------------------------------------
// Class JoinConfig
// ----------------------------------------------------------------------------

/*!
 * @class JoinConfig
 * @headerfile <seqan/journaled_set.h>
 * @brief Specifies the strategy and all necessary parameters used to journal a sequence to a reference sequence.
 *
 * @signature template <[typename TMethod]>
 *            struct JoinConfig;
 *
 * @tparam TMethod The method type. Types: @link GlobalAlign @endlink, @link GlobalChain @endlink
 *
 * SeqAn offers two general methods to compute the journal.  The first one uses a @link globalAlignment @endlink
 * function and the second one uses an anchor based approach.
 */

/**
.Class.JoinConfig:
..summary:Specifies the strategy and all necessary parameters used to journal a sequence to a reference sequence.
..cat:Sequences
..signature:JoinConfig<TMethod>
..param.TMethod:The method type.
...type:Spec.GlobalAlign
...type:Spec.GlobalChain
..default:Spec.JournaledManhatten
..remarks:SeqAn offers two general methods to compute the journal. The first one uses a @Function.globalAlignment@ function
and the second one uses an anchor based approach.
..include:seqan/journal_set.h
 */

template <typename TSpec = GlobalAlign<JournaledManhatten> >
struct JoinConfig{};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

}  // namespace seqan

#endif  // EXTRAS_INCLUDE_SEQAN_JOURNALED_SET_JOURNALED_SET_BASE_H_


text:
package io.reactivex.rxjava3.disposables;

import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.*;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.*;

import org.junit.Test;
import org.reactivestreams.Subscription;

import io.reactivex.rxjava3.core.RxJavaTest;
import io.reactivex.rxjava3.exceptions.TestException;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.internal.disposables.DisposableHelper;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
import io.reactivex.rxjava3.testsupport.TestHelper;

public class DisposableTest extends RxJavaTest {

    @Test
    public void unsubscribeOnlyOnce() {
        Runnable run = mock(Runnable.class);

        Disposable d = Disposable.fromRunnable(run);

        assertTrue(d.toString(), d.toString().contains("RunnableDisposable(disposed=false, "));

        d.dispose();
        assertTrue(d.toString(), d.toString().contains("RunnableDisposable(disposed=true, "));

        d.dispose();
        assertTrue(d.toString(), d.toString().contains("RunnableDisposable(disposed=true, "));

        verify(run, times(1)).run();
    }

    @Test
    public void empty() {
        Disposable empty = Disposable.empty();
        assertFalse(empty.isDisposed());
        empty.dispose();
        assertTrue(empty.isDisposed());
    }

    @Test
    public void unsubscribed() {
        Disposable disposed = Disposable.disposed();
        assertTrue(disposed.isDisposed());
    }

    @Test
    public void fromAction() throws Throwable {
        Action action = mock(Action.class);

        Disposable d = Disposable.fromAction(action);

        assertTrue(d.toString(), d.toString().contains("ActionDisposable(disposed=false, "));

        d.dispose();
        assertTrue(d.toString(), d.toString().contains("ActionDisposable(disposed=true, "));

        d.dispose();
        assertTrue(d.toString(), d.toString().contains("ActionDisposable(disposed=true, "));

        verify(action, times(1)).run();
    }

    @Test
    public void fromActionThrows() {
        try {
            Disposable.fromAction(new Action() {
                @Override
                public void run() throws Exception {
                    throw new IllegalArgumentException();
                }
            }).dispose();
            fail("Should have thrown!");
        } catch (IllegalArgumentException ex) {
            // expected
        }

        try {
            Disposable.fromAction(new Action() {
                @Override
                public void run() throws Exception {
                    throw new InternalError();
                }
            }).dispose();
            fail("Should have thrown!");
        } catch (InternalError ex) {
            // expected
        }

        try {
            Disposable.fromAction(new Action() {
                @Override
                public void run() throws Exception {
                    throw new IOException();
                }
            }).dispose();
            fail("Should have thrown!");
        } catch (RuntimeException ex) {
            if (!(ex.getCause() instanceof IOException)) {
                fail(ex.toString() + ": Should have cause of IOException");
            }
            // expected
        }

    }

    @Test
    public void disposeRace() {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            final Disposable d = Disposable.empty();

            Runnable r = new Runnable() {
                @Override
                public void run() {
                    d.dispose();
                }
            };

            TestHelper.race(r, r);
        }
    }

    @Test(expected = NullPointerException.class)
    public void fromSubscriptionNull() {
        Disposable.fromSubscription(null);
    }

    @Test
    public void fromSubscription() {
        Subscription s = mock(Subscription.class);

        Disposable.fromSubscription(s).dispose();

        verify(s).cancel();
        verify(s, never()).request(anyInt());
    }

    @Test
    public void setOnceTwice() {
        List<Throwable> errors = TestHelper.trackPluginErrors();
        try {

            AtomicReference<Disposable> target = new AtomicReference<>();
            Disposable d = Disposable.empty();

            DisposableHelper.setOnce(target, d);

            Disposable d1 = Disposable.empty();

            DisposableHelper.setOnce(target, d1);

            assertTrue(d1.isDisposed());

            TestHelper.assertError(errors, 0, IllegalStateException.class, "Disposable already set!");
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void fromAutoCloseable() {
        AtomicInteger counter = new AtomicInteger();

        AutoCloseable ac = () -> counter.getAndIncrement();

        Disposable d = Disposable.fromAutoCloseable(ac);

        assertFalse(d.isDisposed());
        assertEquals(0, counter.get());
        assertTrue(d.toString(), d.toString().contains("AutoCloseableDisposable(disposed=false, "));

        d.dispose();

        assertTrue(d.isDisposed());
        assertEquals(1, counter.get());
        assertTrue(d.toString(), d.toString().contains("AutoCloseableDisposable(disposed=true, "));

        d.dispose();

        assertTrue(d.isDisposed());
        assertEquals(1, counter.get());
        assertTrue(d.toString(), d.toString().contains("AutoCloseableDisposable(disposed=true, "));
    }

    @Test
    public void fromAutoCloseableThrows() throws Throwable {
        TestHelper.withErrorTracking(errors -> {
            AutoCloseable ac = () -> { throw new TestException(); };

            Disposable d = Disposable.fromAutoCloseable(ac);

            assertFalse(d.isDisposed());

            assertTrue(errors.isEmpty());

            try {
                d.dispose();
                fail("Should have thrown!");
            } catch (TestException expected) {
                // expected
            }

            assertTrue(d.isDisposed());

            d.dispose();

            assertTrue(d.isDisposed());

            assertTrue(errors.isEmpty());
        });
    }

    @Test
    public void toAutoCloseable() throws Exception {
        AtomicInteger counter = new AtomicInteger();

        Disposable d = Disposable.fromAction(() -> counter.getAndIncrement());

        AutoCloseable ac = Disposable.toAutoCloseable(d);

        assertFalse(d.isDisposed());
        assertEquals(0, counter.get());

        ac.close();

        assertTrue(d.isDisposed());
        assertEquals(1, counter.get());

        ac.close();

        assertTrue(d.isDisposed());
        assertEquals(1, counter.get());
    }
}


text:
public class Detergent1{
	private String name;
	private Cleaner1 cleaner=new Cleaner1();
	public Detergent1(String name){
		this.name=name;
	}
	public void append(String a){
		name+=a;
	}
	public void dilute(){
		cleaner.append("dilute()");
	}
	public void apply(){
		cleaner.append("apply()");
	}
	public void scrub(){
		cleaner.append("scrub()");
	}
	public String toString(){
		return name;
	}
	public static void main(String args[]){
		Detergent1 test=new Detergent1("cleaner");
		test.dilute();
	}
}


text:
"""
Main Space Trader Galaxy class.

Created on Thu Jul  6 01:59:38 2017

@author: mjm
"""

import logging
import logging.config
import character as char
import good as good

def trade(seller, buyer, commodity, pay):
    """
    Seller sells commodity to the buyer who pays with pay.
    Arguments:
        seller - type Character
        buyer - type Character
        commodity - type Good
        pay - type Good
    Returns:
        success (True) or fail (False)
    """
    """
    Pseudocode
    log init
    if seller owns commodity:
        if buyer owns pay:
            commodity.transfer(new_owner=buyer)
            pay.transfer(new_owner=seller)
            log
            return True
        else:
            log
            return False
    else:
        log
        return False
    log end
    """
    pass
    success = False
    if commodity in seller.belongings: #TODO change into owns() by Character
        if pay in buyer.belongings: #same here
            commodity.transfer(new_owner=buyer)
            pay.transfer(new_owner=seller)
            pass
            success = True
        else:
            pass
            success = False
    else:
        pass
        success = False
    pass
    return success

def test_trade():
    print """Initialisation"""
    matt = char.Character("Matt", [], "Earth")
    tony = char.Character("Tony", [], "Mars")
    matt1 = good.Good("Matt's item 1", matt)
    tony1 = good.Good("Tony's item 1", tony)
    tony2 = good.Good("Tony's item 2", tony)
    print matt.describe()
    print
    print tony.describe()
    print
    print """Trade undertaking:"""
    print "- Tony trades with Matt, seller does not have good"
    print trade(tony, matt, matt1, matt1)
    print
    print matt.describe()
    print
    print tony.describe()
    print
    print "- Tony trades with Matt, buyer does not have good"
    print trade(tony, matt, tony1, tony2)
    print
    print matt.describe()
    print
    print tony.describe()
    print
    print "- Tony trades with Matt, None have the good"
    print trade(tony, matt, matt1, tony1)
    print
    print matt.describe()
    print
    print tony.describe()
    print
    print "- Matt trades with Tony, both have the good"""
    print trade(matt, tony, matt1, tony1)
    print matt.describe()
    print
    print tony.describe()
    print

def main():
    logging.config.fileConfig('logs.conf')
    logging.info("Program started.")

    test_trade()

    logging.info("Program finished.")

if __name__ == "__main__":
    main()


text:
layout: default
title: CAS - Google Apps Integration
category: Integration
---

# Overview

Google Apps for Education (or any of the Google Apps) utilizes SAML 2.0 to provide an
integration point for external authentication services.

Usage

The Google Apps for Education integration described here allows CAS to act as a miniaturized SAML2 identity provider,
for deployments that may not be prepared to turn on and allow CAS to fully act as a SAML2 identity provider. It does not
make much sense to turn on and use both features in CAS at the same time, as one outranks the other and it is likely
that using both features in CAS simultanously would intefere with the functionality of both. If you can, consider using
the SAML2 identity provider functionality in CAS to handle this integration as you would any other SAML2 service provider.

Support is enabled by including the following dependency in the WAR overlay:

```xml
<dependency>
  <groupId>org.apereo.cas</groupId>
  <artifactId>cas-server-support-saml-googleapps</artifactId>
  <version>${cas.version}</version>
</dependency>
```

## Generate Public/Private Keys

The first step is to generate DSA/RSA public and private keys. These are used to sign and read the Assertions.
After keys are created, the public key needs to be registered with Google.

The keys will also need to be available to the CAS application (but not publicly available over the Internet)
via the classpath though any location accessible by the user running the web server
instance and not served publicly to the Internet is acceptable.  Thus, inside `src/main/resources` is
nice because it is scoped to the web application but not normally served. `/etc/cas/`
is also fine as well and protects the key from being overwritten on deploy of a new CAS webapp version.

```bash
openssl genrsa -out private.key 1024
openssl rsa -pubout -in private.key -out public.key -inform PEM -outform DER
openssl pkcs8 -topk8 -inform PER -outform DER -nocrypt -in private.key -out private.p8
openssl req -new -x509 -key private.key -out x509.pem -days 365
```

The `x509.pem` file should be uploaded into Google Apps under Security/SSO.

To see the relevant list of CAS properties, please [review this guide](../configuration/Configuration-Properties.html#google-apps-authentication).

## Register Google Apps

Ensure that Google Apps is registered in your [service registry](../services/Service-Management.html).

```json
{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "https://www.google.com/a/YourGoogleDomain/acs",
  "name" : "googleApps",
  "id" : 1000,
  "evaluationOrder" : 10
}
```

## Configure Username Attribute

As an optional step, you can configure an alternate username to be send to Google in the SAML reply. This alternate user name
can be specified in the CAS service registry via [username attribute providers](../services/Service-Management.html)
for the registered Google Apps service.

## Configure Google

You'll need to provide Google with the URL for your SAML-based SSO service, as well as the URL your users will
be redirected to when they log out of a hosted Google application.
Use the following URLs when you are configuring for Google Apps:

* Sign-in page URL: `https://sso.school.edu/cas/login`
* Sign-out page URL: `https://sso.school.edu/cas/logout`
* Change password URL: `https://mgmt.password.edu/`

## Test

Attempt to access a Google-hosted application, such as Google Calendar
with the url: `https://calendar.google.com/a/YourGoogleDomain`


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\CfgTipoAlerta;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;

/**
 * Cfgtipoalertum controller.
 *
 * @Route("cfgtipoalerta")
 */
class CfgTipoAlertaController extends Controller
{
    /**
     * Lists all cfgTipoAlertum entities.
     *
     * @Route("/", name="cfgtipoalerta_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $helpers = $this->get("app.helpers");

        $em = $this->getDoctrine()->getManager();

        $tiposAlerta = $em->getRepository('AppBundle:CfgTipoAlerta')->findAll();

        $response['data'] = array();

        if ($tiposAlerta) {
            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => count($tiposAlerta)." registros encontrados",
                'data'=> $tiposAlerta,
            );
        }

        return $helpers->json($response);
    }

    /**
     * Creates a new cfgTipoAlertum entity.
     *
     * @Route("/new", name="cfgtipoalerta_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck== true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $tipoAlerta = new CfgTipoAlerta();

            $tipoAlerta->setNombre(strtoupper($params->nombre));
            $tipoAlerta->setEstado(true);

            $em = $this->getDoctrine()->getManager();

            $em->persist($tipoAlerta);
            $em->flush();

            $response = array(
                'status' => 'success',
                'code' => 200,
                'message' => "Registro creado con exito",
            );
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorizacion no valida",
            );
        }

        return $helpers->json($response);
    }

    /**
     * Finds and displays a cfgTipoAlertum entity.
     *
     * @Route("/show", name="cfgtipoalerta_show")
     * @Method("POST")
     */
    public function showAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck == true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();

            $tipoAlerta = $em->getRepository('AppBundle:CfgTipoAlerta')->find(
                $params->id
            );

            if ($tipoAlerta) {
                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Registro encontrado",
                    'data'=> $tipoAlerta,
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "El registro no se encuentra en la base de datos",
                );
            }
        }else{
            $response = array(
                'status' => 'error',
                'code' => 400,
                'message' => "Autorizacion no valida",
            );
        }

        return $helpers->json($response);
    }

    /**
     * Displays a form to edit an existing cfgTipoAlertum entity.
     *
     * @Route("/edit", name="cfgtipoalerta_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request)
    {
        $helpers = $this->get("app.helpers");
        $hash = $request->get("authorization", null);
        $authCheck = $helpers->authCheck($hash);

        if ($authCheck==true) {
            $json = $request->get("data",null);
            $params = json_decode($json);

            $em = $this->getDoctrine()->getManager();
            $tipoAlerta = $em->getRepository("AppBundle:CfgTipoAlerta")->find(
                $params->id
            );

            if ($tipoAlerta) {
                $tipoAlerta->setNombre(strtoupper($params->nombre));

                $em->flush();

                $response = array(
                    'status' => 'success',
                    'code' => 200,
                    'message' => "Registro actualizado con exito",
                    'data'=> $tipoAlerta,
                );
            }else{
                $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "El registro no se encuentra en la base de datos",
                );
            }
        }else{
            $response = array(
                    'status' => 'error',
                    'code' => 400,
                    'message' => "Autorizacion no valida para editar",
                );
        }

        return $helpers->json($response);
    }

    /**
     * Deletes a cfgTipoAlertum entity.
     *
     * @Route("/{id}/delete", name="cfgtipoalerta_delete")
     * @Method("POST")
     */
    public function deleteAction(Request $request, CfgTipoAlerta $cfgTipoAlertum)
    {
        $form = $this->createDeleteForm($cfgTipoAlertum);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($cfgTipoAlertum);
            $em->flush();
        }

        return $this->redirectToRoute('cfgtipoalerta_index');
    }

    /**
     * Creates a form to delete a cfgTipoAlertum entity.
     *
     * @param CfgTipoAlerta $cfgTipoAlertum The cfgTipoAlertum entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(CfgTipoAlerta $cfgTipoAlertum)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('cfgtipoalerta_delete', array('id' => $cfgTipoAlertum->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     * datos para select 2
     *
     * @Route("/select", name="alerta_select")
     * @Method({"GET", "POST"})
     */
    public function selectAction()
    {
        $helpers = $this->get("app.helpers");
        $em = $this->getDoctrine()->getManager();

        $tiposAlerta = $em->getRepository('AppBundle:CfgTipoAlerta')->findAll();

        $response = null;

        foreach ($tiposAlerta as $key => $tipoAlerta) {
            $response[$key] = array(
                'value' => $tipoAlerta->getId(),
                'label' => $tipoAlerta->getNombre()
            );
        }
        return $helpers->json($response);
    }
}


text:
"""Support for writing JUnit XML test results for the regrtest"""
import os
import re
import sys
import time
import traceback
import unittest
from StringIO import StringIO
from xml.sax import saxutils

# Invalid XML characters (control chars)
EVIL_CHARACTERS_RE = re.compile(r"[\000-\010\013\014\016-\037]")

class JUnitXMLTestRunner:

    """A unittest runner that writes results to a JUnit XML file in
    xml_dir
    """

    def __init__(self, xml_dir):
        self.xml_dir = xml_dir

    def run(self, test):
        result = JUnitXMLTestResult(self.xml_dir)
        test(result)
        result.write_xml()
        return result

class JUnitXMLTestResult(unittest.TestResult):

    """JUnit XML test result writer.

    The name of the file written to is determined from the full module
    name of the first test ran
    """

    def __init__(self, xml_dir):
        unittest.TestResult.__init__(self)
        self.xml_dir = xml_dir

        # The module name of the first test ran
        self.module_name = None

        # All TestCases
        self.tests = []

        # Start time
        self.start = None

        self.old_stdout = sys.stdout
        self.old_stderr = sys.stderr
        sys.stdout = self.stdout = Tee(sys.stdout)
        sys.stderr = self.stderr = Tee(sys.stderr)

    def startTest(self, test):
        unittest.TestResult.startTest(self, test)
        self.ensure_module_name(test)
        self.error, self.failure = None, None
        self.start = time.time()

    def stopTest(self, test):
        took = time.time() - self.start
        unittest.TestResult.stopTest(self, test)
        args = [test, took]
        if self.error:
            args.extend(['error', self.error])
        elif self.failure:
            args.extend(['failure', self.failure])
        self.tests.append(TestInfo.from_testcase(*args))

    def addError(self, test, err):
        unittest.TestResult.addError(self, test, err)
        self.error = err

    def addFailure(self, test, err):
        unittest.TestResult.addFailure(self, test, err)
        self.failure = err

    def ensure_module_name(self, test):
        """Set self.module_name from test if not already set"""
        if not self.module_name:
            self.module_name = '.'.join(test.id().split('.')[:-1])

    def write_xml(self):
        if not self.module_name:
            # No tests ran, nothing to write
            return
        took = time.time() - self.start

        stdout = self.stdout.getvalue()
        stderr = self.stderr.getvalue()
        sys.stdout = self.old_stdout
        sys.stderr = self.old_stderr

        ensure_dir(self.xml_dir)
        filename = os.path.join(self.xml_dir, 'TEST-%s.xml' % self.module_name)
        stream = open(filename, 'w')

        write_testsuite_xml(stream, len(self.tests), len(self.errors),
                            len(self.failures), 0, self.module_name, took)

        for info in self.tests:
            info.write_xml(stream)

        write_stdouterr_xml(stream, stdout, stderr)

        stream.write('</testsuite>')
        stream.close()

class TestInfo(object):

    """The JUnit XML <testcase/> model."""

    def __init__(self, name, took, type=None, exc_info=None):
        # The name of the test
        self.name = name

        # How long it took
        self.took = took

        # Type of test: 'error', 'failure' 'skipped', or None for a
        # success
        self.type = type

        if exc_info:
            self.exc_name = exc_name(exc_info)
            self.message = exc_message(exc_info)
            self.traceback = safe_str(''.join(
                    traceback.format_exception(*exc_info)))
        else:
            self.exc_name = self.message = self.traceback = ''

    @classmethod
    def from_testcase(cls, testcase, took, type=None, exc_info=None):
        name = testcase.id().split('.')[-1]
        return cls(name, took, type, exc_info)

    def write_xml(self, stream):
        stream.write('  <testcase name="%s" time="%.3f"' % (self.name,
                                                            self.took))

        if not self.type:
            # test was successful
            stream.write('/>\n')
            return

        stream.write('>\n    <%s type="%s" message=%s><![CDATA[%s]]></%s>\n' %
                     (self.type, self.exc_name, saxutils.quoteattr(self.message),
                      escape_cdata(self.traceback), self.type))
        stream.write('  </testcase>\n')

class Tee(StringIO):

    """Writes data to this StringIO and a separate stream"""

    def __init__(self, stream):
        StringIO.__init__(self)
        self.stream = stream

    def write(self, data):
        StringIO.write(self, data)
        self.stream.write(data)

    def flush(self):
        StringIO.flush(self)
        self.stream.flush()

def write_testsuite_xml(stream, tests, errors, failures, skipped, name, took):
    """Write the XML header (<testsuite/>)"""
    stream.write('<?xml version="1.0" encoding="utf-8"?>\n')
    stream.write('<testsuite tests="%d" errors="%d" failures="%d" ' %
                 (tests, errors, failures))
    stream.write('skipped="%d" name="%s" time="%.3f">\n' % (skipped, name,
                                                            took))

def write_stdouterr_xml(stream, stdout, stderr):
    """Write the stdout/err tags"""
    if stdout:
        stream.write('  <system-out><![CDATA[%s]]></system-out>\n' %
                     escape_cdata(safe_str(stdout)))
    if stderr:
        stream.write('  <system-err><![CDATA[%s]]></system-err>\n' %
                     escape_cdata(safe_str(stderr)))

def write_direct_test(junit_xml_dir, name, took, type=None, exc_info=None,
                      stdout=None, stderr=None):
    """Write XML for a regrtest 'direct' test; a test which was ran on
    import (which we label as __main__.__import__)
    """
    return write_manual_test(junit_xml_dir, '%s.__main__' % name, '__import__',
                             took, type, exc_info, stdout, stderr)

def write_doctest(junit_xml_dir, name, took, type=None, exc_info=None,
                  stdout=None, stderr=None):
    """Write XML for a regrtest doctest, labeled as __main__.__doc__"""
    return write_manual_test(junit_xml_dir, '%s.__main__' % name, '__doc__',
                             took, type, exc_info, stdout, stderr)

def write_manual_test(junit_xml_dir, module_name, test_name, took, type=None,
                      exc_info=None, stdout=None, stderr=None):
    """Manually write XML for one test, outside of unittest"""
    errors = type == 'error' and 1 or 0
    failures = type == 'failure' and 1 or 0
    skipped = type == 'skipped' and 1 or 0

    ensure_dir(junit_xml_dir)
    stream = open(os.path.join(junit_xml_dir, 'TEST-%s.xml' % module_name),
                  'w')

    write_testsuite_xml(stream, 1, errors, failures, skipped, module_name,
                        took)

    info = TestInfo(test_name, took, type, exc_info)
    info.write_xml(stream)

    write_stdouterr_xml(stream, stdout, stderr)

    stream.write('</testsuite>')
    stream.close()

def ensure_dir(dir):
    """Ensure dir exists"""
    if not os.path.exists(dir):
        os.mkdir(dir)

def exc_name(exc_info):
    """Determine the full name of the exception that caused exc_info"""
    exc = exc_info[1]
    name = getattr(exc.__class__, '__module__', '')
    if name:
        name += '.'
    return name + exc.__class__.__name__

def exc_message(exc_info):
    """Safely return a short message passed through safe_str describing
    exc_info, being careful of unicode values.
    """
    exc = exc_info[1]
    if exc is None:
        return safe_str(exc_info[0])
    if isinstance(exc, BaseException) and isinstance(exc.message, unicode):
        return safe_str(exc.message)
    try:
        return safe_str(str(exc))
    except UnicodeEncodeError:
        try:
            val = unicode(exc)
            return safe_str(val)
        except UnicodeDecodeError:
            return '?'

def escape_cdata(cdata):
    """Escape a string for an XML CDATA section"""
    return cdata.replace(']]>', ']]>]]><![CDATA[')

def safe_str(base):
    """Return a str valid for UTF-8 XML from a basestring"""
    if isinstance(base, unicode):
        return remove_evil(base.encode('utf-8', 'replace'))
    return remove_evil(base.decode('utf-8', 'replace').encode('utf-8',
                                                              'replace'))

def remove_evil(string):
    """Remove control characters from a string"""
    return EVIL_CHARACTERS_RE.sub('?', string)


text:
import java.util.*;

public class Test {
  public void test() {
    List<String[]> list = List.<String[]>of(new String[]{"aaa"});
  }
}


text:
package org.develnext.jphp.core.tokenizer.token.expr.operator;

import php.runtime.common.Association;
import org.develnext.jphp.core.tokenizer.TokenType;
import org.develnext.jphp.core.tokenizer.TokenMeta;
import org.develnext.jphp.core.tokenizer.token.expr.OperatorExprToken;
import org.develnext.jphp.core.tokenizer.token.expr.ValueExprToken;
import org.develnext.jphp.core.tokenizer.token.stmt.ExprStmtToken;

public class DynamicAccessExprToken extends OperatorExprToken {
    protected ValueExprToken field;
    protected ExprStmtToken fieldExpr;

    public DynamicAccessExprToken(TokenMeta meta) {
        super(meta, TokenType.T_OBJECT_OPERATOR);
    }

    public ValueExprToken getField() {
        return field;
    }

    public void setField(ValueExprToken field) {
        this.field = field;
    }

    public ExprStmtToken getFieldExpr() {
        return fieldExpr;
    }

    public void setFieldExpr(ExprStmtToken fieldExpr) {
        this.fieldExpr = fieldExpr;
    }

    @Override
    public boolean isBinary() {
        return false;
    }

    @Override
    public int getPriority() {
        return 1;
    }

    @Override
    public Association getOnlyAssociation() {
        return Association.LEFT;
    }
}


text:
/**
 *
 */
package jframe.example.plugin2;

import jframe.core.plugin.annotation.Service;

/**
 * @author dzh
 * @date Sep 16, 2014 5:07:48 PM
 * @since 1.0
 */
@Service(id = "jframe.example.CountService2", clazz = "jframe.example.plugin2.CountService2Impl")
public interface CountService2 {

	int mul(int x, int y);

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class org.apache.commons.math3.util.BigReal (Apache Commons Math 3.3 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.commons.math3.util.BigReal

Packages that use BigReal

Package
Description

org.apache.commons.math3.util

Convenience routines and common data structures used throughout the commons-math library.

Uses of BigReal in org.apache.commons.math3.util

Fields in org.apache.commons.math3.util declared as BigReal

Modifier and Type
Field and Description

static BigReal
BigReal.ONE

A big real representing 1.

static BigReal
BigReal.ZERO

A big real representing 0.

Methods in org.apache.commons.math3.util that return BigReal

Modifier and Type
Method and Description

BigReal
BigReal.add(BigReal a)

Compute this + a.

BigReal
BigReal.divide(BigReal a)

Compute this ÷ a.

BigReal
BigRealField.getOne()

Get the multiplicative identity of the field.

BigReal
BigRealField.getZero()

Get the additive identity of the field.

BigReal
BigReal.multiply(BigReal a)

Compute this × a.

BigReal
BigReal.multiply(int n)

Compute n × this.

BigReal
BigReal.negate()

Returns the additive inverse of this element.

BigReal
BigReal.reciprocal()

Returns the multiplicative inverse of this element.

BigReal
BigReal.subtract(BigReal a)

Compute this - a.

Methods in org.apache.commons.math3.util that return types with arguments of type BigReal

Modifier and Type
Method and Description

Field<BigReal>
BigReal.getField()

Get the Field to which the instance belongs.

Class<? extends FieldElement<BigReal>>
BigRealField.getRuntimeClass()

Returns the runtime class of the FieldElement.

Methods in org.apache.commons.math3.util with parameters of type BigReal

Modifier and Type
Method and Description

BigReal
BigReal.add(BigReal a)

Compute this + a.

int
BigReal.compareTo(BigReal a)

BigReal
BigReal.divide(BigReal a)

Compute this ÷ a.

BigReal
BigReal.multiply(BigReal a)

Compute this × a.

BigReal
BigReal.subtract(BigReal a)

Compute this - a.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2003–2014 The Apache Software Foundation. All rights reserved.