text:
package textgen

import (
  "errors"
  "math/rand"
  "regexp"
  "strings"
)

var (
  defaultProcessor *Processor
  errorNoVariants  = errors.New("No generate variants")
)

type Processor struct {
  collectionRegex *regexp.Regexp
  borderSize      int
  separator       string
}

func MakeProcessor(re string, sep string, borderSize int) *Processor {
  r, _ := regexp.Compile(re)
  return &Processor{collectionRegex: r, separator: sep, borderSize: borderSize}
}

func getDefaultProcessor() *Processor {
  if nil == defaultProcessor {
    defaultProcessor = MakeProcessor("\\[[^\\]]+\\]", "|", 1)
  }
  return defaultProcessor
}

///////////////////////////////////////////////////////////////////////////////
/// MARK: Methods
///////////////////////////////////////////////////////////////////////////////

func (p *Processor) PrepareVariants(text string) ([]string, [][]string, error) {
  all := p.collectionRegex.FindAllString(text, -1)
  if nil == all {
    return nil, nil, errorNoVariants
  }

  variants := make([][]string, len(all))
  for i, variant := range all {
    variants[i] = strings.Split(variant[p.borderSize:len(variant)-p.borderSize], p.separator)
  }
  return all, variants, nil
}

func PrepareVariants(text string) ([]string, [][]string, error) {
  return getDefaultProcessor().PrepareVariants(text)
}

func (p *Processor) ProcessRandom(text string, words *[]string) (string, error) {
  all, variants, err := p.PrepareVariants(text)
  if nil != err {
    return "", err
  }
  if nil == variants || len(variants) < 1 {
    return "", errorNoVariants
  }
  result, _, err := ProcessExt(text, all, variants, nil, words)
  return result, err
}

func ProcessRandom(text string, words *[]string) (string, error) {
  return getDefaultProcessor().ProcessRandom(text, words)
}

func ProcessExt(text string, raw_variants []string, variants [][]string, indexes []int, words *[]string) (string, bool, error) {
  var vr string
  for i, v := range raw_variants {
    if nil != indexes && len(indexes) > i {
      vr = variants[i][indexes[i]]
    } else {
      vr = variant(variants[i])
    }
    if nil != words {
      *words = append(*words, vr)
    }
    text = strings.Replace(text, v, vr, 1)
  }
  return text, incIndex(variants, indexes) /* can continue? */, nil
}

///////////////////////////////////////////////////////////////////////////////
/// MARK: Generators
///////////////////////////////////////////////////////////////////////////////

func (p *Processor) GenerateRandom(text string, count, try_count int, exclude bool) chan string {
  var excludes []string = nil
  if count < 1 {
    count = -1
    exclude = true
  }
  if try_count < 1 {
    try_count = 1
  }

  if exclude {
    excludes = make([]string, 0)
  }

  ch := make(chan string)

  go func() {
    raw_variants, variants, err := p.PrepareVariants(text)
    if nil == variants || len(variants) < 1 {
      err = errorNoVariants
    }

    if nil == err {
      for {
        if count == 0 {
          break
        }
        if count > 0 {
          count--
        }

        b := false
        for i := 0; i < try_count; i++ {
          s, _, e := ProcessExt(text, raw_variants, variants, nil, nil)
          if nil == e {
            if !containt(excludes, s) {
              if nil != excludes {
                excludes = append(excludes, s)
              }
              b = true
              ch <- s
              break
            }
          }
        } // end for

        if !b {
          break
        }
      }
    }
    close(ch)
  }()

  return ch
}

func GenerateRandom(text string, count, try_count int, exclude bool) chan string {
  return getDefaultProcessor().GenerateRandom(text, count, try_count, exclude)
}

func (p *Processor) Generate(text string, count int) chan string {
  if count < 1 {
    count = -1
  }

  ch := make(chan string)

  go func() {
    raw_variants, variants, err := p.PrepareVariants(text)
    if nil == variants || len(variants) < 1 {
      err = errorNoVariants
    }

    indexes := make([]int, len(raw_variants))

    if nil == err {
      for {
        if count == 0 {
          break
        }
        if count > 0 {
          count--
        }

        s, b, e := ProcessExt(text, raw_variants, variants, indexes, nil)
        if nil == e {
          ch <- s
        }
        if !b {
          break
        }
      }
    }
    close(ch)
  }()

  return ch
}

func Generate(text string, count int) chan string {
  return getDefaultProcessor().Generate(text, count)
}

///////////////////////////////////////////////////////////////////////////////
/// MARK: Helpers
///////////////////////////////////////////////////////////////////////////////

func variant(variants []string) string {
  return variants[randInt(0, len(variants)-1)]
}

func randInt(min int, max int) int {
  return min + rand.Intn(max-min)
}

func containt(arr []string, s string) bool {
  if nil != arr {
    for _, it := range arr {
      if it == s {
        return true
      }
    }
  }
  return false
}

func incIndex(variants [][]string, indexes []int) bool {
  if nil == variants || nil == indexes || len(indexes) < len(variants) {
    return true
  }
  last := len(variants) - 1
  return incIndexBy(last, variants, indexes)
}

func incIndexBy(i int, variants [][]string, indexes []int) bool {
  indexes[i]++
  if len(variants[i]) <= indexes[i] {
    if i < 1 {
      return false
    }
    indexes[i] = 0
    if i > 0 {
      return incIndexBy(i-1, variants, indexes)
    }
  }
  return true
}


text:
"""
Different methods to save the state, this allows for more modularity than just having a big switch statement in the main code.
Note that these classes are not subclasses of a more generic class, as this allows these classes to save data in a completely
different manner from each other. Furthermore, it avoids (slow) inheritance.
"""
from copy import deepcopy, copy
try:
    import cPickle as pickle
except ImportError:
    import pickle
import marshal

class DeepCopyState(object):
    """
    Class to save the state using the Python 'deepcopy' library
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = deepcopy(state)
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return deepcopy(self.state)

class CopyState(object):
    """
    Class to save the state using the Python 'copy' library
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = copy(state)
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return copy(self.state)

class AssignState(object):
    """
    Class to save the state using a simple assignment, is unsafe for most situations...
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = state
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return self.state

class PickleZeroState(object):
    """
    Class to save the state using the Python 'pickle' library, with the option to use the pickling protocol 0.
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = pickle.dumps(state, 0)
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return pickle.loads(self.state)

class PickleHighestState(object):
    """
    Class to save the state using the Python 'pickle' library, with the option to use the highest available pickling protocol.
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = pickle.dumps(state, pickle.HIGHEST_PROTOCOL)
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return pickle.loads(self.state)

class CustomState(object):
    """
    Class to save the state using a manually defined copy() function of the state. If no such method is provided, an error is raised.
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = state.copy()
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return self.state.copy()

class MarshalState(object):
    """
    Class to save the state using the Python 'marshal' library.
    """
    def __init__(self, time_last, time_next, state, activity, my_input, elapsed):
        """
        Constructor

        :param time_last: time_last to save
        :param time_next: time_next to save
        :param state: state to save
        :param activity: the activity of the computation
        :param my_input: the state input to save for memorisation
        :param elapsed: the time elapsed
        """
        self.time_last = time_last
        self.time_next = time_next
        self.activity = activity
        self.state = marshal.dumps(state)
        self.my_input = my_input
        self.elapsed = elapsed

    def loadState(self):
        """
        Load the state from the class, this will make a copy

        :returns: state - copy of the state that was saved
        """
        return marshal.loads(self.state)

redpajama_set_name: RedPajamaGithub


text:
package de.innosystec.unrar.exception;

/**
 * DOCUMENT ME
 *
 * @author $LastChangedBy$
 * @version $LastChangedRevision$
 */
public class RarException extends Exception
{
	private static final long serialVersionUID = 1L;
	private RarExceptionType type;

	public RarException(Exception e){
		super(RarExceptionType.unkownError.name(),e);
		this.type = RarExceptionType.unkownError;
	}

	public RarException(RarException e)
	{

		super(e.getMessage(),e);
		this.type = e.getType();
	}

	public RarException(RarExceptionType type){
		super(type.name());
		this.type = type;
	}

	public enum RarExceptionType{
		notImplementedYet,
		crcError,
		notRarArchive,
		badRarArchive,
		unkownError,
		headerNotInArchive,
		wrongHeaderType,
		ioError,
		rarEncryptedException ;
	}

	public RarExceptionType getType()
	{
		return type;
	}

	public void setType(RarExceptionType type)
	{
		this.type = type;
	}
}


text:
import { hasMany, Model } from 'miragejs';

export default Model.extend({
  categories: hasMany(),
  keywords: hasMany(),
  versions: hasMany(),
});


text:
.. _slf4j_configuration:

Logging Configuration
=====================

Each GeoMesa Tools distribution comes bundled by default with an SLF4J logging implementation that is installed
to the ``lib`` directory named ``slf4j-log4j12-1.7.5.jar``. If you already have an SLF4J implementation
installed on your Java classpath you may see errors at runtime and will have to exclude one of the JARs. This
can be accomplished by simply deleting the bundled ``slf4j-log4j12-1.7.5.jar``.

Note that if no SLF4J implementation is installed you will see this error:

.. code::

    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

In this case you may download SLF4J `here <http://www.slf4j.org/download.html>`__. Extract
``slf4j-log4j12-1.7.5.jar`` and place it in the ``lib`` directory of the binary distribution.
If this conflicts with another SLF4J implementation, you may need to remove it from the ``lib`` directory.


text:
#import <Foundation/NSObject.h>
#import <AppKit/AppKitExport.h>

@class NSURL,NSBundle,NSDictionary,NSArray,NSData,NSMutableArray;

APPKIT_EXPORT NSString *NSNibOwner;
APPKIT_EXPORT NSString *NSNibTopLevelObjects;

@interface NSNib : NSObject {
   NSData *_data;
   NSMutableArray *_allObjects;
   NSDictionary *_nameTable;
}

-initWithContentsOfURL:(NSURL *)url;
-initWithNibNamed:(NSString *)name bundle:(NSBundle *)bundle;

-(BOOL)instantiateNibWithExternalNameTable:(NSDictionary *)nameTable;
-(BOOL)instantiateNibWithOwner:owner topLevelObjects:(NSArray **)objects;

@end


text:
package android.util;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SparseArray<T> {

	private Map<Integer, T> mMap = new HashMap<Integer, T>();
	private List<Integer> mOrderedKeys = new LinkedList<Integer>();

	@Override
	public SparseArray<T> clone() {
		SparseArray<T> cloned = new SparseArray<T>();

		cloned.mMap.putAll(mMap);
		cloned.mOrderedKeys.addAll(mOrderedKeys);

		return cloned;
	}

	public void put(int key, T value) {

		if (!mMap.containsKey(key)) {
			mOrderedKeys.add(key);
		}

		mMap.put(key, value);

	}

	public T get(int key, T defaultValue) {

		if ( mMap.containsKey(key)) {
			return mMap.get(key);
		} else {
			return defaultValue;
		}
	}

	public T get(int key) {
		return mMap.get(key);
	}

	public int indexOfKey(int i) {
		return mOrderedKeys.indexOf(i);
	}

	public T valueAt(int i) {
		return mMap.get(mOrderedKeys.get(i));
	}

	public int size() {
		return mOrderedKeys.size();
	}

	public int keyAt(int i) {
		return mOrderedKeys.get(i);
	}

}


text:
This is the main config used by core/bootstrap.js. You can take a look in there to see what is happening,
but the process is pretty straight forward. Here is an explanation of the keys you will find in the config.

- **default|dev|\***: The environment. 'default' is used by all, 'dev' will inherit from 'default'. The inheritance is simple
and runs up the config, e.g. adding a 'staging' key between 'default' and 'dev' and including altair/plugins/config?/path/to/config?env=staging
will load 'staging' first, then mixin 'default.' If you did ?env=dev, it would start with 'dev,' mixin 'staging,' then
mixin 'default.'
- **default.paths**: These paths are used throughout Altair for loading and forging. These paths are mapped into the global path resolver,
e.g. require('core/other/thing') will resolve 'core' to node_modules/altair.io/core. They are saved in the main Altair
instance as an array of the aliases (i.e. altair.paths = ['app', 'community', 'local']). The module cartridge will use these
paths for modules to instantiate.
- **default.cartidges**: Altair, at its heart, is a simple cartridge loader. This is an array of cartridges you will be loading.
- **default.cartidges.path**: This is the path to the cartridge you want to load.
- **default.cartidges.options**: This is the path to the cartridge you want to load.


text:
package org.hisp.dhis.dxf2.events.importer.mapper;

import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.hisp.dhis.common.IdScheme.CODE;
import static org.hisp.dhis.common.IdScheme.UID;
import static org.hisp.dhis.event.EventStatus.fromInt;
import static org.hisp.dhis.util.DateUtils.parseDate;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.events.event.Event;
import org.hisp.dhis.dxf2.events.importer.context.WorkContext;
import org.hisp.dhis.eventdatavalue.EventDataValue;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.trackedentitycomment.TrackedEntityComment;

/**
 * @author Luciano Fiandesio
 */
public class ProgramStageInstanceMapper extends AbstractMapper<Event, ProgramStageInstance>
{
    private final ProgramStageInstanceNoteMapper noteMapper;

    public ProgramStageInstanceMapper( WorkContext ctx )
    {
        super( ctx );
        noteMapper = new ProgramStageInstanceNoteMapper( ctx );
    }

    @Override
    public ProgramStageInstance map( Event event )
    {
        ProgramStageInstance psi = workContext.getProgramStageInstanceMap().get( event.getUid() );

        if ( psi == null )
        {
            psi = mapForInsert( event );
        }
        else
        {
            mapForUpdate( event, psi );
        }

        return mapDataValueIdentifier( psi, super.workContext.getDataElementMap() );
    }

    /**
     * Set data element identifier to uid. We run the psi through this method to
     * make sure data value identifiers are UID. Otherwise, we would store data
     * values with whatever identifier is used for import, for example CODE or
     * ATTRIBUTE.
     *
     * @param psi the psi with the datavalues to normalize to uid identifiers
     * @param dataElementMap a map of persisted data elements.
     * @return a program stage instance with normalized data values.
     */
    private ProgramStageInstance mapDataValueIdentifier( ProgramStageInstance psi,
        Map<String, DataElement> dataElementMap )
    {
        for ( EventDataValue dv : psi.getEventDataValues() )
        {
            DataElement de = dataElementMap.get( dv.getDataElement() );
            if ( de != null )
            {
                dv.setDataElement( de.getUid() );
            }
        }
        return psi;
    }

    private ProgramStageInstance mapForUpdate( Event event, ProgramStageInstance psi )
    {
        // Program Instance
        workContext.getProgramInstance( event.getUid() ).ifPresent( psi::setProgramInstance );

        // Program Stage
        getProgramStage( event ).ifPresent( psi::setProgramStage );

        // Org Unit
        getOrganisationUnit( event ).ifPresent( psi::setOrganisationUnit );

        // Status and completed date are set in the Update Preprocessor //

        // Attribute Option Combo
        psi.setAttributeOptionCombo( this.workContext.getCategoryOptionComboMap().get( event.getUid() ) );

        // Geometry
        psi.setGeometry( event.getGeometry() );

        // Notes
        if ( !event.getNotes().isEmpty() )
        {
            psi.setComments( convertNotes( event, this.workContext ) );
        }

        // Data Values
        psi.setEventDataValues( workContext.getEventDataValueMap().get( event.getUid() ) );

        if ( event.getDueDate() != null )
        {
            psi.setDueDate( parseDate( event.getDueDate() ) );
        }

        setExecutionDate( event, psi );

        if ( psi.getProgramStage() != null && psi.getProgramStage().isEnableUserAssignment() )
        {
            psi.setAssignedUser( this.workContext.getAssignedUserMap().get( event.getUid() ) );
        }

        // CREATED AT CLIENT + UPDATED AT CLIENT
        psi.setCreatedAtClient( parseDate( event.getCreatedAtClient() ) );
        psi.setLastUpdatedAtClient( parseDate( event.getLastUpdatedAtClient() ) );

        psi.setStoredBy( event.getStoredBy() );
        psi.setCompletedBy( event.getCompletedBy() );

        psi.setLastUpdatedByUserInfo( event.getLastUpdatedByUserInfo() );

        return psi;
    }

    public ProgramStageInstance mapForInsert( Event event )
    {
        ImportOptions importOptions = workContext.getImportOptions();

        ProgramStageInstance psi = new ProgramStageInstance();

        if ( importOptions.getIdSchemes().getProgramStageInstanceIdScheme().equals( CODE ) )
        {
            psi.setCode( event.getEvent() );
        }
        else if ( importOptions.getIdSchemes().getProgramStageIdScheme().equals( UID ) )
        {
            psi.setUid( event.getUid() );
        }

        // Program Instance
        psi.setProgramInstance( this.workContext.getProgramInstanceMap().get( event.getUid() ) );

        // Program Stage
        psi.setProgramStage( this.workContext.getProgramStage( importOptions.getIdSchemes().getProgramStageIdScheme(),
            event.getProgramStage() ) );

        // Org Unit
        psi.setOrganisationUnit( this.workContext.getOrganisationUnitMap().get( event.getUid() ) );

        // Status
        psi.setStatus( fromInt( event.getStatus().getValue() ) );

        // Attribute Option Combo
        psi.setAttributeOptionCombo( this.workContext.getCategoryOptionComboMap().get( event.getUid() ) );

        // Geometry
        psi.setGeometry( event.getGeometry() );

        // Notes
        psi.setComments( convertNotes( event, this.workContext ) );

        // Data Values
        psi.setEventDataValues( workContext.getEventDataValueMap().get( event.getUid() ) );

        Date dueDate = new Date();

        if ( event.getDueDate() != null )
        {
            dueDate = parseDate( event.getDueDate() );
        }

        psi.setDueDate( dueDate );
        setCompletedDate( event, psi );
        // Note that execution date can be null
        setExecutionDate( event, psi );

        if ( psi.getProgramStage() != null && psi.getProgramStage().isEnableUserAssignment() )
        {
            psi.setAssignedUser( this.workContext.getAssignedUserMap().get( event.getUid() ) );
        }

        // CREATED AT CLIENT + UPDATED AT CLIENT
        psi.setCreatedAtClient( parseDate( event.getCreatedAtClient() ) );
        psi.setLastUpdatedAtClient( parseDate( event.getLastUpdatedAtClient() ) );

        psi.setStoredBy( event.getStoredBy() );
        psi.setCompletedBy( event.getCompletedBy() );

        psi.setCreatedByUserInfo( event.getCreatedByUserInfo() );
        psi.setLastUpdatedByUserInfo( event.getLastUpdatedByUserInfo() );

        return psi;
    }

    private List<TrackedEntityComment> convertNotes( Event event, WorkContext ctx )
    {
        if ( isNotEmpty( event.getNotes() ) )
        {
            return event.getNotes().stream().filter( note -> ctx.getNotesMap().containsKey( note.getNote() ) )
                .map( noteMapper::map ).collect( toList() );
        }

        return emptyList();
    }

    private Optional<ProgramStage> getProgramStage( Event event )
    {
        return Optional.ofNullable( this.workContext.getProgramStage(
            this.workContext.getImportOptions().getIdSchemes().getProgramStageIdScheme(), event.getProgramStage() ) );
    }

    private Optional<OrganisationUnit> getOrganisationUnit( Event event )
    {
        return Optional.ofNullable( this.workContext.getOrganisationUnitMap().get( event.getUid() ) );
    }

    private void setExecutionDate( Event event, ProgramStageInstance psi )
    {
        if ( event.getEventDate() != null )
        {
            psi.setExecutionDate( parseDate( event.getEventDate() ) );
        }
    }

    private void setCompletedDate( Event event, ProgramStageInstance psi )
    {
        // Completed Date // FIXME this logic should be moved to a preprocessor
        if ( psi.isCompleted() )
        {
            Date completedDate = new Date();
            if ( event.getCompletedDate() != null )
            {
                completedDate = parseDate( event.getCompletedDate() );
            }
            psi.setCompletedDate( completedDate );
        }
    }
}


text:
package ru.job4j;
/**
 @Class : Управление игровыми объектами (Marine)
 @param :  mode_id и int x,int y,Marine obj
 @return name : shot_status_id

 */
public class GameObjects extends Game {
    Marine mashinUser;
    Marine User_1;
    Marine User_2;
    public void Buildobjects(int mode_id){
if(mode_id==1) {
    mashinUser = new Marine();
    mashinUser.buildmarine();
    User_1=new Marine();
    User_1.buildusermarine();
}else {
    User_1=new Marine();
    User_1.buildusermarine();

    User_2=new Marine();
    User_2.buildusermarine();
}

    }
    public int checkShot(int x,int y,Marine obj){
        if(obj.alivemarine()) {
            int result = obj.checkShot(x, y);
            return result;
        }else {return -100;}

    }
}


text:
var App = Em.Application.create({});

App.ApplicationView  = Ember.View.extend({
	templateName: 'application-view'
});
App.TextItem = Ember.Object.extend({
    value: "defaultItemName"
});
App.TextItemController = Ember.ArrayProxy.extend({
});

App.TypesView =  Ember.View.extend({
	templateName: 'type-view',
	tagName:'div',
	content: App.TextItemController.create({
		content: []
	}),
	init: function(){
		this.set('content',App.TextItemController.create({content: []}));
		return this._super();
	},
	addType: function(e,view){
		var theType = this;
		_gaq.push(['_trackEvent', 'AddType', 'Clicked: ' +  this.label]);
		var modal = App.ModalView.create({modify: this});
	},
	removeType: function(e){
		this.get('content').removeObject(e.context);
		_gaq.push(['_trackEvent', 'RemoveType', 'Clicked']);
	}
});
App.ModalView =  Ember.View.extend({
	templateName: 'modal-view',
	tagName:'div',
	classNames: 'modal hide fade',
	modify: undefined,
	init: function(){
		var theType=this.get('modify');
		var This = this;
		this.append();
		setTimeout(function(){
			$('.modal').modal('show');
			$('.modal').on('shown', function(){
				$('#theAdd').focus();
			});
			$('.modal').on('hidden', function(){
				$('.modal').remove();
				This.destroy();
			});
			$('.btn-primary,form').on('click submit', function(e){
				e.preventDefault();
				_gaq.push(['_trackEvent', 'AddType', 'Saved: ' + theType.get('label')]);
				theType.content.pushObject(App.TextItem.create({value:$('#theAdd').val()}));
				$('.modal').modal('hide');
			});
		},50);
	}
});
App.ApplicationController   = Ember.Controller.extend({});
var router = Ember.Router.create({
	root: Ember.Route.extend({
		index: Ember.Route.extend({
			route: '/',
			enter: function(router) {
			},
			connectOutlets: function (router, context) {
				router.get('applicationController').connectOutlet('application');
			}
		})
	})
});
App.initialize(router);


text:
case node['platform_family']
when 'rhel', 'fedora'
  case node['platform']
  when 'centos'
    # See http://wiki.nginx.org/Install
    default['nginx']['upstream_repository'] = "http://nginx.org/packages/centos/#{node['platform_version'].to_i}/$basearch/"
  else
    default['nginx']['upstream_repository'] = "http://nginx.org/packages/rhel/#{node['platform_version'].to_i}/$basearch/"
  end
when 'debian'
  default['nginx']['upstream_repository'] = "http://nginx.org/packages/#{node['platform']}"
end


text:
package io.github.interestinglab.waterdrop.filter

import io.github.interestinglab.waterdrop.apis.BaseFilter
import io.github.interestinglab.waterdrop.config.{Config, ConfigFactory}
import org.apache.spark.sql.{Dataset, Row, SparkSession}
import org.apache.spark.sql.functions.{col, udf}

import scala.collection.JavaConversions._
import java.net.URLDecoder

import org.apache.spark.sql.expressions.UserDefinedFunction

class URLDecode extends BaseFilter {

  var conf: Config = ConfigFactory.empty()

  /**
   * Set Config.
   * */
  override def setConfig(config: Config): Unit = {
    this.conf = config
  }

  /**
   * Get Config.
   * */
  override def getConfig(): Config = {
    this.conf
  }

  override def getUdfList(): List[(String, UserDefinedFunction)] = {
    val func = udf((source: String) => URLDecoder.decode(source, "utf-8"))
    List(("urldecode", func))
  }

  override def checkConfig(): (Boolean, String) = (true, "")

  override def prepare(spark: SparkSession): Unit = {
    super.prepare(spark)
    val defaultConfig = ConfigFactory.parseMap(
      Map(
        "source_field" -> "raw_message"
      )
    )
    conf = conf.withFallback(defaultConfig)
  }

  override def process(spark: SparkSession, df: Dataset[Row]): Dataset[Row] = {
    val decodeFunc = getUdfList().get(0)._2
    val sourceField = conf.getString("source_field")
    var targetField = sourceField
    if (conf.hasPath("target_field")) {
      targetField = conf.getString("target_field")
    }
    df.withColumn(conf.getString("target_field"), decodeFunc(col(sourceField)))
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace ExtendedControls
{
    public class TextBoxBorder : TextBox
    {
        public Color BorderColor { get; set; } = Color.Transparent;
        public float BorderColorScaling { get; set; } = 0.5F;           // Popup style only
        public int BorderOffset = 3;

        public TextBoxBorder() : base()
        {
        }

        private const int WM_PAINT = 15;

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == WM_PAINT)          // Stupid control does not have a OnPaint
            {
                if (BorderColor != Color.Transparent)
                {
                    Graphics g = Parent.CreateGraphics();

                    Rectangle clientborder = new Rectangle(Location.X - BorderOffset, Location.Y - BorderOffset, ClientRectangle.Width + BorderOffset*2, ClientRectangle.Height + BorderOffset*2);

                    Color color1 = BorderColor;
                    Color color2 = Multiply(BorderColor, BorderColorScaling);

                    GraphicsPath g1 = RectCutCorners(clientborder.X + 1, clientborder.Y+1, clientborder.Width - 2, clientborder.Height - 1, 1, 1);
                    using (Pen pc1 = new Pen(color1, 1.0F))
                        g.DrawPath(pc1, g1);

                    GraphicsPath g2 = RectCutCorners(clientborder.X, clientborder.Y, clientborder.Width, clientborder.Height - 1, 2, 2);
                    using (Pen pc2 = new Pen(color2, 1.0F))
                        g.DrawPath(pc2, g2);

                    g.Dispose();
                }
            }
        }

        private GraphicsPath RectCutCorners(int x, int y, int width, int height, int roundnessleft, int roundnessright)
        {
            GraphicsPath gr = new GraphicsPath();

            gr.AddLine(x + roundnessleft, y, x + width - 1 - roundnessright, y);
            gr.AddLine(x + width - 1, y + roundnessright, x + width - 1, y + height - 1 - roundnessright);
            gr.AddLine(x + width - 1 - roundnessright, y + height - 1, x + roundnessleft, y + height - 1);
            gr.AddLine(x, y + height - 1 - roundnessleft, x, y + roundnessleft);
            gr.AddLine(x, y + roundnessleft, x + roundnessleft, y);         // close figure manually, closing it with a break does not seem to work
            return gr;
        }

        private byte limit(float a) { if (a > 255F) return 255; else return (byte)a; }
        public Color Multiply(Color from, float m) { return Color.FromArgb(from.A, limit((float)from.R * m), limit((float)from.G * m), limit((float)from.B * m)); }
    }

}


text:
package io.agora.chatdemo.group;

import io.agora.GroupChangeListener;
import io.agora.chat.MucSharedFile;
import java.util.List;

/**
 * Created by benson on 2016/10/31.
 */
public abstract class AgoraGroupChangeListener implements GroupChangeListener {

    /*!
     * current user receive group invitation
     * @param s The group ID.
     * @param s1 group's name
     * @param s2 Who invite you join the group
     * @param s3 Literal message coming with the invitation
     */
    @Override public void onInvitationReceived(String s, String s1, String s2, String s3) {}

    /*
     * some one want to join the group.
     * @param s The group ID
     * @param s1 group's name
     * @param s2 The applicant want to join the group
     * @param s3 Literal message coming with the application
     */
    @Override public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {}

    /*
     * Join group's application has been approved
     * @param s The group ID
     * @param s1 group's name
     * @param s2 who approve the application
     */

    @Override public void onRequestToJoinAccepted(String s, String s1, String s2) {}

    /*!
     * Join group's application has been declined
     * @param s The group ID
     * @param s1 group's name
     * @param s2 decliner's username
     * @param s3 decline reason
     */
    @Override public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {}

    /*
     * invite some one to be member of group, and the user has accept the invitation
     * @param s The group ID
     * @param s1 invitee
     * @param s2 reason
     */

    @Override public void onInvitationAccepted(String s, String s1, String s2) {}

    /*
     * invite some one to be member of group, and the user has decline the invitation
     * @param groupId The group ID
     * @param invitee
     * @param reason refuse reason
     */
    @Override public void onInvitationDeclined(String s, String s1, String s2) {}

    /*!
     * current user has been remove from the group
     * @param s groupId
     * @param s1 groupName
     */
    @Override public void onUserRemoved(String s, String s1) {}

    /*!
     * @param s groupId
     * @param s1 groupName
     *
     * group dissolution
     * SDK will delete the group from local DB and local memory cache, then notify user this group has been destroyed
     */
    @Override public void onGroupDestroyed(String s, String s1) {}

    /*!
     * @param s groupId
     * @param s1 inviter
     * @param s2 inviteMessage
     *
     * When receive group join invitation, will auto accept it, and join the group.
     * Please refer to {@link io.agora.chat.ChatOptions.setAutoAcceptGroupInvitation(boolean value)}
     */
    @Override public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {
    }

    /**
     * Callback when group member(s) is muted (added to mute list), and is not allowed to post message temporarily based on muted
     * time duration
     *
     * @param groupId group id
     * @param mutes member(s) added to mute list Map.entry.key is muted username. Map.entry.value is the duration of muted time,
     * in milliseconds
     * @return NA
     */
    @Override public void onMuteListAdded(String groupId, final List<String> mutes, final long muteExpire) {
    }

    /**
     * Callback when group member(s) is unmuted (removed from mute list), and allow to post message now
     *
     * @param groupId group id
     * @param mutes members that be removed from mute list
     * @return NA
     */
    @Override public void onMuteListRemoved(String groupId, final List<String> mutes) {
    }

    /**
     * Callback when a member has been changed to admin
     *
     * @param groupId group id
     * @param administrator member who has been changed to admin
     */
    @Override public void onAdminAdded(String groupId, String administrator) {
    }

    /**
     * Callback when member is removed from admin
     *
     * @param groupId group id
     * @param administrator the member whose admin permission is removed
     * @return NA
     */
    @Override public void onAdminRemoved(String groupId, String administrator) {
    }

    /**
     * Callback when chat room ownership has been transferred
     *
     * @param groupId group id
     * @param newOwner new owner
     * @param oldOwner previous owner
     * @return NA
     */
    @Override public void onOwnerChanged(String groupId, String newOwner, String oldOwner) {
    }

    /**
     * Callback when a member join the group.
     *
     * @param groupId group id
     * @param member new member's id
     */
    @Override public void onMemberJoined(final String groupId, final String member) {
    }

    /**
     * Callback when a member exited the group
     *
     * @param groupId group id
     * @param member the member who exited the group
     */
    @Override public void onMemberExited(final String groupId, final String member) {
    }

    @Override public void onAnnouncementChanged(String groupId, String announcement) {

    }

    @Override public void onSharedFileAdded(String groupId, MucSharedFile sharedFile) {

    }

    @Override public void onSharedFileDeleted(String groupId, String fileId) {

    }
}


text:
RSpec.describe Metasploit::Credential::Exporter::Core do

  include_context 'export objects'

  subject(:core_exporter){ Metasploit::Credential::Exporter::Core.new(workspace: workspace) }

  before(:example) do
    origin.task = nil
  end

  #
  # Clean up generated files/paths
  #
  after(:example) do
    Dir.glob("#{Dir.tmpdir}/metasploit*").each {|d| FileUtils.rm_rf d}
  end

  describe "initialization" do
    it 'should raise an exception if initialized with an invalid mode' do
      expect{ Metasploit::Credential::Exporter::Core.new(mode: :fail_mode) }.to raise_error(RuntimeError)
    end

    it 'should be in LOGIN_MODE by default' do
      expect(core_exporter.mode).to eq(Metasploit::Credential::Exporter::Core::LOGIN_MODE)
    end
  end

  describe "#export!" do
    it 'should create the zipfile' do
      core_exporter.export!
      expect(File.exist?(core_exporter.output_zipfile_path)).to eq(true)
    end

    it 'should output to a directory whose name contains the standardized identifier' do
      core_exporter.export!
      expect(core_exporter.output_final_directory_path).to include(Metasploit::Credential::Exporter::Core::CREDS_DUMP_FILE_IDENTIFIER)
    end
  end

  describe "#key_path" do
    let(:key_path_basename_string){ "#{core.public.username}-#{core.private.id}" }

    describe "when the argument is a Core" do
      it 'should be formed from the Public#username and the Private#id' do
        key_path = core_exporter.path_for_key(core)
        expect(Pathname.new(key_path).basename.to_s).to eq(key_path_basename_string)
      end
    end

    describe "when the argument is a Login" do
      it 'should be formed from the Public#username and the Private#id' do
        key_path = core_exporter.path_for_key(login)
        expect(Pathname.new(key_path).basename.to_s).to eq(key_path_basename_string)
      end
    end
  end

  describe "#line_for_core" do
    let(:result_hash) { core_exporter.line_for_core(core) }

    it 'should produce values in the proper order' do
      expect(result_hash.values).to eq(
                                        [
                                            core.public.username,
                                            core.private.type,
                                            core.private.data,
                                            core.realm.key,
                                            core.realm.value
                                        ]
                                    )
    end

    it 'should produce a hash with the public username' do
      expect(result_hash[:username]).to eq(core.public.username)
    end

    it 'should produce a hash with the private data' do
      expect(result_hash[:private_data]).to eq(core.private.data)
    end

    it 'should produce a hash with the name of the private type' do
      expect(result_hash[:private_type]).to eq(core.private.type)
    end
  end

  describe "#line_for_login" do
    let(:login){ FactoryBot.create(:metasploit_credential_login, core: core, service: service) }
    let(:result_hash) { core_exporter.line_for_login(login) }

    it 'should produce values in the proper order' do
      expect(result_hash.values).to eq(
                                        [
                                            core.public.username,
                                            core.private.type,
                                            core.private.data,
                                            core.realm.key,
                                            core.realm.value,
                                            login.service.host.address,
                                            login.service.port,
                                            login.service.name,
                                            login.service.proto,
                                            login.status,
                                            login.access_level,
                                            login.last_attempted_at
                                        ]
                                    )
    end

    it 'should produce a hash with the service host address' do
      expect(result_hash[:host_address]).to eq(login.service.host.address.to_s)
    end

    it 'should produce a hash with the service port' do
      expect(result_hash[:service_port]).to eq(login.service.port)
    end

    it 'should produce a hash with the service name' do
      expect(result_hash[:service_name]).to eq(login.service.name)
    end

    it 'should produce a hash with the service protocol' do
      expect(result_hash[:service_protocol]).to eq(login.service.proto)
    end

    it 'should produce a hash with the login status' do
      expect(result_hash[:status]).to eq(login.status)
    end

    it 'should produce a hash with the login access_level' do
      expect(result_hash[:access_level]).to eq(login.access_level)
    end

    it 'should produce a hash with the login last_attempted_at' do
      expect(result_hash[:last_attempted_at]).to eq(login.last_attempted_at)
    end

    it 'should produce a hash with the public information' do
      expect(result_hash[:username]).to eq(login.core.public.username)
    end

    it 'should produce a hash with the private data' do
      expect(result_hash[:private_data]).to eq(login.core.private.data)
    end

    it 'should produce a hash with the demodulized name of the private type' do
      expect(result_hash[:private_type]).to eq(login.core.private.type)
    end
  end

  describe "#output" do
    it 'should be a writable File' do
      file_stat = core_exporter.output.stat
      expect(file_stat).to be_writable
    end

    it 'should not be opened in binmode' do
      expect(core_exporter.output).not_to be_binmode
    end
  end

  describe "#output_directory_path" do
    it 'should be in the platform-agnostic temp directory' do
      expect(core_exporter.output_final_directory_path).to include(Dir.tmpdir)
    end

    it 'should have the set export prefix' do
      expect(core_exporter.output_final_directory_path).to include(Metasploit::Credential::Exporter::Core::TEMP_ZIP_PATH_PREFIX)
    end

    describe "uniqueness for export" do
      let(:path_fragment){ "export-#{Time.now.to_s}" }

      before(:example) do
        allow(core_exporter).to receive(:output_final_subdirectory_name).and_return(path_fragment)
      end

      it 'should include a special time-stamped directory to contain the export data being staged' do
        expect(core_exporter.output_final_directory_path).to include(core_exporter.output_final_subdirectory_name)
      end
    end
  end

  describe "#data" do
    describe "in LOGIN_MODE" do
      before(:example) do
        allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::LOGIN_MODE
      end

      describe "when whitelist_ids is present" do
        before(:example) do
          allow(core_exporter).to receive(:whitelist_ids).and_return([login1.id])
        end

        it 'should contain only those objects whose IDs are in the whitelist' do
          expect(core_exporter.data).not_to include(login2)
        end
      end

      describe "when whitelist_ids is blank" do
        it 'should be the same as #export_data' do
          expect(core_exporter.data).to eq(core_exporter.export_data)
        end
      end
    end

    describe "in CORE_MODE" do
      before(:example) do
        allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::CORE_MODE
      end

      describe "when whitelist_ids is present" do
        before(:example) do
          allow(core_exporter).to receive(:whitelist_ids).and_return([core1.id])
        end

        it 'should contain only those objects whose IDs are in the whitelist' do
          expect(core_exporter.data).not_to include(core2)
        end
      end

      describe "when whitelist_ids is blank" do
        it 'should be the same as #export_data' do
          expect(core_exporter.data).to eq(core_exporter.export_data)
        end
      end
    end
  end

  describe "#export_data" do
    describe "in CORE_MODE" do
      before(:example) do
        allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::CORE_MODE
      end

      it 'should grab data using the proper scope' do
        expect(Metasploit::Credential::Core).to receive(:workspace_id).with(core_exporter.workspace.id)
        core_exporter.export_data
      end
    end

    describe "in LOGIN_MODE" do
      before(:example) do
        allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::LOGIN_MODE
      end

      it 'should grab data using the proper scope' do
        expect(Metasploit::Credential::Login).to receive(:in_workspace_including_hosts_and_services).with(core_exporter.workspace)
        core_exporter.export_data
      end
    end
  end

  describe "generation" do
    describe "#render_manifest_and_output_keys" do
      describe "in CORE_MODE" do
        before(:example) do
          allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::CORE_MODE
          core_exporter.render_manifest_output_and_keys
          path = core_exporter.output_final_directory_path + '/' + Metasploit::Credential::Importer::Zip::MANIFEST_FILE_NAME

          @core_publics            = []
          @core_private_data       = []
          @core_private_types      = []
          @core_realm_keys         = []
          @core_realm_values       = []

          CSV.new(File.open(path), headers:true).each do |row|
            @core_publics            << row['username']
            @core_private_data       << row['private_data']
            @core_private_types      << row['private_type']
            @core_realm_keys         << row['realm_key']
            @core_realm_values       << row['realm_value']
          end
        end

        it 'should contain the Public#username for all Core objects' do
          expect(@core_publics).to include(core1.public.username)
          expect(@core_publics).to include(core2.public.username)
        end

        it 'should contain the Private#type for all Core objects' do
          expect(@core_private_types).to include(core1.private.type)
          expect(@core_private_types).to include(core2.private.type)
        end

        it 'should contain the Private#data for all Core objects' do
          expect(@core_private_data).to include(core1.private.data)
          expect(@core_private_data).to include(core2.private.data)
        end

        it 'should contain the Realm#key for all Core objects' do
          expect(@core_realm_keys).to include(core1.realm.key)
          expect(@core_realm_keys).to include(core2.realm.key)
        end

        it 'should contain the Realm#value for all Core objects' do
          expect(@core_realm_values).to include(core1.realm.value)
          expect(@core_realm_values).to include(core2.realm.value)
        end
      end

      describe "in LOGIN_MODE" do
        before(:example) do
          allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::LOGIN_MODE
          core_exporter.render_manifest_output_and_keys
          path = core_exporter.output_final_directory_path + '/' + Metasploit::Credential::Importer::Zip::MANIFEST_FILE_NAME

          @login_publics            = []
          @login_private_data       = []
          @login_private_types      = []
          @login_realm_keys         = []
          @login_realm_values       = []
          @login_host_addresses     = []
          @login_service_ports      = []
          @login_service_names      = []
          @login_service_protocols  = []

          CSV.new(File.open(path), headers:true).each do |row|
            @login_publics            << row['username']
            @login_private_data       << row['private_data']
            @login_private_types      << row['private_type']
            @login_realm_keys         << row['realm_key']
            @login_realm_values       << row['realm_value']
            @login_host_addresses     << row['host_address']
            @login_service_ports      << row['service_port']
            @login_service_names      << row['service_name']
            @login_service_protocols  << row['service_protocol']
          end
        end

        it 'should contain the Public#username for all Login objects' do
          expect(@login_publics).to include(login1.core.public.username)
          expect(@login_publics).to include(login2.core.public.username)
        end

        it 'should contain the Private#type for all Login objects' do
          expect(@login_private_types).to include(login1.core.private.type)
          expect(@login_private_types).to include(login2.core.private.type)
        end

        it 'should contain the Private#data for all Login objects' do
          expect(@login_private_data).to include(login1.core.private.data)
          expect(@login_private_data).to include(login2.core.private.data)
        end

        it 'should contain the Realm#key for all Login objects' do
          expect(@login_realm_keys).to include(login1.core.realm.key)
          expect(@login_realm_keys).to include(login2.core.realm.key)
        end

        it 'should contain the Realm#value for all Login objects' do
          expect(@login_realm_values).to include(login1.core.realm.value)
          expect(@login_realm_values).to include(login2.core.realm.value)
        end

        it 'should contain the associated Mdm::Host#address for all Login objects' do
          expect(@login_host_addresses).to include(login1.service.host.address.to_s, login2.service.host.address.to_s)
        end

        it 'should contain the associated Mdm::Service#port (stringified) for all Login objects' do
          expect(@login_service_ports).to include(login1.service.port.to_s)
          expect(@login_service_ports).to include(login2.service.port.to_s)
        end

        it 'should contain the associated Mdm::Service#name for all Login objects' do
          expect(@login_service_names).to include(login1.service.name)
          expect(@login_service_names).to include(login2.service.name)
        end

        it 'should contain the associated Mdm::Service#proto for all Login objects' do
          expect(@login_service_protocols).to include(login1.service.proto)
          expect(@login_service_protocols).to include(login2.service.proto)
        end
      end
    end

    describe "#render_zip" do
      describe "when there are no SSH keys in the dataset" do
        before(:example) do
          allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::CORE_MODE
          core_exporter.render_manifest_output_and_keys
          core_exporter.render_zip
        end

        it 'should contain the manifest file' do
          manifest_entry = nil
          Zip::File.open(core_exporter.output_zipfile_path) do |zip_file|
            manifest_entry = zip_file.glob(Metasploit::Credential::Importer::Zip::MANIFEST_FILE_NAME).first
          end
          expect(manifest_entry).not_to be_blank
        end

        it 'should not contain a keys directory' do
          keys_entry = nil
          Zip::File.open(core_exporter.output_zipfile_path) do |zip_file|
            keys_entry = zip_file.glob(Metasploit::Credential::Importer::Zip::KEYS_SUBDIRECTORY_NAME).first
          end
          expect(keys_entry).to be_blank
        end
      end

      describe "when there ARE SSH keys in the dataset" do
        let(:private_with_key){ FactoryBot.create(:metasploit_credential_ssh_key)}
        let!(:core_with_key){ FactoryBot.create(:metasploit_credential_core,
                                                 origin: origin,
                                                 public: public1,
                                                 private: private_with_key,
                                                 workspace: workspace)}

        before(:example) do
          allow(core_exporter).to receive(:mode).and_return Metasploit::Credential::Exporter::Core::CORE_MODE
          core_exporter.render_manifest_output_and_keys
          core_exporter.render_zip
        end

        it 'should contain the manifest file' do
          manifest_entry = nil
          Zip::File.open(core_exporter.output_zipfile_path) do |zip_file|
            manifest_entry = zip_file.glob(Metasploit::Credential::Importer::Zip::MANIFEST_FILE_NAME).first
          end
          expect(manifest_entry).not_to be_blank
        end

        it 'should contain a keys directory' do
          keys_entry = nil
          Zip::File.open(core_exporter.output_zipfile_path) do |zip_file|
            keys_entry = zip_file.glob(Metasploit::Credential::Importer::Zip::KEYS_SUBDIRECTORY_NAME).first
          end
          expect(keys_entry).not_to be_blank
        end

        describe "the keys directory" do
          before(:example) do
            @key_entries = nil
            Zip::File.open(core_exporter.output_zipfile_path) do |zip_file|
              @key_entries = zip_file.glob("#{Metasploit::Credential::Importer::Zip::KEYS_SUBDIRECTORY_NAME}/*")
            end
          end

          it 'should contain a key for each SSH private in the export' do
            expect(@key_entries.size).to eq(core_exporter.data[:core].select{ |d| d.private.type == Metasploit::Credential::SSHKey.name }.size)
          end

          it 'should contain key files named with Public#username and Private#id for each Core that uses an SSHKey' do
            key_names = @key_entries.map{ |e| e.to_s.gsub("#{Metasploit::Credential::Importer::Zip::KEYS_SUBDIRECTORY_NAME}/", '') }
            expect(key_names).to include("#{core_with_key.public.username}-#{core_with_key.private.id}")
          end

        end
      end
    end
  end
end


text:
<?php include "head.php" ?>
<?php
session_start();
include "connection.php";
if (!empty($_POST["findhome"])) {
  $findhome = $_POST["findhome"];
}
if (!empty($_POST["findFname"])) {
  $findFname = $_POST["findFname"];
}
if (!empty($_POST["findLname"])) {
  $findLname = $_POST["findLname"];
}
if (!empty($_POST["sex"])) {
  $sex = $_POST["sex"];
}
if (!empty($_POST["age"])) {
  $age = $_POST["age"];
}
?>

      บ้านเลขที่ :
      <?php
        if (!empty($_POST["findhome"])) {
            $vilno = "SELECT HomeNo FROM home WHERE HomeNo = '$findhome' ";
            $resultVilno = mysqli_query($con,$vilno);
            $resno = mysqli_fetch_assoc($resultVilno);
            echo $resno["HomeNo"];
        } else {
            echo "-";
        }
          ?>

        ชื่อ :
        <?php
            if (!empty($_POST["findFname"])) {
              $name = "SELECT Fname FROM person WHERE Fname = '$findFname' ";
              $resultName = mysqli_query($con,$name);
              $resname = mysqli_fetch_assoc($resultName);
              echo $resname["Fname"];
            } else {
              echo "-";
            }
        ?>

        สกุล :
        <?php
            if (!empty($_POST["findLname"])) {
              $surname = "SELECT Lname FROM person WHERE Lname = '$findLname' ";
              $resultSurname = mysqli_query($con,$surname);
              $ressurname = mysqli_fetch_assoc($resultSurname);
              echo $ressurname["Lname"];
            } else {
              echo "-";
            }
        ?>

                  ข้อมูลผู้อาศัย

                    #
                    ชื่อ - สกุล
                    บ้านเลขที่
                    ตรวจสุขภาพ
                    แก้ไขข้อมูล
                    ลบข้อมูล

                    <?php
                      if((!empty($_POST["findhome"]))&&(!empty($_POST["findFname"]))&&(!empty($_POST["findLname"]))){
                        $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Year(CURRENT_DATE)-Year(Birth_date) AS Age,Hid FROM person,home,health_info WHERE Citizen_ID = Hcid and year(current_date) = years and HomeID = Hid and HomeNo = '$findhome'  and Fname = '$findFname' and Lname = '$findLname' ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }else if((!empty($_POST["findhome"]))&& (!empty($_POST["findFname"]))){
                          $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Years(CURRENT_DATE)-Years(Birth_date) AS Age,Hid FROM person,home,health_info WHERE Citizen_ID = Hcid and year(current_date) = years and HomeID = Hid and HomeNo = '$findhome' AND Fname = '$findFname' ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }else if((!empty($_POST["findhome"]))&&(!empty($_POST["findLname"]))){
                          $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Year(CURRENT_DATE)-Year(Birth_date) AS Age,Hid FROM person LEFT OUTER JOIN health_info ON Citizen_id = Hcid and year(current_date) = years JOIN home ON Hid = HomeID AND HomeNo = '$findhome' AND Lname = '$findLname' ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }else if((!empty($_POST["findFname"]))&&(!empty($_POST["findLname"]))){
                          $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Year(CURRENT_DATE)-Year(Birth_date) AS Age,Hid FROM person,home,health_info WHERE Citizen_ID = Hcid and year(current_date) = years and HomeID = Hid and Fname = '$findFname' and Lname = '$findLname' ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }

                      else if(!empty($_POST["findhome"])){
                        $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Year(CURRENT_DATE)-Year(Birth_date) AS Age,Hid FROM person LEFT OUTER JOIN health_info ON Citizen_id = Hcid and year(current_date) = years JOIN home ON Hid = HomeID AND HomeNo = '$findhome' ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }else if(!empty($_POST["findFname"])){
                          $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Year(CURRENT_DATE)-Year(Birth_date) AS Age,Hid FROM person LEFT OUTER JOIN health_info ON   Citizen_id = Hcid and year(current_date) = years JOIN home ON Hid = HomeID  AND Fname = '$findFname'  ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }else if(!empty($_POST["findLname"])){
                          $query = "SELECT Title,Fname,Lname,HomeNo,Citizen_ID,years, Year(CURRENT_DATE)-Year(Birth_date) AS Age,Hid FROM person LEFT OUTER JOIN health_info ON Citizen_id = Hcid and year(current_date) = years JOIN home ON Hid = HomeID AND Lname = '$findLname' ORDER BY HomeNo ASC" or die("Error:" . mysqli_error());
                      }
                      $result = mysqli_query($con,$query);
                      $i = 1;
                          while($row = mysqli_fetch_array($result)){
                            $id = $row["Citizen_ID"];
                            $Hid = $row["Hid"];
                                echo "
";
                                    echo "". $i ."	";
                                    echo "" .$row["Title"] . "	";
                                    echo "" .$row["Fname"] . "	";
                                    echo "" .$row["Lname"] . "	";
                                    echo "" .$row["HomeNo"] . "	";
                                    $sql = "SELECT health_info.years FROM health_info, person WHERE health_info.Hcid = person.Citizen_ID and year(current_date) = years AND person.Citizen_ID='$id' " or die("Error:" . mysqli_error());
                                    $r = mysqli_query($con,$sql);
                                    if(mysqli_num_rows($r) == 0){
                                        echo "ไม่ได้ตรวจ	";
                                    }else{
                                       echo "ตรวจแล้ว	";

                                    }
                                    echo "<button type='button' class='btn btn-primary'>แก้ไขข้อมูล</button>	";
                                    echo "<button type='button' class='btn btn-primary'>ลบข้อมูล</button>	";
                                echo "
";
                                $i++;
                              #mysqli_close($con);
                              #echo $_SESSION['id'] = $row["Citizen_ID"]+ "    ";

                      }
                      ?>

<a href='add_inval.php?Hid=<?php echo $Hid;?>' >


text:
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */

const screenshot = require('terra-toolkit').screenshot;

module.exports = {
  before: (browser, done) => {
    browser.resizeWindow(browser.globals.width, browser.globals.height, done);
  },

  afterEach: (browser, done) => {
    screenshot(browser, 'terra-list', done);
  },

  'Displays a default list item': (browser) => {
    browser
      .url(`http://localhost:${browser.globals.webpackDevServerPort}/#/tests/list-item-tests/default`)
      .assert.elementPresent('.terra-ListItem');
  },
  'Displays a selected list item': (browser) => {
    browser
      .url(`http://localhost:${browser.globals.webpackDevServerPort}/#/tests/list-item-tests/selected`)
      .assert.cssClassPresent('.terra-ListItem', 'terra-ListItem--selected');
  },
  'Displays a selectable list item': (browser) => {
    browser
      .url(`http://localhost:${browser.globals.webpackDevServerPort}/#/tests/list-item-tests/selectable`)
      .assert.cssClassPresent('.terra-ListItem', 'terra-ListItem-isSelectable');
  },
  'Displays a chevron list item': (browser) => {
    browser
      .url(`http://localhost:${browser.globals.webpackDevServerPort}/#/tests/list-item-tests/chevron`)
      .assert.cssClassPresent('.terra-ListItem', 'terra-ListItem-hasChevron');
  },
  'Displays a content for list item with the provided content': (browser) => {
    browser
      .url(`http://localhost:${browser.globals.webpackDevServerPort}/#/tests/list-item-tests/content`)
      .assert.elementPresent('.terra-ListItem p:nth-child(1)')
      .assert.containsText('.terra-ListItem p:nth-child(1)', 'test content');
  },
};


text:
#include <ClientCredential.h>

namespace rmsauth {

ClientCredential::ClientCredential(const String& clientId, const String& clientSecret)
    : clientId_ (clientId)
    , clientSecret_(clientSecret)
{
    if (clientId.empty())
    {
        throw new IllegalArgumentException("clientId");
    }

    if (clientSecret.empty())
    {
        throw new IllegalArgumentException("clientSecret");
    }
}

} // namespace rmsauth {


text:
SPEC_BEGIN(LocalStorageSpec)

describe(@"LocalStorageSpec", ^{

    NSDictionary *environment = [[NSProcessInfo processInfo] environment];
    NSString *apikey = environment[@"API_KEY"];
    NSString *instanceName = environment[@"INSTANCE_NAME"];
    Book *mockBook = [Book mock];

    beforeAll(^{
        [SCFileManager cleanUpLocalStorage];
        [Syncano enableOfflineStorage];
        [Syncano sharedInstanceWithApiKey:apikey instanceName:instanceName];
    });

    context(@"data object", ^{
        it(@"should save data object locally", ^{
            __block NSError *_error = nil;
            __block BOOL _blockFinished = NO;
            __block Book *_storedBook = nil;
            __block NSNumber *_bookId = mockBook.objectId;
            __block NSString *_bookTitle = mockBook.title;
            __block NSNumber *_bookNumOfPages = mockBook.numOfPages;

            // Savig first of them
            [mockBook saveToLocalStorageWithCompletion:^(NSError *error) {
                SCPredicate *predicate = [SCPredicate whereKey:@"objectId" isEqualToNumber:_bookId];
               // Getting this book from local storage
                [[Book please] giveMeDataObjectsFromLocalStorageWithPredicate:predicate completion:^(NSArray *objects, NSError *error) {
                    _storedBook = [objects firstObject];
                    _blockFinished = YES;
                }];
                _error = error;
                if(error){
                    NSLog(@"error: %@",error);
                }
            }];
            [[expectFutureValue(theValue(_blockFinished)) shouldEventuallyBeforeTimingOutAfter(10.0)] beYes];
            [[_error should] beNil];
            [[mockBook should] beNonNil];
            [[_storedBook should] beNonNil];
            [[_bookId should] equal:_storedBook.objectId];
            [[_bookTitle should] equal:_storedBook.title];
            [[_bookNumOfPages should] equal:_storedBook.numOfPages];

        });

        it(@"should delete that object", ^{
            __block NSError *_saveError = nil;
            __block NSError *_deleteError = nil;

            __block BOOL _blockFinished = NO;
            __block Book *_storedBook = nil;
            __block NSNumber *_bookId = mockBook.objectId;

            // Savig first of them
            [mockBook saveToLocalStorageWithCompletion:^(NSError *error) {
                _saveError = error;
                if(error){
                    NSLog(@"error: %@",error);
                }

                [mockBook deleteFromLocalStorageWithCompletion:^(NSError *error) {
                    _deleteError = error;
                    // Getting this book from local storage
                    SCPredicate *predicate = [SCPredicate whereKey:@"objectId" isEqualToNumber:_bookId];
                    [[Book please] giveMeDataObjectsFromLocalStorageWithPredicate:predicate completion:^(NSArray *objects, NSError *error) {
                        _storedBook = [objects firstObject];
                        _blockFinished = YES;
                    }];
                }];
            }];
            [[expectFutureValue(theValue(_blockFinished)) shouldEventuallyBeforeTimingOutAfter(10.0)] beYes];
            [[_saveError should] beNil];
            [[_deleteError should] beNil];
            [[mockBook should] beNonNil];
            [[_storedBook should] beNil];
        });
    });

    context(@"local search", ^{

        const NSString* const bookTitle = @"Karius og Baktus";
        __block Book* newBook = [[Book alloc] init];

        void (^testBook)(SCPredicate*,BOOL) = ^(SCPredicate* predicate, BOOL shouldFindBook) {
            __block NSError *_error = nil;
            __block BOOL _blockFinished = NO;
            __block Book *_storedBook = nil;

            [[Book please] giveMeDataObjectsFromLocalStorageWithPredicate:predicate completion:^(NSArray *objects, NSError *error) {
                _storedBook = [objects firstObject];
                _blockFinished = YES;
                _error = error;
            }];
            [[expectFutureValue(theValue(_blockFinished)) shouldEventually] beYes];
            [[_error should] beNil];
            if(shouldFindBook) {
                [[_storedBook should] beNonNil];
                [[_storedBook.title should] equal:bookTitle];
            } else {
                [[_storedBook should] beNil];
            }
        };

        void (^testNilPredicate)() = ^() {
            __block NSError *_error = nil;
            __block BOOL _blockFinished = NO;

            [[Book please] giveMeDataObjectsFromLocalStorageWithPredicate:nil completion:^(NSArray *objects, NSError *error) {
                _blockFinished = YES;
                _error = error;
            }];
            [[expectFutureValue(theValue(_blockFinished)) shouldEventually] beYes];
            [[_error should] beNil];
        };

        beforeAll(^{
            __block NSError* _error = nil;
            __block BOOL _blockFinished = NO;
            newBook = [[Book alloc] init];
            newBook.title = [bookTitle copy];
            newBook.numOfPages = @(23);
            [newBook saveToLocalStorageWithCompletion:^(NSError *error) {
                _blockFinished = YES;
                _error = error;
            }];
            [[expectFutureValue(theValue(_blockFinished)) shouldEventually] beYes];
            [[_error should] beNil];
        });

        afterAll(^{
            __block NSError* _error = nil;
            __block BOOL _blockFinished = NO;
            [newBook deleteFromLocalStorageWithCompletion:^(NSError *error) {
                _blockFinished = YES;
                _error = error;
            }];
            [[expectFutureValue(theValue(_blockFinished)) shouldEventually] beYes];
            [[_error should] beNil];
        });

        it(@"should not throw exception for nil predicate", ^{
            [[theBlock(testNilPredicate) shouldNot] raise];
        });

        it(@"should work for hasPrefix", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" hasPrefix:@"Karius"];
            testBook(predicate, YES);
        });
        it(@"should work for hasPrefix case sensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" hasPrefix:@"karius"];
            testBook(predicate, NO);
        });
        it(@"should work for hasPrefix case insensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" caseInsensitiveHasPrefix:@"karius"];
            testBook(predicate, YES);
        });

        it(@"should work for hasSuffix", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" hasSuffix:@"Baktus"];
            testBook(predicate, YES);
        });
        it(@"should work for hasSuffix case sensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" hasSuffix:@"baktus"];
            testBook(predicate, NO);
        });
        it(@"should work for hasSuffix case insensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" caseInsensitiveHasSuffix:@"baktus"];
            testBook(predicate, YES);
        });

        it(@"should work for contains", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" containsString:@"s og B"];
            testBook(predicate, YES);
        });
        it(@"should work for contains case sensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" containsString:@"s og b"];
            testBook(predicate, NO);
        });
        it(@"should work for contains case insensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" caseInsensitiveContainsString:@"s og b"];
            testBook(predicate, YES);
        });

        it(@"should work for equals", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" isEqualToString:@"Karius og Baktus"];
            testBook(predicate, YES);
        });
        it(@"should work for equals case sensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" isEqualToString:@"karius og baktus"];
            testBook(predicate, NO);
        });
        it(@"should work for equals case insensitive", ^{
            SCPredicate *predicate = [SCPredicate whereKey:@"title" caseInsensitiveIsEqualToString:@"karius og baktus"];
            testBook(predicate, YES);
        });
    });
});

SPEC_END


text:
require "../lib/cashboard"

Cashboard::Base.authenticate('your_subdomain', 'your_api_key')

# Grab reference to first task in account
prj = Cashboard::Project.list[0]

# Grab reference to first task
task = prj.tasks[0]

puts "Creating a time entry for..."
puts "  Project: #{prj.name}"
puts "  Task   : #{task.title}\n\n"

# Create a time entry for it
te = Cashboard::TimeEntry.create({
  :line_item_id => task.id,
  :minutes => 60,
  :description => "Doin work!"
})

# Show our handy work
puts te.inspect

# Remove it
if te.delete == true
  puts "\nTime entry has been destroyed"
else
  puts "\nTime entry could not be destroyed"
end


text:
namespace gfx {

void GLContextStubWithExtensions::AddExtensionsString(const char* extensions) {
  if (extensions == NULL)
    return;

  if (extensions_.size() != 0)
    extensions_ += ' ';
  extensions_ += extensions;
}

std::string GLContextStubWithExtensions::GetExtensions() {
  return extensions_;
}

void GLContextStubWithExtensions::SetGLVersionString(const char* version_str) {
  version_str_ = std::string(version_str ? version_str : "");
}

std::string GLContextStubWithExtensions::GetGLVersion() {
  return version_str_;
}

}  // namespace gfx


text:
using java.util;

class C {
	private Iterable<?> f1;
	private Map<? : object, string : ?> f2;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.example.plugin1.TestButton
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/show_fragment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="show fragment" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

    <Button
        android:id="@+id/start_plugin_b"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="start plugin b" />

    <TextView
        android:id="@+id/txtTestInfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
title: 2021-08.x Release Notes
keywords: release notes
sidebar: doc_sidebar
permalink: 2021.08.x_release_notes.html
summary: New and updated features.
---

These release notes give an overview of the changes for Release 2021-02.x to 2021-08.x of the Wavefront service.

##  Delta Counter Changes

The implementation of delta counters, which was deprecated last year, will reach end of life on April 4th, 2021.

Wavefront updates the system dashboard and integration content. But, you have to update dashboards, charts, and alerts that use custom delta counters. See [Wavefront Obsolescence and Remediation](wavefront_obsolescence_policy.html#delta-counters) for details.

## Create New PagerDuty Incident For Each Failing Series

You can now configure [alerts](alerts.html) to receive separate PagerDuty notifications for each series that meets the alert condition. Select **Advanced** > **Unique PagerDuty Incidents** when you create or edit an alert.
With this setting turned on, you get separate PagerDuty notifications for both of the following series because the `env` tag is different.

```
#first series
app.errors source=machine env=prod

#second series
app.errors source=machine env=stage
```

![Shows a screenshot of the advanced alert settings with the Unique PagerDuty Incidents option highlighted in red. ](images/release_notes_pagerduty_notification_alerts.png)

## Application Permissions

A [Super Admin user](authorization-faq.html#who-is-the-super-admin-user) or a user with [Applications permissions](permissions_overview.html) can configure the [Apdex threshold (T)](tracing_apdex.html).

## New and Changed functions

### `limit()` Function Supports Histograms

You can now use the [limit() function](ts_limit.html) on histogram data.

### New `mvalues()` Function

Use the [`mvalues()` function](ts_mvalues.html) to count the number of the unique values over a shifting time window.

The example below returns the number of unique bytes sent to and from the database, grouped by environment over a 5-minute time window.

```
mvalues(5m, ts(~sample.db.bytes.sent), env)
```

## Tracing Improvements and New Features

### Zoom In Setting on Application Map

The **Fade Labels on Zoom** setting hides labels of small services and gradually exposes them as you zoom in on the application map. See [ Customize the application map view](tracing_ui_overview.html#appmap).

      Before
      After

        The Fade Labels on Zoom setting is not selected:

        The Fade Labels on Zoom setting is selected:

### New Operation Dashboard to See Operation RED Metrics

This default, read-only dashboard lets you explore RED metrics of an operation. See [Operation Dashboard](tracing_operation_dashboard.html).
![A screenshot of the operation dashboard.](images/release_notes_2021_08_tracing_operations_dashboard_intro.png)

### span.kind Tag Required For External Java Databases

The `span.kind` tag is required when you define external databases for Java Applications. See [required span tags for an external Java database service](tracing_external_services.html#required-span-tags-1).

## Miscellaneous Improvements

* You no longer have to specify Source Tags when using the [`without` keyword](query_language_aggregate_functions.html#grouping-with-by-or-without).
* You can [allow or deny access to embedded charts](ui_sharing.html#allow-or-deny-access-to-embedded-charts) in Wavefront.


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.Data.Tables
{
    internal static class MultipartContentExtensions
    {
        private const string CteHeaderName = "Content-Transfer-Encoding";
        private const string Binary = "binary";
        private const string ApplicationHttp = "application/http";

        internal static MultipartContent AddChangeset(this MultipartContent batch, Guid changesetGuid)
        {
            var guid = changesetGuid == default ? Guid.NewGuid() : changesetGuid;
            var changeset = new MultipartContent("mixed", $"changeset_{guid}");
            batch.Add(changeset, changeset._headers);
            return changeset;
        }

        internal static void AddContent(this MultipartContent changeset, RequestRequestContent content)
        {
            changeset.Add(content, new Dictionary<string, string> { { HttpHeader.Names.ContentType, ApplicationHttp }, { CteHeaderName, Binary } });
        }
    }
}


text:
import re
import urlparse

from fjord.feedback import config

TOKEN_SPLIT_RE = re.compile(r'[\s\.\,\/\\\?\;\:\"\*\&\^\%\$\#\@\!]+')

def tokenize(text):
    """Tokenizes the text

    1. lowercases text
    2. throws out all non-alpha-characters
    3. nixes all stop words

    """
    # Lowercase the text
    text = text.lower()

    # Nix all non-word characters
    tokens = TOKEN_SPLIT_RE.split(text)

    # Nix all stopwords and one-letter characters
    tokens = [token for token in tokens
              if (token not in config.ANALYSIS_STOPWORDS
                  and len(token) > 1)]

    # Return whatever we have left
    return tokens

def compute_grams(text):
    """Computes bigrams from analyzed text

    :arg text: text to analyze and generate bigrams from

    :returns: list of bigrams

    >>> compute_grams(u'The quick brown fox jumped')
    [u'quick brown', u'brown fox', u'fox jumped']

    """
    if not text:
        return []

    tokens = tokenize(text)

    # Generate set of bigrams. A bigram is a set of two consecutive
    # tokens. We put them in a set because we don't want duplicates.
    # We sort them so that "youtube crash" will match "crash youtube".
    bigrams = set()
    if len(tokens) >= 2:
        for i in range(len(tokens) - 1):
            bigrams.add(u' '.join(
                sorted([tokens[i], tokens[i+1]])))

    return list(bigrams)

def clean_url(url):
    """Takes a user-supplied url and cleans bits out

    This removes:

    1. nixes any non http/https/chrome/about urls
    2. port numbers
    3. query string variables
    4. hashes

    """
    if not url:
        return url

    # Don't mess with about: urls.
    if url.startswith('about:'):
        return url

    parsed = urlparse.urlparse(url)

    if parsed.scheme not in ('http', 'https', 'chrome'):
        return u''

    # Rebuild url to drop querystrings, hashes, etc
    new_url = (parsed.scheme, parsed.hostname, parsed.path, None, None, None)

    return urlparse.urlunparse(new_url)