text:
// .NAME vtkCheckerboardRepresentation - represent the vtkCheckerboardWidget
// .SECTION Description
// The vtkCheckerboardRepresentation is used to implement the representation of
// the vtkCheckerboardWidget. The user can adjust the number of divisions in
// each of the i-j directions in a 2D image. A frame appears around the
// vtkImageActor with sliders along each side of the frame. The user can
// interactively adjust the sliders to the desired number of checkerboard
// subdivisions. The representation uses four instances of
// vtkSliderRepresentation3D to implement itself.

// .SECTION See Also
// vtkCheckerboardWidget vtkImageCheckerboard vtkImageActor vtkSliderWidget
// vtkRectilinearWipeWidget

#ifndef __vtkCheckerboardRepresentation_h
#define __vtkCheckerboardRepresentation_h

#include "vtkInteractionWidgetsModule.h" // For export macro
#include "vtkWidgetRepresentation.h"

class vtkImageCheckerboard;
class vtkImageActor;
class vtkSliderRepresentation3D;

class VTKINTERACTIONWIDGETS_EXPORT vtkCheckerboardRepresentation : public vtkWidgetRepresentation
{
public:
  // Description:
  // Instantiate class.
  static vtkCheckerboardRepresentation *New();

  // Description:
  // Standard VTK methods.
  vtkTypeMacro(vtkCheckerboardRepresentation,vtkWidgetRepresentation);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Specify an instance of vtkImageCheckerboard to manipulate.
  void SetCheckerboard(vtkImageCheckerboard *chkrbrd);
  vtkGetObjectMacro(Checkerboard,vtkImageCheckerboard);

  // Description:
  // Specify an instance of vtkImageActor to decorate.
  void SetImageActor(vtkImageActor *imageActor);
  vtkGetObjectMacro(ImageActor,vtkImageActor);

  // Description:
  // Specify the offset of the ends of the sliders (on the boundary edges of
  // the image) from the corner of the image. The offset is expressed as a
  // normalized fraction of the border edges.
  vtkSetClampMacro(CornerOffset,double,0.0,0.4);
  vtkGetMacro(CornerOffset,double);

//BTX
  enum {
    TopSlider=0,
    RightSlider,
    BottomSlider,
    LeftSlider
  };
//ETX

  // Description:
  // This method is invoked by the vtkCheckerboardWidget() when a value of some
  // slider has changed.
  void SliderValueChanged(int sliderNum);

  // Description:
  // Set and get the instances of vtkSliderRepresention used to implement this
  // representation. Normally default representations are created, but you can
  // specify the ones you want to use.
  void SetTopRepresentation(vtkSliderRepresentation3D*);
  void SetRightRepresentation(vtkSliderRepresentation3D*);
  void SetBottomRepresentation(vtkSliderRepresentation3D*);
  void SetLeftRepresentation(vtkSliderRepresentation3D*);
  vtkGetObjectMacro(TopRepresentation,vtkSliderRepresentation3D);
  vtkGetObjectMacro(RightRepresentation,vtkSliderRepresentation3D);
  vtkGetObjectMacro(BottomRepresentation,vtkSliderRepresentation3D);
  vtkGetObjectMacro(LeftRepresentation,vtkSliderRepresentation3D);

  // Description:
  // Methods required by superclass.
  virtual void BuildRepresentation();
  virtual void GetActors(vtkPropCollection*);
  virtual void ReleaseGraphicsResources(vtkWindow *w);
  virtual int RenderOverlay(vtkViewport *viewport);
  virtual int RenderOpaqueGeometry(vtkViewport *viewport);
  virtual int RenderTranslucentPolygonalGeometry(vtkViewport *viewport);
  virtual int HasTranslucentPolygonalGeometry();

protected:
  vtkCheckerboardRepresentation();
  ~vtkCheckerboardRepresentation();

  // Instances that this class manipulates
  vtkImageCheckerboard *Checkerboard;
  vtkImageActor        *ImageActor;

  // The internal widgets for each side
  vtkSliderRepresentation3D *TopRepresentation;
  vtkSliderRepresentation3D *RightRepresentation;
  vtkSliderRepresentation3D *BottomRepresentation;
  vtkSliderRepresentation3D *LeftRepresentation;

  // The corner offset
  double CornerOffset;

  // Direction index of image actor's plane normal
  int OrthoAxis;

private:
  vtkCheckerboardRepresentation(const vtkCheckerboardRepresentation&);  //Not implemented
  void operator=(const vtkCheckerboardRepresentation&);  //Not implemented
};

#endif


text:
import webob.exc

from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import compute
from nova import exception

ALIAS = "os-server-diagnostics"
authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS)
sd_nsmap = {None: wsgi.XMLNS_V11}

class ServerDiagnosticsTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('diagnostics')
        elem = xmlutil.SubTemplateElement(root, xmlutil.Selector(0),
                                          selector=xmlutil.get_items)
        elem.text = 1
        return xmlutil.MasterTemplate(root, 1, nsmap=sd_nsmap)

class ServerDiagnosticsController(object):
    @wsgi.serializers(xml=ServerDiagnosticsTemplate)
    def index(self, req, server_id):
        context = req.environ["nova.context"]
        authorize(context)
        compute_api = compute.API()
        try:
            instance = compute_api.get(context, server_id)
        except exception.NotFound():
            raise webob.exc.HTTPNotFound(_("Instance not found"))

        return compute_api.get_diagnostics(context, instance)

class ServerDiagnostics(extensions.V3APIExtensionBase):
    """Allow Admins to view server diagnostics through server action."""

    name = "ServerDiagnostics"
    alias = ALIAS
    namespace = ("http://docs.openstack.org/compute/ext/"
                 "server-diagnostics/api/v3")
    version = 1

    def get_resources(self):
        parent_def = {'member_name': 'server', 'collection_name': 'servers'}
        resources = [
            extensions.ResourceExtension(ALIAS,
                                         ServerDiagnosticsController(),
                                         parent=parent_def)]
        return resources

    def get_controller_extensions(self):
        return []

redpajama_set_name: RedPajamaGithub


text:
{#-
  This file was automatically generated - do not edit
-#}
<!--
{% import "partials/language.html" as lang with context %}
{% set repo = config.repo_url %}
{% if repo | last == "/" %}
  {% set repo = repo[:-1] %}
{% endif %}
{% set path = page.meta.path | default([""]) %}
<a href="{{ [repo, path, page.meta.source] | join('/') }}" title="{{ page.meta.source }}" class="md-content__button md-icon">
  {{ lang.t("meta.source") }}
  {% set icon = config.theme.icon.repo or "fontawesome/brands/git-alt" %}
  {% include ".icons/" ~ icon ~ ".svg" %}
</a>
-->


text:
package org.maproulette.framework.repository

import java.sql.Connection

import anorm._
import javax.inject.Inject
import org.maproulette.framework.model.Group
import org.maproulette.framework.repository.{GroupMemberRepository}
import org.maproulette.framework.psql.Query
import org.maproulette.framework.psql.filter.{BaseParameter, Operator, FilterGroup}
import play.api.db.Database

/**
  * Repository to handle all the database queries for the Group object
  *
  * @author nrotstan
  */
class GroupRepository @Inject() (
    override val db: Database,
    groupMemberRepository: GroupMemberRepository
) extends RepositoryMixin {
  implicit val baseTable: String = Group.TABLE

  /**
    * Finds 0 or more groups that match the filter criteria
    *
    * @param query The psql query object containing all the filtering, paging and ordering information
    * @param c An implicit connection, that defaults to None
    * @return The list of groups that match the filter criteria
    */
  def query(query: Query)(implicit c: Option[Connection] = None): List[Group] = {
    withMRConnection { implicit c =>
      query.build(s"SELECT * FROM groups").as(GroupRepository.parser.*)
    }
  }

  /**
    * For a given id returns the group
    *
    * @param id The id of the group you are looking for
    * @param c An implicit connection, defaults to none and one will be created automatically
    * @return None if not found, otherwise the Group
    */
  def retrieve(id: Long)(implicit c: Option[Connection] = None): Option[Group] = {
    this.withMRTransaction { implicit c =>
      Query
        .simple(List(BaseParameter(Group.FIELD_ID, id)))
        .build("SELECT * FROM groups")
        .as(GroupRepository.parser.*)
        .headOption
    }
  }

  /**
    * Retrieve all groups matching the ids
    */
  def list(ids: List[Long], query: Query = Query.empty): List[Group] = {
    if (ids.isEmpty) {
      return List()
    }

    this
      .query(
        query.addFilterGroup(
          FilterGroup(
            List(BaseParameter(Group.FIELD_ID, ids, Operator.IN))
          )
        )
      )
  }

  /**
    * Insert a group into the database
    *
    * @param group The group to insert into the database. The group will fail to be inserted
    *             if a group with the same name already exists. If the id field is set on the
    *             provided group it will be ignored
    * @param c An implicit connection, that defaults to None
    * @return The group that was inserted now with the generated id or None
    */
  def create(group: Group)(implicit c: Option[Connection] = None): Option[Group] = {
    this.withMRTransaction { implicit c =>
      SQL(
        """
        |INSERT INTO groups (name, description, avatar_url, group_type)
        |VALUES ({name}, {description}, {avatarURL}, {groupType})
        |RETURNING *
        """.stripMargin
      ).on(
          Symbol("name")        -> group.name,
          Symbol("description") -> group.description,
          Symbol("avatarURL")   -> group.avatarURL,
          Symbol("groupType")   -> group.groupType
        )
        .as(GroupRepository.parser.*)
        .headOption
    }
  }

  /**
    * Updates an existing Group
    *
    * @param group The properties of the Group to update
    * @param c    Implicit provided optional connection
    * @return The updated group
    */
  def update(group: Group)(
      implicit c: Option[Connection] = None
  ): Option[Group] = {
    withMRTransaction { implicit c =>
      SQL(
        """
        |UPDATE groups
        |SET name = {name}, description = {description}, avatar_url={avatarURL}
        |WHERE id = {id}
        |RETURNING *
        """.stripMargin
      ).on(
          Symbol("id")          -> group.id,
          Symbol("name")        -> group.name,
          Symbol("description") -> group.description,
          Symbol("avatarURL")   -> group.avatarURL
        )
        .as(GroupRepository.parser.*)
        .headOption
    }
  }

  /**
    * Deletes a Group from the database
    *
    * @param group The group to delete
    * @param c    Implicit provided optional connection
    */
  def delete(group: Group)(
      implicit c: Option[Connection] = None
  ): Boolean = {
    withMRConnection { implicit c =>
      Query
        .simple(List(BaseParameter(Group.FIELD_ID, group.id)))
        .build("DELETE FROM groups")
        .execute()
    }
  }
}

object GroupRepository {
  // The anorm row parser mapping database records to Group objects
  val parser: RowParser[Group] = Macro.parser[Group](
    "groups.id",
    "groups.name",
    "groups.description",
    "groups.avatar_url",
    "groups.group_type",
    "groups.created",
    "groups.modified"
  )
}


text:
package com.castlemock.web.mock.rest.controller.rest;

import com.castlemock.model.core.ServiceProcessor;
import com.castlemock.model.mock.rest.domain.RestApplication;
import com.castlemock.service.mock.rest.project.input.CreateRestApplicationInput;
import com.castlemock.service.mock.rest.project.input.DeleteRestApplicationInput;
import com.castlemock.service.mock.rest.project.input.ReadRestApplicationInput;
import com.castlemock.service.mock.rest.project.input.UpdateRestApplicationInput;
import com.castlemock.service.mock.rest.project.input.UpdateRestResourcesForwardedEndpointInput;
import com.castlemock.service.mock.rest.project.input.UpdateRestResourcesStatusInput;
import com.castlemock.service.mock.rest.project.output.CreateRestApplicationOutput;
import com.castlemock.service.mock.rest.project.output.DeleteRestApplicationOutput;
import com.castlemock.service.mock.rest.project.output.ReadRestApplicationOutput;
import com.castlemock.service.mock.rest.project.output.UpdateRestApplicationOutput;
import com.castlemock.web.core.controller.rest.AbstractRestController;
import com.castlemock.web.mock.rest.model.CreateRestApplicationRequest;
import com.castlemock.web.mock.rest.model.UpdateRestApplicationRequest;
import com.castlemock.web.mock.rest.model.UpdateRestResourceForwardedEndpointsRequest;
import com.castlemock.web.mock.rest.model.UpdateRestResourceStatusesRequest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("api/rest/rest")
@Api(value="REST - Application", description="REST Operations for Castle Mock REST Application",
        tags = {"REST - Application"})
public class RestApplicationRestController extends AbstractRestController {

    @Autowired
    public RestApplicationRestController(final ServiceProcessor serviceProcessor){
        super(serviceProcessor);
    }

    @ApiOperation(value = "Get Application", response = RestApplication.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved REST Application")})
    @RequestMapping(method = RequestMethod.GET, value = "/project/{projectId}/application/{applicationId}")
    @PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
    public @ResponseBody ResponseEntity<RestApplication> getApplication(
            @ApiParam(name = "projectId", value = "The id of the project")
            @PathVariable(value = "projectId") final String projectId,
            @ApiParam(name = "applicationId", value = "The id of the application")
            @PathVariable(value = "applicationId") final String applicationId) {
        final ReadRestApplicationOutput output = super.serviceProcessor.process(ReadRestApplicationInput.builder()
                .restProjectId(projectId)
                .restApplicationId(applicationId)
                .build());
        return ResponseEntity.ok(output.getRestApplication());
    }

    @ApiOperation(value = "Delete Application", response = RestApplication.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully deleted REST Application")})
    @RequestMapping(method = RequestMethod.DELETE, value = "/project/{projectId}/application/{applicationId}")
    @PreAuthorize("hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
    public ResponseEntity<RestApplication> deleteApplication(
            @ApiParam(name = "projectId", value = "The id of the project")
            @PathVariable(value = "projectId") final String projectId,
            @ApiParam(name = "applicationId", value = "The id of the application")
            @PathVariable(value = "applicationId") final String applicationId) {
        final DeleteRestApplicationOutput output = super.serviceProcessor.process(DeleteRestApplicationInput.builder()
                .restProjectId(projectId)
                .restApplicationId(applicationId)
                .build());
        return ResponseEntity.ok(output.getApplication());
    }

    @ApiOperation(value = "Update Application", response = RestApplication.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully updated REST Application")})
    @RequestMapping(method = RequestMethod.PUT, value = "/project/{projectId}/application/{applicationId}")
    @PreAuthorize("hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
    public ResponseEntity<RestApplication> updateApplication(
            @ApiParam(name = "projectId", value = "The id of the project")
            @PathVariable(value = "projectId") final String projectId,
            @ApiParam(name = "applicationId", value = "The id of the application")
            @PathVariable(value = "applicationId") final String applicationId,
            @RequestBody final UpdateRestApplicationRequest request) {
        final UpdateRestApplicationOutput output = super.serviceProcessor.process(UpdateRestApplicationInput.builder()
                .restProjectId(projectId)
                .restApplicationId(applicationId)
                .name(request.getName())
                .build());
        return ResponseEntity.ok(output.getUpdatedRestApplication());
    }

    @ApiOperation(value = "Create Application", response = RestApplication.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully created REST Application")})
    @RequestMapping(method = RequestMethod.POST, value = "/project/{projectId}/application")
    @PreAuthorize("hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
    public ResponseEntity<RestApplication> createApplication(
            @ApiParam(name = "projectId", value = "The id of the project")
            @PathVariable(value = "projectId") final String projectId,
            @RequestBody CreateRestApplicationRequest request) {
        final CreateRestApplicationOutput output = super.serviceProcessor.process(CreateRestApplicationInput.builder()
                .projectId(projectId)
                .name(request.getName())
                .build());
        return ResponseEntity.ok(output.getSavedRestApplication());
    }

    @ApiOperation(value = "Update resource statuses")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully updated REST resource statuses")})
    @RequestMapping(method = RequestMethod.PUT, value = "/project/{projectId}/application/{applicationId}/resource/status")
    @PreAuthorize("hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
    public @ResponseBody
    ResponseEntity<Void> updateResourceStatuses(
            @ApiParam(name = "projectId", value = "The id of the project")
            @PathVariable(value = "projectId") final String projectId,
            @ApiParam(name = "applicationId", value = "The id of the application")
            @PathVariable(value = "applicationId") final String applicationId,
            @RequestBody UpdateRestResourceStatusesRequest request){
        request.getResourceIds()
                .forEach(resourceId -> super.serviceProcessor.process(UpdateRestResourcesStatusInput.builder()
                        .projectId(projectId)
                        .applicationId(applicationId)
                        .resourceId(resourceId)
                        .methodStatus(request.getStatus())
                        .build()));
        return ResponseEntity.ok().build();
    }

    @ApiOperation(value = "Update Resource forwarded endpoints")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully updated REST Resource forwarded endpoints")})
    @RequestMapping(method = RequestMethod.PUT, value = "/project/{projectId}/application/{applicationId}/resource/endpoint/forwarded")
    @PreAuthorize("hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
    public @ResponseBody
    ResponseEntity<Void> updateResourceForwardedEndpoints(
            @ApiParam(name = "projectId", value = "The id of the project")
            @PathVariable(value = "projectId") final String projectId,
            @ApiParam(name = "applicationId", value = "The id of the application")
            @PathVariable(value = "applicationId") final String applicationId,
            @org.springframework.web.bind.annotation.RequestBody UpdateRestResourceForwardedEndpointsRequest request){
        super.serviceProcessor.process(UpdateRestResourcesForwardedEndpointInput.builder()
                .projectId(projectId)
                .applicationId(applicationId)
                .resourceIds(request.getResourceIds())
                .forwardedEndpoint(request.getForwardedEndpoint())
                .build());
        return ResponseEntity.ok().build();
    }

}


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of Qt Designer.  This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//

#ifndef QDESIGNER_COMMAND2_H
#define QDESIGNER_COMMAND2_H

#include "shared_global_p.h"
#include "qdesigner_formwindowcommand_p.h"

#include <QtWidgets/QWidget>

QT_BEGIN_NAMESPACE

namespace qdesigner_internal {

class LayoutCommand;
class BreakLayoutCommand;

/* This command changes the type of a managed layout on a widget (including
 * red layouts of type 'QLayoutWidget') into another type, maintaining the
 * applicable properties. It does this by chaining BreakLayoutCommand and
 * LayoutCommand, parametrizing them not to actually delete/reparent
 * QLayoutWidget's. */

class QDESIGNER_SHARED_EXPORT MorphLayoutCommand : public QDesignerFormWindowCommand {
    Q_DISABLE_COPY(MorphLayoutCommand)
public:
    explicit MorphLayoutCommand(QDesignerFormWindowInterface *formWindow);
    virtual ~MorphLayoutCommand();

    bool init(QWidget *w, int newType);

    static bool canMorph(const QDesignerFormWindowInterface *formWindow, QWidget *w, int *ptrToCurrentType = 0);

    virtual void redo();
    virtual void undo();

private:
    static QString formatDescription(QDesignerFormEditorInterface *core, const QWidget *w, int oldType, int newType);

    BreakLayoutCommand *m_breakLayoutCommand;
    LayoutCommand *m_layoutCommand;
    int m_newType;
    QWidgetList m_widgets;
    QWidget *m_layoutBase;
};

// Change the alignment of a widget in a managed grid/box layout cell.
class LayoutAlignmentCommand : public QDesignerFormWindowCommand {
    Q_DISABLE_COPY(LayoutAlignmentCommand)
public:
    explicit LayoutAlignmentCommand(QDesignerFormWindowInterface *formWindow);

    bool init(QWidget *w, Qt::Alignment alignment);

    virtual void redo();
    virtual void undo();

    // Find out alignment and return whether command is enabled.
    static Qt::Alignment alignmentOf(const QDesignerFormEditorInterface *core, QWidget *w, bool *enabled = 0);

private:
    static void applyAlignment(const QDesignerFormEditorInterface *core, QWidget *w, Qt::Alignment a);

    Qt::Alignment m_newAlignment;
    Qt::Alignment m_oldAlignment;
    QWidget *m_widget;
};

} // namespace qdesigner_internal

QT_END_NAMESPACE

#endif // QDESIGNER_COMMAND2_H


text:
import isPlaylistValid from './isPlaylistValid';
import getTrackSources from './getTrackSources';
import findTrackIndexByUrl from './findTrackIndexByUrl';

const veryLongKey =
  '__highly_unstable_snapshot_internals_which_will_break_your_app_if_you_use_them_directly__';
const versionKey = '__cassette_snapshot_version__';

// IMPORTANT: new migrations *must* always be added to the end since
// the tracked snapshot version is based on the migration index.
// If there is a crash-inducing bug in an existing migration, it can be patched
// in-place, but it should never be removed from the migrations array.
const migrations = [
  oldSnapshot => {
    const { __unstable__, ...rest } = oldSnapshot;
    return {
      ...rest,
      [veryLongKey]: __unstable__
    };
  }
];

export function getStateSnapshot(state) {
  const {
    paused,
    currentTime,
    activeTrackIndex,
    volume,
    muted,
    loop,
    cycle,
    shuffle,
    playbackRate,
    duration,
    __playlist__
  } = state;
  return {
    [versionKey]: migrations.length,
    [veryLongKey]: {
      paused,
      // currentTime can't be restored for unbounded live streams
      currentTime: duration === Infinity ? 0 : currentTime,
      activeTrackIndex,
      volume,
      muted,
      loop,
      cycle,
      shuffle,
      playbackRate,
      activeTrackSrc: isPlaylistValid(__playlist__)
        ? getTrackSources(__playlist__, activeTrackIndex)[0].src
        : null
    }
  };
}

export function restoreStateFromSnapshot(snapshot, props) {
  const migratedSnapshot = migrations
    .slice(snapshot[versionKey] || 0)
    .reduce((oldSnapshot, migration) => migration(oldSnapshot), snapshot);
  const {
    paused,
    currentTime,
    activeTrackIndex,
    volume,
    muted,
    loop,
    cycle,
    shuffle,
    playbackRate,
    activeTrackSrc
  } = migratedSnapshot[veryLongKey];
  const restoredStateValues = {};
  if (isPlaylistValid(props.playlist) && typeof paused === 'boolean') {
    // using awaitingPlay instead of paused triggers an animation
    restoredStateValues.awaitingPlay = !paused;
  }
  if (typeof volume === 'number' && volume >= 0 && volume <= 1) {
    restoredStateValues.volume = volume;
  }
  if (typeof muted === 'boolean') {
    restoredStateValues.muted = muted;
  }
  if (typeof loop === 'boolean') {
    restoredStateValues.loop = loop;
  }
  if (typeof cycle === 'boolean') {
    restoredStateValues.cycle = cycle;
  }
  if (typeof shuffle === 'boolean') {
    restoredStateValues.shuffle = shuffle;
  }
  if (typeof playbackRate === 'number') {
    restoredStateValues.playbackRate = playbackRate;
  }
  let useCurrentTime = false;
  if (
    typeof activeTrackSrc === 'string' &&
    typeof activeTrackIndex === 'number' &&
    activeTrackIndex >= 0
  ) {
    // let's try staying on the same track index
    const currentSrc =
      props.playlist[activeTrackIndex] &&
      getTrackSources(props.playlist, activeTrackIndex)[0].src;
    if (currentSrc && activeTrackSrc === currentSrc) {
      restoredStateValues.activeTrackIndex = activeTrackIndex;
      useCurrentTime = true;
    } else {
      /* if the track we were playing before is in the new playlist,
       * update the activeTrackIndex.
       */
      const newTrackIndex = findTrackIndexByUrl(props.playlist, activeTrackSrc);
      if (newTrackIndex !== -1) {
        restoredStateValues.activeTrackIndex = newTrackIndex;
        useCurrentTime = true;
      }
    }
  }
  if (useCurrentTime && typeof currentTime === 'number' && currentTime >= 0) {
    restoredStateValues.currentTime = currentTime;
  }
  return restoredStateValues;
}


text:
package net.shad.s3gdxcodec;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Pixmap;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import org.jcodec.codecs.h264.H264Encoder;
import org.jcodec.codecs.h264.H264Utils;
import org.jcodec.common.NIOUtils;
import org.jcodec.common.SeekableByteChannel;
import org.jcodec.common.model.ColorSpace;
import org.jcodec.common.model.Picture;
import org.jcodec.containers.mp4.Brand;
import org.jcodec.containers.mp4.MP4Packet;
import org.jcodec.containers.mp4.TrackType;
import org.jcodec.containers.mp4.muxer.FramesMP4MuxerTrack;
import org.jcodec.containers.mp4.muxer.MP4Muxer;
import org.jcodec.scale.RgbToYuv420;

/**
 * Simple class to encode libGdx pixmap to mpeg4 video file. Used jcodec.org
 * pure java codec library and libGdx pixamp. Based on jcodec example
 *
 * @author Jaroslaw Czub (http://shad.net.pl)
 */
public class PixmapEncoder
{

	// Enable loging
	public static boolean log=false;
	private SeekableByteChannel ch;
	private Picture encodePicture=null;
	private Picture rgbPicture;
	private RgbToYuv420 transform;
	private H264Encoder encoder;
	private ArrayList<ByteBuffer> spsList;
	private ArrayList<ByteBuffer> ppsList;
	private ByteBuffer outBuffer;
	private int frameNo;
	private MP4Muxer muxer;
	private FramesMP4MuxerTrack outTrack;
	private int frameRate=25;
	private double deltaTime=1.0d / frameRate;
	private int width=1900;
	private int height=1080;

	/**
	 * Return video framerate
	 *
	 * @return
	 */
	public int getFrameRate(){
		return frameRate;
	}

	/**
	 * Set video framerate
	 *
	 * @param frameRate
	 */
	public void setFrameRate(int frameRate){
		this.frameRate=frameRate;
		deltaTime=1.0d / frameRate;
	}

	/**
	 * Return a delaTime, used to calculate different time between frames
	 *
	 * @return
	 */
	public double getDeltaTime(){
		return deltaTime;
	}

	/**
	 *
	 * @return
	 */
	public int getWidth(){
		return width;
	}

	/**
	 *
	 * @return
	 */
	public int getHeight(){
		return height;
	}

	/**
	 * Initalize a compress class
	 *
	 * @param fileHandle - resource to mpeg4 file
	 * @param width - video width
	 * @param height - video height
	 * @throws IOException
	 */
	public void initalize(File fileHandle, int width, int height) throws IOException{

		this.width=width;
		this.height=height;

		ch=NIOUtils.writableFileChannel(fileHandle);
		muxer=new MP4Muxer(ch, Brand.MP4);
		outTrack=muxer.addTrackForCompressed(TrackType.VIDEO, frameRate);
		outBuffer=ByteBuffer.allocate(width * height * 6);
		transform=new RgbToYuv420(0, 0);
		encoder=new H264Encoder();
		spsList=new ArrayList<ByteBuffer>();
		ppsList=new ArrayList<ByteBuffer>();
		frameNo=0;
	}

	/**
	 * Convert a libGdx pixmap to jcodec Picture and convert color space model
	 * RGB to YUV.
	 *
	 * @param pixmap to convert
	 * @return picture
	 */
	public Picture pixmapToPicture(Pixmap pixmap){

		if (encodePicture == null){
			encodePicture=Picture.create(width, height, ColorSpace.YUV420);
			rgbPicture=Picture.create(width, height, ColorSpace.RGB);
			if (log){
				Gdx.app.log("PixmapEncoder::pixmapToPicture()", "Create encode picture w:" + encodePicture.getWidth() + " h:" + encodePicture.getHeight());
			}
		}

		int dstOff=0;
		int[] rgbData=rgbPicture.getPlaneData(0);

		switch (pixmap.getFormat()){
			case RGBA8888:
				for (int i=0; i < height; i++){
					for (int j=0; j < width; j++){

						int rgb=pixmap.getPixel(j, i);
						int r=(rgb & 0xff000000) >>> 24;
						int g=(rgb & 0x00ff0000) >>> 16;
						int b=(rgb & 0x0000ff00) >>> 8;

						rgbData[dstOff]=r;
						rgbData[dstOff + 1]=g;
						rgbData[dstOff + 2]=b;
						dstOff+=3;
					}
				}
				break;
			case RGB888:
				for (int i=0; i < height; i++){
					for (int j=0; j < width; j++){

						int rgb=pixmap.getPixel(j, i);
						int r=(rgb & 0x00ff0000) >>> 16;
						int g=(rgb & 0x0000ff00) >>> 8;
						int b=(rgb & 0x000000ff);

						rgbData[dstOff]=r;
						rgbData[dstOff + 1]=g;
						rgbData[dstOff + 2]=b;
						dstOff+=3;
					}
				}
				break;
			default:
				throw new IllegalArgumentException("Not support Pixmap Format ...");
		}

		transform.transform(rgbPicture, encodePicture);
		return encodePicture;
	}

	/**
	 * Add picture to video stream
	 * @param picture
	 * @throws IOException
	 */
	public void encodeFrame(Picture picture) throws IOException{
		if (log){
			Gdx.app.log("PixmapEncoder::encodeFrame()", "Compress frame " + frameNo + " w:" + encodePicture.getWidth() + " h:" + encodePicture.getHeight());
		}
		outBuffer.clear();
		ByteBuffer result=encoder.encodeFrame(outBuffer, picture);
		spsList.clear();
		ppsList.clear();
		H264Utils.encodeMOVPacket(result, spsList, ppsList);
		outTrack.addFrame(new MP4Packet(result, frameNo, frameRate, 1, frameNo, true, null, frameNo, 0));
		frameNo++;
	}

	/**
	 * Close the file and clear resource
	 * @throws IOException
	 */
	public void close() throws IOException{
		outTrack.addSampleEntry(H264Utils.createMOVSampleEntry(spsList, ppsList));
		muxer.writeHeader();
		NIOUtils.closeQuietly(ch);

		outBuffer.clear();
		spsList.clear();
		ppsList.clear();

		outBuffer=null;
		transform=null;
		muxer=null;
		encoder=null;
		spsList=null;
		ppsList=null;
	}
}


text:
'''OpenGL extension AMD.pinned_memory

This module customises the behaviour of the
OpenGL.raw.GL.AMD.pinned_memory to provide a more
Python-friendly API

Overview (from the spec)

	This extension defines an interface that allows improved control
	of the physical memory used by the graphics device.

	It allows an existing page of system memory allocated by the application
	to be used as memory directly accessible to the graphics processor. One
	example application of this functionality would be to be able to avoid an
	explicit synchronous copy with sub-system of the application; for instance
	it is possible to directly draw from a system memory copy of a video
	image.

The official definition of this extension is available here:
http://www.opengl.org/registry/specs/AMD/pinned_memory.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GL import _types, _glgets
from OpenGL.raw.GL.AMD.pinned_memory import *
from OpenGL.raw.GL.AMD.pinned_memory import _EXTENSION_NAME

def glInitPinnedMemoryAMD():
    '''Return boolean indicating whether this extension is available'''
    from OpenGL import extensions
    return extensions.hasGLExtension( _EXTENSION_NAME )

### END AUTOGENERATED SECTION


text:
"""v3/mail/send response body builder"""
import json

class Mail(object):
    """Creates the response body for v3/mail/send"""
    def __init__(self, from_email = None, subject = None, to_email = None, content = None):
        self.from_email = None
        self.subject = None
        self.personalizations = None
        self.contents = None
        self.attachments = None
        self.template_id = None
        self.sections = None
        self.headers = None
        self.categories = None
        self.custom_args = None
        self.send_at = None
        self.batch_id = None
        self.asm = None
        self.ip_pool_name = None
        self.mail_settings = None
        self.tracking_settings = None
        self.reply_to = None

        # Minimum required to send an email
        if from_email and subject and to_email and content:
            self.set_from(from_email)
            personalization = Personalization()
            personalization.add_to(to_email)
            self.add_personalization(personalization)
            self.set_subject(subject)
            self.add_content(content)

    def __str__(self):
        self.get()

    def get(self):
        """
        :return: response body dict
        """
        mail = {}
        if self.from_email != None:
            mail["from"] = self.from_email.get()
        if self.subject != None:
            mail["subject"] = self.subject
        if self.personalizations != None:
            mail["personalizations"] = [personalization.get() for personalization in self.personalizations]
        if self.contents != None:
            mail["content"] = [ob.get() for ob in self.contents]
        if self.attachments != None:
            mail["attachments"] = [ob.get() for ob in self.attachments]
        if self.template_id != None:
            mail["template_id"] = self.template_id
        if self.sections != None:
            sections = {}
            for key in self.sections:
                sections.update(key.get())
            mail["sections"] = sections
        if self.headers != None:
            headers = {}
            for key in self.headers:
                headers.update(key.get())
            mail["headers"] = headers
        if self.categories != None:
            mail["categories"] = [category.get() for category in self.categories]
        if self.custom_args != None:
            custom_args = {}
            for key in self.custom_args:
                custom_args.update(key.get())
            mail["custom_args"] = custom_args
        if self.send_at != None:
            mail["send_at"] = self.send_at
        if self.batch_id != None:
            mail["batch_id"] = self.batch_id
        if self.asm != None:
            mail["asm"] = self.asm
        if self.ip_pool_name != None:
            mail["ip_pool_name"] = self.ip_pool_name
        if self.mail_settings != None:
            mail["mail_settings"] = self.mail_settings.get()
        if self.tracking_settings != None:
            mail["tracking_settings"] = self.tracking_settings.get()
        if self.reply_to != None:
            mail["reply_to"] = self.reply_to.get()
        return mail

    def set_from(self, email):
        self.from_email = email

    def set_subject(self, subject):
        self.subject = subject

    def add_personalization(self, personalizations):
        if self.personalizations is None:
            self.personalizations = []
        self.personalizations.append(personalizations)

    def add_content(self, content):
        if self.contents is None:
            self.contents = []
        self.contents.append(content)

    def add_attachment(self, attachment):
        if self.attachments is None:
            self.attachments = []
        self.attachments.append(attachment)

    def set_template_id(self, template_id):
        self.template_id = template_id

    def add_section(self, section):
        if self.sections is None:
            self.sections = []
        self.sections.append(section)

    def add_header(self, header):
        if self.headers is None:
            self.headers = []
        self.headers.append(header)

    def add_category(self, category):
        if self.categories is None:
            self.categories = []
        self.categories.append(category)

    def add_custom_arg(self, custom_arg):
        if self.custom_args is None:
            self.custom_args = []
        self.custom_args.append(custom_arg)

    def set_send_at(self, send_at):
        self.send_at = send_at

    def set_batch_id(self, batch_id):
        self.batch_id = batch_id

    def set_asm(self, asm):
        self.asm = asm.get()

    def set_mail_settings(self, mail_settings):
        self.mail_settings = mail_settings

    def set_tracking_settings(self, tracking_settings):
        self.tracking_settings = tracking_settings

    def set_ip_pool_name(self, ip_pool_name):
        self.ip_pool_name = ip_pool_name

    def set_reply_to(self, reply_to):
        self.reply_to = reply_to

################################################################
# The following objects are meant to be extended with validation
################################################################

class Email(object):
    def __init__(self, email=None, name=None):
        self.name = name if name != None else None
        self.email = email if email != None else None

    def set_name(self, name):
        self.name = name

    def set_email(self, email):
        self.email = email

    def get(self):
        email = {}
        if self.name != None:
            email["name"] = self.name
        if self.email != None:
            email["email"] = self.email
        return email

class Content(object):
    def __init__(self, type=None, value=None):
        self.type = type if type != None else None
        self.value = value if value != None else None

    def set_type(self, type):
        self.type = type

    def set_value(self, value):
        self.value = value

    def get(self):
        content = {}
        if self.type != None:
            content["type"] = self.type
        if self.value != None:
            content["value"] = self.value
        return content

class Header(object):
    def __init__(self, key=None, value=None):
        self.key = key if key != None else None
        self.value = value if value != None else None

    def set_key(self, key):
        self.key = key

    def set_value(self, value):
        self.value = value

    def get(self):
        header = {}
        if self.key != None and self.value != None:
            header[self.key] = self.value
        return header

class Substitution(object):
    def __init__(self, key=None, value=None):
        self.key = key if key != None else None
        self.value = value if value != None else None

    def set_key(self, key):
        self.key = key

    def set_value(self, value):
        self.value = value

    def get(self):
        substitution = {}
        if self.key != None and self.value != None:
            substitution[self.key] = self.value
        return substitution

class Section(object):
    def __init__(self, key=None, value=None):
        self.key = key if key != None else None
        self.value = value if value != None else None

    def set_key(self, key):
        self.key = key

    def set_value(self, value):
        self.value = value

    def get(self):
        section = {}
        if self.key != None and self.value != None:
            section[self.key] = self.value
        return section

class CustomArg(object):
    def __init__(self, key=None, value=None):
        self.key = key if key != None else None
        self.value = value if value != None else None

    def set_key(self, key):
        self.key = key

    def set_value(self, value):
        self.value = value

    def get(self):
        custom_arg = {}
        if self.key != None and self.value != None:
            custom_arg[self.key] = self.value
        return custom_arg

class Personalization(object):
    def __init__(self):
        self.tos = None
        self.ccs = None
        self.bccs = None
        self.subject = None
        self.headers = None
        self.substitutions = None
        self.custom_args = None
        self.send_at = None

    def add_to(self, email):
        if self.tos is None:
            self.tos = []
        self.tos.append(email.get())

    def add_cc(self, email):
        if self.ccs is None:
            self.ccs = []
        self.ccs.append(email.get())

    def add_bcc(self, email):
        if self.bccs is None:
            self.bccs = []
        self.bccs.append(email.get())

    def set_subject(self, subject):
        self.subject = subject

    def add_header(self, header):
        if self.headers is None:
            self.headers = []
        self.headers.append(header.get())

    def add_substitution(self, substitution):
        if self.substitutions is None:
            self.substitutions = []
        self.substitutions.append(substitution.get())

    def add_custom_arg(self, custom_arg):
        if self.custom_args is None:
            self.custom_args = []
        self.custom_args.append(custom_arg.get())

    def set_send_at(self, send_at):
        self.send_at = send_at

    def get(self):
        personalization = {}
        if self.tos != None:
            personalization["to"] = self.tos
        if self.ccs != None:
            personalization["cc"] = self.ccs
        if self.bccs != None:
            personalization["bcc"] = self.bccs
        if self.subject != None:
            personalization["subject"] = self.subject
        if self.headers != None:
            headers = {}
            for key in self.headers:
                headers.update(key)
            personalization["headers"] = headers
        if self.substitutions != None:
            substitutions = {}
            for key in self.substitutions:
                substitutions.update(key)
            personalization["substitutions"] = substitutions
        if self.custom_args != None:
            custom_args = {}
            for key in self.custom_args:
                custom_args.update(key)
            personalization["custom_args"] = custom_args
        if self.send_at != None:
            personalization["send_at"] = self.send_at
        return personalization

class Attachment(object):
    def __init__(self):
        self.content = None
        self.type = None
        self.filename = None
        self.disposition = None
        self.content_id = None

    def set_content(self, content):
        self.content = content

    def set_type(self, type):
        self.type = type

    def set_filename(self, filename):
        self.filename = filename

    def set_disposition(self, disposition):
        self.disposition = disposition

    def set_content_id(self, content_id):
        self.content_id = content_id

    def get(self):
        attachment = {}
        if self.content != None:
            attachment["content"] = self.content
        if self.type != None:
            attachment["type"] = self.type
        if self.filename != None:
            attachment["filename"] = self.filename
        if self.disposition != None:
            attachment["disposition"] = self.disposition
        if self.content_id != None:
            attachment["content_id"] = self.content_id
        return attachment

class Category(object):
    def __init__(self, name=None):
        self.name = name if name != None else None

    def get(self):
        return self.name

class ASM(object):
    def __init__(self, group_id=None, groups_to_display=None):
        self.group_id = group_id if group_id != None else None
        self.groups_to_display = groups_to_display if groups_to_display != None else None

    def get(self):
        asm = {}
        if self.group_id != None:
            asm["group_id"] = self.group_id
        if self.groups_to_display != None:
            asm["groups_to_display"] = self.groups_to_display
        return asm

class BCCSettings(object):
    def __init__(self, enable=None, email=None):
        self.enable = enable if enable != None else None
        self.email = email if email != None else None

    def get(self):
        bcc_settings = {}
        if self.enable != None:
            bcc_settings["enable"] = self.enable
        if self.email != None:
            email = self.email.get()
            bcc_settings["email"] = email["email"]
        return bcc_settings

class BypassListManagement(object):
    def __init__(self, enable=None):
        self.enable = enable if enable != None else None

    def get(self):
        bypass_list_management = {}
        if self.enable != None:
            bypass_list_management["enable"] = self.enable
        return bypass_list_management

class FooterSettings(object):
    def __init__(self, enable=None, text=None, html=None):
        self.enable = enable if enable != None else None
        self.text = text if text else text
        self.html = html if html else html

    def set_enable(self, enable):
        self.enable = enable

    def set_text(self, text):
        self.text = text

    def set_html(self, html):
        self.html = html

    def get(self):
        footer_settings = {}
        if self.enable != None:
            footer_settings["enable"] = self.enable
        if self.text != None:
            footer_settings["text"] = self.text
        if self.html != None:
            footer_settings["html"] = self.html
        return footer_settings

class SandBoxMode(object):
    def __init__(self, enable=None):
        self.enable = enable if enable else False

    def get(self):
        sandbox_mode = {}
        if self.enable != None:
            sandbox_mode["enable"] = self.enable
        return sandbox_mode

class SpamCheck(object):
    def __init__(self, enable=None, threshold=None, post_to_url=None):
        self.enable = enable if enable != None else None
        self.threshold = threshold if threshold != None else None
        self.post_to_url = post_to_url if post_to_url != None else None

    def set_enable(self, enable):
        self.enable = enable

    def set_threshold(self, threshold):
        self.threshold = threshold

    def set_post_to_url(self, post_to_url):
        self.post_to_url = post_to_url

    def get(self):
        spam_check = {}
        if self.enable != None:
            spam_check["enable"] = self.enable
        if self.threshold != None:
            spam_check["threshold"] = self.threshold
        if self.post_to_url != None:
            spam_check["post_to_url"] = self.post_to_url
        return spam_check

class MailSettings(object):
    def __init__(self):
        self.bcc_settings = None
        self.bypass_list_management = None
        self.footer_settings = None
        self.sandbox_mode = None
        self.spam_check = None

    def set_bcc_settings(self, bcc_settings):
        self.bcc_settings = bcc_settings

    def set_bypass_list_management(self, bypass_list_management):
        self.bypass_list_management = bypass_list_management

    def set_footer_settings(self, footer_settings):
        self.footer_settings = footer_settings

    def set_sandbox_mode(self, sandbox_mode):
        self.sandbox_mode = sandbox_mode

    def set_spam_check(self, spam_check):
        self.spam_check = spam_check

    def get(self):
        mail_settings = {}
        if self.bcc_settings != None:
            mail_settings["bcc"] = self.bcc_settings.get()
        if self.bypass_list_management != None:
            mail_settings["bypass_list_management"] = self.bypass_list_management.get()
        if self.footer_settings != None:
            mail_settings["footer"] = self.footer_settings.get()
        if self.sandbox_mode != None:
            mail_settings["sandbox_mode"] = self.sandbox_mode.get()
        if self.spam_check != None:
            mail_settings["spam_check"] = self.spam_check.get()
        return mail_settings

class ClickTracking(object):
    def __init__(self, enable=None, enable_text=None):
        self.enable = enable if enable else None
        self.enable_text = enable_text if enable_text !=None else None

    def set_enable(self, enable):
        self.enable = enable

    def set_enable_text(self, enable_text):
        self.enable_text = enable_text

    def get(self):
        click_tracking = {}
        if self.enable != None:
            click_tracking["enable"] = self.enable
        if self.enable_text != None:
            click_tracking["enable_text"] = self.enable_text
        return click_tracking

class OpenTracking(object):
    def __init__(self, enable=None, substitution_tag=None):
        self.enable = enable if enable != None else None
        self.substitution_tag = substitution_tag if substitution_tag !=None else None

    def set_enable(self, enable):
        self.enable = enable

    def set_substitution_tag(self, substitution_tag):
        self.substitution_tag = substitution_tag

    def get(self):
        open_tracking = {}
        if self.enable != None:
            open_tracking["enable"] = self.enable
        if self.substitution_tag != None:
            open_tracking["substitution_tag"] = self.substitution_tag
        return open_tracking

class SubscriptionTracking(object):
    def __init__(self, enable=None, text=None, html=None, substitution_tag=None):
        self.enable = enable if enable != None else None
        self.text = text if text != None else None
        self.html = html if html != None else None
        self.substitution_tag = substitution_tag if substitution_tag != None else None

    def set_enable(self, enable):
        self.enable = enable

    def set_text(self, text):
        self.text = text

    def set_html(self, html):
        self.html = html

    def set_substitution_tag(self, substitution_tag):
        self.substitution_tag = substitution_tag

    def get(self):
        subscription_tracking = {}
        if self.enable != None:
            subscription_tracking["enable"] = self.enable
        if self.text != None:
            subscription_tracking["text"] = self.text
        if self.html != None:
            subscription_tracking["html"] = self.html
        if self.substitution_tag != None:
            subscription_tracking["substitution_tag"] = self.substitution_tag
        return subscription_tracking

class Ganalytics(object):
    def __init__(self,
                 enable=None,
                 utm_source=None,
                 utm_medium=None,
                 utm_term=None,
                 utm_content=None,
                 utm_campaign=None):
        self.enable = enable if enable != None else None
        self.utm_source = utm_source if utm_source != None else None
        self.utm_medium = utm_medium if utm_medium != None else None
        self.utm_term = utm_term if utm_term != None else None
        self.utm_content = utm_content if utm_content != None else None
        self.utm_campaign = utm_campaign if utm_campaign != None else None

    def set_enable(self, enable):
        self.enable = enable

    def set_utm_source(self, utm_source):
        self.utm_source = utm_source

    def set_utm_medium(self, utm_medium):
        self.utm_medium = utm_medium

    def set_utm_term(self, utm_term):
        self.utm_term = utm_term

    def set_utm_content(self, utm_content):
        self.utm_content = utm_content

    def set_utm_campaign(self, utm_campaign):
        self.utm_campaign = utm_campaign

    def get(self):
        ganalytics = {}
        if self.enable != None:
            ganalytics["enable"] = self.enable
        if self.utm_source != None:
            ganalytics["utm_source"] = self.utm_source
        if self.utm_medium != None:
            ganalytics["utm_medium"] = self.utm_medium
        if self.utm_term != None:
            ganalytics["utm_term"] = self.utm_term
        if self.utm_content != None:
            ganalytics["utm_content"] = self.utm_content
        if self.utm_campaign != None:
            ganalytics["utm_campaign"] = self.utm_campaign
        return ganalytics

class TrackingSettings(object):
    def __init__(self):
        self.click_tracking = None
        self.open_tracking = None
        self.subscription_tracking = None
        self.ganalytics = None

    def set_click_tracking(self, click_tracking):
        self.click_tracking = click_tracking

    def set_open_tracking(self, open_tracking):
        self.open_tracking = open_tracking

    def set_subscription_tracking(self, subscription_tracking):
        self.subscription_tracking = subscription_tracking

    def set_ganalytics(self, ganalytics):
        self.ganalytics = ganalytics

    def get(self):
        tracking_settings = {}
        if self.click_tracking != None:
            tracking_settings["click_tracking"] = self.click_tracking.get()
        if self.open_tracking != None:
            tracking_settings["open_tracking"] = self.open_tracking.get()
        if self.subscription_tracking != None:
            tracking_settings["subscription_tracking"] = self.subscription_tracking.get()
        if self.ganalytics != None:
            tracking_settings["ganalytics"] = self.ganalytics.get()
        return tracking_settings


text:
/***********************************************************************
	created:	3/2/2005
	author:		Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#include "CEGUI/widgets/Spinner.h"
#include "CEGUI/widgets/PushButton.h"
#include "CEGUI/widgets/Editbox.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/WindowManager.h"
#include <stdio.h>
#include <sstream>
#include <iomanip>

// Start of CEGUI namespace section
namespace CEGUI
{
    const String Spinner::WidgetTypeName("CEGUI/Spinner");

    //////////////////////////////////////////////////////////////////////////
    // event strings
    const String Spinner::EventNamespace("Spinner");
    const String Spinner::EventValueChanged("ValueChanged");
    const String Spinner::EventStepChanged("StepChanged");
    const String Spinner::EventMaximumValueChanged("MaximumValueChanged");
    const String Spinner::EventMinimumValueChanged("MinimumValueChanged");
    const String Spinner::EventTextInputModeChanged("TextInputModeChanged");
    // Validator strings
    const String Spinner::FloatValidator("-?\\d*\\.?\\d*");
    const String Spinner::IntegerValidator("-?\\d*");
    const String Spinner::HexValidator("[0-9a-fA-F]*");
    const String Spinner::OctalValidator("[0-7]*");
    // component widget name strings
    const String Spinner::EditboxName( "__auto_editbox__" );
    const String Spinner::IncreaseButtonName( "__auto_incbtn__" );
    const String Spinner::DecreaseButtonName( "__auto_decbtn__" );
    //////////////////////////////////////////////////////////////////////////

    Spinner::Spinner(const String& type, const String& name) :
        Window(type, name),
        d_stepSize(1.0f),
        d_currentValue(1.0f),
        d_maxValue(32767.0f),
        d_minValue(-32768.0f),
        d_inputMode((TextInputMode)-1)
    {
        addSpinnerProperties();
    }

    Spinner::~Spinner(void)
    {
        // Nothing to do here.
    }

    void Spinner::initialiseComponents(void)
    {
        // get all the component widgets
        PushButton* increaseButton = getIncreaseButton();
        PushButton* decreaseButton = getDecreaseButton();
        Editbox* editbox = getEditbox();

        // setup component controls
        increaseButton->setWantsMultiClickEvents(false);
        increaseButton->setMouseAutoRepeatEnabled(true);
        decreaseButton->setWantsMultiClickEvents(false);
        decreaseButton->setMouseAutoRepeatEnabled(true);

        // perform event subscriptions.
        increaseButton->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&Spinner::handleIncreaseButton, this));
        decreaseButton->subscribeEvent(Window::EventMouseButtonDown, Event::Subscriber(&Spinner::handleDecreaseButton, this));
        editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this));

        // final initialisation
        setTextInputMode(Integer);
        setCurrentValue(0.0f);
        performChildWindowLayout();
    }

    double Spinner::getCurrentValue(void) const
    {
        return d_currentValue;
    }

    double Spinner::getStepSize(void) const
    {
        return d_stepSize;
    }

    double Spinner::getMaximumValue(void) const
    {
        return d_maxValue;
    }

    double Spinner::getMinimumValue(void) const
    {
        return d_minValue;
    }

    Spinner::TextInputMode Spinner::getTextInputMode(void) const
    {
        return d_inputMode;
    }

    void Spinner::setCurrentValue(double value)
    {
        if (value != d_currentValue)
        {
            // limit input value to within valid range for spinner
            value = ceguimax(ceguimin(value, d_maxValue), d_minValue);

            d_currentValue = value;

            WindowEventArgs args(this);
            onValueChanged(args);
        }
    }

    void Spinner::setStepSize(double step)
    {
        if (step != d_stepSize)
        {
            d_stepSize = step;

            WindowEventArgs args(this);
            onStepChanged(args);
        }
    }

    void Spinner::setMaximumValue(double maxValue)
    {
        if (maxValue != d_maxValue)
        {
            d_maxValue = maxValue;

            WindowEventArgs args(this);
            onMaximumValueChanged(args);
        }
    }

    void Spinner::setMinimumValue(double minVaue)
    {
        if (minVaue != d_minValue)
        {
            d_minValue = minVaue;

            WindowEventArgs args(this);
            onMinimumValueChanged(args);
        }
    }

    void Spinner::setTextInputMode(TextInputMode mode)
    {
        if (mode != d_inputMode)
        {
            switch (mode)
            {
            case FloatingPoint:
                getEditbox()->setValidationString(FloatValidator);
                break;
            case Integer:
                getEditbox()->setValidationString(IntegerValidator);
                break;
            case Hexadecimal:
                getEditbox()->setValidationString(HexValidator);
                break;
            case Octal:
                getEditbox()->setValidationString(OctalValidator);
                break;
            default:
                CEGUI_THROW(InvalidRequestException(
                    "An unknown TextInputMode was specified."));
            }

            d_inputMode = mode;

            WindowEventArgs args(this);
            onTextInputModeChanged(args);
        }
    }

    void Spinner::addSpinnerProperties(void)
    {
        const String& propertyOrigin = WidgetTypeName;

        CEGUI_DEFINE_PROPERTY(Spinner, double,
            "CurrentValue", "Property to get/set the current value of the spinner.  Value is a float.",
            &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f
        );

        CEGUI_DEFINE_PROPERTY(Spinner, double,
            "StepSize", "Property to get/set the step size of the spinner.  Value is a float.",
            &Spinner::setStepSize, &Spinner::getStepSize, 1.0f
        );

        CEGUI_DEFINE_PROPERTY(Spinner, double,
            "MinimumValue", "Property to get/set the minimum value setting of the spinner.  Value is a float.",
            &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f
        );

        CEGUI_DEFINE_PROPERTY(Spinner, double,
            "MaximumValue", "Property to get/set the maximum value setting of the spinner.  Value is a float.",
            &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f
        );

        CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode,
            "TextInputMode", "Property to get/set the TextInputMode setting for the spinner.  Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".",
            &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer
        );
    }

    double Spinner::getValueFromText(void) const
    {
        String tmpTxt(getEditbox()->getText());

        // handle empty and lone '-' or '.' cases
        if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == "."))
        {
            return 0.0f;
        }

        int res, tmp;
        uint utmp;
        double val;

        switch (d_inputMode)
        {
        case FloatingPoint:
            res = sscanf(tmpTxt.c_str(), "%lf", &val);
            break;
        case Integer:
            res = sscanf(tmpTxt.c_str(), "%d", &tmp);
            val = static_cast<double>(tmp);
            break;
        case Hexadecimal:
            res = sscanf(tmpTxt.c_str(), "%x", &utmp);
            val = static_cast<double>(utmp);
            break;
        case Octal:
            res = sscanf(tmpTxt.c_str(), "%o", &utmp);
            val = static_cast<double>(utmp);
            break;
        default:
            CEGUI_THROW(InvalidRequestException(
                "An unknown TextInputMode was encountered."));
        }

        if (res)
        {
            return val;
        }

        CEGUI_THROW(InvalidRequestException(
            "The string '" + getEditbox()->getText() +
            "' can not be converted to numerical representation."));
    }

    String Spinner::getTextFromValue(void) const
    {
        std::stringstream tmp;

        switch (d_inputMode)
        {
        case FloatingPoint:
            return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) );
            break;
        case Integer:
            tmp << static_cast<int>(d_currentValue);
            break;
        case Hexadecimal:
            tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue);
            break;
        case Octal:
            tmp << std::oct << static_cast<int>(d_currentValue);
            break;
        default:
            CEGUI_THROW(InvalidRequestException(
                "An unknown TextInputMode was encountered."));
        }

        return String(tmp.str().c_str());
    }

    void Spinner::onFontChanged(WindowEventArgs& e)
    {
        // Propagate to children
        getEditbox()->setFont(getFont());
        // Call base class handler
        Window::onFontChanged(e);
    }

    void Spinner::onTextChanged(WindowEventArgs& e)
    {
        Editbox* editbox = getEditbox();

        // update only if needed
        if (editbox->getText() != getText())
        {
            // done before doing base class processing so event subscribers see
            // 'updated' version.
            editbox->setText(getText());
            ++e.handled;

            Window::onTextChanged(e);
        }
    }

    void Spinner::onActivated(ActivationEventArgs& e)
    {
        if (!isActive())
        {
            Window::onActivated(e);

            Editbox* editbox = getEditbox();

            if (!editbox->isActive())
            {
                editbox->activate();
            }
        }
    }

    void Spinner::onValueChanged(WindowEventArgs& e)
    {
        Editbox* editbox = getEditbox();

        // mute to save doing unnecessary events work.
        bool wasMuted = editbox->isMuted();
        editbox->setMutedState(true);

        // Update editbox and spinner text with new value.
        // (allow empty and '-' cases to equal 0 with no text change required)
        if (!(d_currentValue == 0 &&
              (editbox->getText().empty() || editbox->getText() == "-")))
        {
            const CEGUI::String& valueString = getTextFromValue();
            editbox->setText(valueString);
            setText(valueString);
        }
        // restore previous mute state.
        editbox->setMutedState(wasMuted);

        fireEvent(EventValueChanged, e, EventNamespace);
    }

    void Spinner::onStepChanged(WindowEventArgs& e)
    {
        fireEvent(EventStepChanged, e, EventNamespace);
    }

    void Spinner::onMaximumValueChanged(WindowEventArgs& e)
    {
        fireEvent(EventMaximumValueChanged, e, EventNamespace);

        if (d_currentValue > d_maxValue)
        {
            setCurrentValue(d_maxValue);
        }
    }

    void Spinner::onMinimumValueChanged(WindowEventArgs& e)
    {
        fireEvent(EventMinimumValueChanged, e, EventNamespace);

        if (d_currentValue < d_minValue)
        {
            setCurrentValue(d_minValue);
        }
    }

    void Spinner::onTextInputModeChanged(WindowEventArgs& e)
    {
        Editbox* editbox = getEditbox();
        // update edit box text to reflect new mode.
        // mute to save doing unnecessary events work.
        bool wasMuted = editbox->isMuted();
        editbox->setMutedState(true);
        // Update text with new value.
        editbox->setText(getTextFromValue());
        // restore previous mute state.
        editbox->setMutedState(wasMuted);

        fireEvent(EventTextInputModeChanged, e, EventNamespace);
    }

    bool Spinner::handleIncreaseButton(const EventArgs& e)
    {
        if (((const MouseEventArgs&)e).button == LeftButton)
        {
            setCurrentValue(d_currentValue + d_stepSize);
            return true;
        }

        return false;
    }

    bool Spinner::handleDecreaseButton(const EventArgs& e)
    {
        if (((const MouseEventArgs&)e).button == LeftButton)
        {
            setCurrentValue(d_currentValue - d_stepSize);
            return true;
        }

        return false;
    }

    bool Spinner::handleEditTextChange(const EventArgs&)
    {
        // set this windows text to match
        setText(getEditbox()->getText());
        // update value
        setCurrentValue(getValueFromText());
        return true;
    }

    PushButton* Spinner::getIncreaseButton() const
    {
        return static_cast<PushButton*>(getChild(IncreaseButtonName));
    }

    PushButton* Spinner::getDecreaseButton() const
    {
        return static_cast<PushButton*>(getChild(DecreaseButtonName));
    }

    Editbox* Spinner::getEditbox() const
    {
        return static_cast<Editbox*>(getChild(EditboxName));
    }

//////////////////////////////////////////////////////////////////////////

} // End of  CEGUI namespace section


text:
"""
Created on Tue Apr 14 17:44:32 2015

@author: Dominic White
"""

import Tree

def _newick_to_tree(newick):
    lengths=False
    if ':' in newick:
        lengths=True
    t = Tree.Tree()
    current_anc=0 # current ancestor node
    current_node=1
    t.add_node(current_anc)
    x=0
    while x < len(newick): #loop to go through tree string
        if newick[x]=="(":
            t.add_edge(current_anc,current_node)
            current_anc=current_node
            current_node=current_node+1
            x=x+1
        elif newick[x] == ',':
            x=x+1
        elif newick[x] == ')':
            if x+1 < len(newick) and current_anc!=1:
                next_anc=t.predecessors(current_anc)[0]
                x=x+1
                if lengths==True:
                    bl, idx_plus = _get_branch_length(newick,x)
                    t.edge[next_anc][current_anc]['length']=bl
                    x=x+idx_plus
                current_anc=next_anc
            else:
                break
        else:
            new_taxon, idx_plus = _get_taxon_name(newick, x)
            t.add_edge(current_anc,current_node)
            t.node[current_node]['name']=new_taxon
            x=x+idx_plus
            if lengths==True:
                bl, idx_plus = _get_branch_length(newick,x)
                t.edge[current_anc][current_node]['length']=bl
                x=x+idx_plus
            current_node=current_node+1
    t.remove_node(0)
    return t

def _get_branch_length(newick,count): #count is the index of the colon
    if newick[count] != ':':
        raise ValueError('Expecting a colon in newick tree before branch length')
    y=0
    while True:
        if newick[count+y] == ',' or newick[count+y] == ')':
            break
        else:
            y=y+1
    if y < 2:
        raise ValueError('Missing branch length in newick tree')
    return float(newick[count+1:count+y]), y

def _get_taxon_name(newick, count):
    y=0
    while True:
#        print len(newick), count+y
        if newick[count+y] == ':' or newick[count+y] == ',' or newick[count+y] == ')':
            break
        else:
            y=y+1
    if y==0:
        raise ValueError('Missing a taxon name in newick tree')
    return newick[count:count+y], y

def read_trees(filename, filetype="newick"):
    """Takes a file containing phylogenetic trees (newick format) and returns
    a tree objects for each tree in the file.
    In the future this function should also handle tnt and nexus files."""
    trees=[]
    if filetype=="newick":
        newick = open(filename)
        lines = newick.readlines()
        for t in lines:
            ntree = t.strip().replace(';','')
            if len(ntree)>0:
                trees.append( _newick_to_tree(ntree) )
        newick.close()
    elif filetype=="tnt":
        tnt=open(filename)
        lines = tnt.readlines()
        for t in lines:
            if t[0]=='(':
                t = t.replace('*','').replace(';','').replace(' )',')').replace(')(','),(').replace(' ',',')
                trees.append(_newick_to_tree(t.strip()))
        tnt.close()
    return trees


text:
/**
 * @license Highcharts JS v8.0.3 (2020-03-06)
 * @module highcharts/modules/solid-gauge
 * @requires highcharts
 * @requires highcharts/highcharts-more
 *
 * Solid angular gauge module
 *
 * (c) 2010-2019 Torstein Honsi
 *
 * License: www.highcharts.com/license
 */
'use strict';
import '../../modules/solid-gauge.src.js';


text:
SOURCE="${BASH_SOURCE[0]}"
RDIR="$( dirname "$SOURCE" )"
SUDO=`which sudo 2> /dev/null`
SUDO_OPTION=""
#SUDO_OPTION="--sudo"
OS_TYPE=${1:-}
OS_VERSION=${2:-}
ANSIBLE_VERSION=${3:-}

ANSIBLE_VAR=""
ANSIBLE_INVENTORY="tests/inventory"
ANSIBLE_PLAYBOOk="tests/test.yml"
#ANSIBLE_LOG_LEVEL=""
ANSIBLE_LOG_LEVEL="-v"

# if there wasn't sudo then ansible couldn't use it
if [ "x$SUDO" == "x" ];then
    SUDO_OPTION=""
fi

ANSIBLE_EXTRA_VARS=""
if [ "${ANSIBLE_VAR}x" == "x" ];then
    ANSIBLE_EXTRA_VARS=" -e \"${ANSIBLE_VAR}\" "
fi

cd $RDIR/..
printf "[defaults]\nroles_path = ../:roles" > ansible.cfg
printf "" > ssh.config

function show_version() {

echo "TEST: show versions"
ansible --version
id
systemctl --no-pager
proc1comm=$(cat /proc/1/comm)
echo "TEST: proc1s comm is $proc1comm"

}

function install_ansible_devel() {

# http://docs.ansible.com/ansible/intro_installation.html#latest-release-via-yum

echo "TEST: building ansible"

yum -y install PyYAML python-paramiko python-jinja2 python-httplib2 rpm-build make python2-devel asciidoc patch wget 2>&1 >/dev/null || (echo "Could not install ansible yum dependencies" && exit 2 )
rm -Rf ansible
git clone https://github.com/ansible/ansible --recursive ||(echo "Could not clone ansible from Github" && exit 2 )
cd ansible
# checking out this commit because some errors after 2015-11-05
#git checkout 07d0d2720c73816e1206882db7bc856087eb5c3f
# because systemctl and systemd
git checkout 589971fe7ef78ea8bb41fb9ae6cd19cb8e277371
make rpm 2>&1 >/dev/null
rpm -Uvh ./rpm-build/ansible-*.noarch.rpm ||(echo "Could not install built ansible devel rpms" && exit 2 )
cd ..
rm -Rf ansible

}

function install_os_deps() {
echo "TEST: installing os deps"

yum -y install epel-release sudo tree git which file less||(echo "Could not install some os deps" && exit 2 )

}

function tree_list() {

tree

}
function test_ansible_setup(){
    echo "TEST: ansible -m setup -i ${ANSIBLE_INVENTORY} --connection=local localhost"

    ansible -m setup -i ${ANSIBLE_INVENTORY} --connection=local localhost

}

function test_install_requirements(){
    echo "TEST: ansible-galaxy install -r requirements.yml --force"

    ansible-galaxy install -r requirements.yml --force ||(echo "requirements install failed" && exit 2 )

}
function slurm_create_munge_key(){
    echo "TEST: creating munge.key without any special tools or depending on entropy"

    mkdir -vp /ansible-role-slurm/tests/files/
    cp -v /ansible-role-slurm/README.md /ansible-role-slurm/tests/files/munge.key
}

function test_playbook_syntax(){
    echo "TEST: ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} --syntax-check"

    ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} --syntax-check ||(echo "ansible playbook syntax check was failed" && exit 2 )
}

function test_playbook_check(){
    echo "TEST: ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} ${ANSIBLE_LOG_LEVEL} --connection=local ${SUDO_OPTION} ${ANSIBLE_EXTRA_VARS} --check"

    ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} ${ANSIBLE_LOG_LEVEL} --connection=local ${SUDO_OPTION} ${ANSIBLE_EXTRA_VARS} --check ||(echo "playbook check failed" && exit 2 )

}

function test_playbook(){
    echo "TEST: ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} ${ANSIBLE_LOG_LEVEL} --connection=local ${SUDO_OPTION} ${ANSIBLE_EXTRA_VARS}"
    ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} ${ANSIBLE_LOG_LEVEL} --connection=local ${SUDO_OPTION} ${ANSIBLE_EXTRA_VARS} ||(echo "first ansible run failed" && exit 2 )

#    echo "TEST: idempotence test! Same as previous but now grep for changed=0.*failed=0"
#    ansible-playbook -i ${ANSIBLE_INVENTORY} ${ANSIBLE_PLAYBOOk} ${ANSIBLE_LOG_LEVEL} --connection=local ${SUDO_OPTION} ${ANSIBLE_EXTRA_VARS} || grep -q 'changed=0.*failed=0' && (echo 'Idempotence test: pass' ) || (echo 'Idempotence test: fail' && exit 1)
}
function extra_tests(){

    echo "TEST: cat /etc/slurm/slurm.conf"
    cat /etc/slurm/slurm.conf

    echo "TEST: sinfo"
    sinfo

    echo "TEST: scontrol show node"
    scontrol show node

    echo "TEST: time srun --immediate=30 env"
    time srun --immediate=30 env

}

set -e
function main(){
#    install_os_deps
#    install_ansible_devel
    show_version
    tree_list
    test_install_requirements
    test_ansible_setup
    slurm_create_munge_key
    tree_list
    test_playbook_syntax
    test_playbook
    test_playbook_check
    extra_tests

}

################ run #########################
main


text:
#pragma once
#ifdef WIN32

#define _CRT_SECURE_NO_DEPRECATE 1
#define _CRT_NONSTDC_NO_DEPRECATE 1

#ifndef _WIN32_WINNT		// Allow use of features specific to Windows XP or later.
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif

#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here
#endif


text:
project_path: /web/_project.yaml
book_path: /web/fundamentals/_book.yaml

{# wf_updated_on: 2016-09-27 #}
{# wf_published_on: 2016-09-27 #}

# Web Fundamentals {: .page-title }

Web Push

    Web push notifications makes it easy to re-engage with users by
    showing relevant, timely, and contextual notifications to the user,
    even when the browser is closed!

    Web push notifications allow users to opt-in to timely updates from
    sites they love and allow you to effectively re-engage them with
    customized, relevant content.

    The Push API and Notification API open a whole new set of
    possibilities for you to re-engage with your users.

    Get Started

Building Web Components

    Web Components are a new set of standards which let you create your own
    HTML elements. You can use them to build anything, from simple UI elements,
    to entire applications.

    Because Web Components are standards based, they're designed to work in
    any environment, even if there are other CSS or JavaScript libraries being
    used on the page. This makes them easy to share amongst teams who might
    be on different stacks, but still wish to have consistent looking UI.

    Get Started

## Latest updates for Web Developers {: .hide-from-toc }

{% include "web/_shared/latest_show.html" %}

{% include "web/_shared/latest_articles.html" %}

## Ways to enhance your site (AKA the Hot Stuff) {: .hide-from-toc }

Build a Progressive Web App

    What is a Progressive Web App and what do you need to know to get
    started building one? In this step-by-step guide, you'll build your
    own Progressive Web App and learn the fundamentals needed for building
    Progressive Web Apps.

    Get Started

Make Your Site Instant and Reliable

    Service workers are a programmable proxy sitting between the network
    and the browser. Using a service worker, you get to decide what gets
    cached, how it's cached and how it should be returned to the user.

    The Offline Cookbook

Enable Add to Home Screen

    App install banners make it easy for users to add your app to their
    home screen with a single click, and is an indication to the user that
    the app they're adding meets an important quality bar.

    Learn more

Move to HTTPS

    HTTPS allows users to securely connect to your website or app. Set up
    HTTPS to protect the integrity of your site, and the security of your
    users.

    Learn more


text:
#include <cstdlib>
#include<iostream>

#include "Cat.h"
using namespace std;

/*
 * Constructor- runs when object is instantiated
 *
 * Destructor- when a object is destroyed
 * destructor is called automatically
 *
 */
int main(int argc, char** argv) {
    cout << "Starting the Code" << endl;

    //instantiating a Cat object from a class
    //The constructors runs as soon as the object is created
    //In this case when object bob is created, constructor executes.
    //does not require a special call
    {
        Cat bob;
        bob.speak();
    }//Normally not used but, sometimes done to specifically de-allocate memory
    //Cat bob is destroyed at the nearest closing brackets
    /* OUTPUT for
     * {
        Cat bob;
        bob.speak();
        }
     * ------------------
     * Starting the Code
        Cat created.
        Meow!!
        Cat destroyed.
        Ending the Code
     */
    cout << "Ending the Code" << endl;
    return 0;
    //Cat bob is destroyed at this point if there were no above enclosing brackets
    /* OUTPUT for:
     *
     * Cat bob;
       bob.speak();
     *
     * ---------------------
     * Starting the Code
        Cat created.
        Meow!!
        Ending the Code
        Cat destroyed
     */
}


text:
package com.citelic.game.entity.player.content.socialization;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import com.citelic.GameConstants;
import com.citelic.game.engine.Engine;
import com.citelic.game.entity.player.Player;
import com.citelic.game.entity.player.chat.QuickChatMessage;
import com.citelic.game.entity.player.content.controllers.impl.distractions.clanwars.ClanWars;
import com.citelic.networking.streaming.OutputStream;
import com.citelic.utility.SerializableFilesManager;
import com.citelic.utility.Utilities;

public class FriendChatsManager {

	private static HashMap<String, FriendChatsManager> cachedFriendChats;
	private String owner;
	private String ownerDisplayName;
	private FriendsIgnores settings;
	private CopyOnWriteArrayList<Player> players;
	private ConcurrentHashMap<String, Long> bannedPlayers;
	private byte[] dataBlock;
	/**
	 * The clan wars instance (if the clan is in a war).
	 */
	private ClanWars clanWars;

	private FriendChatsManager(Player player) {
		owner = player.getUsername();
		ownerDisplayName = player.getDisplayName();
		settings = player.getFriendsIgnores();
		players = new CopyOnWriteArrayList<Player>();
		bannedPlayers = new ConcurrentHashMap<String, Long>();
	}

	public static void destroyChat(Player player) {
		synchronized (FriendChatsManager.cachedFriendChats) {
			FriendChatsManager chat = FriendChatsManager.cachedFriendChats
					.get(player.getUsername());
			if (chat == null)
				return;
			chat.destroyChat();
			player.getPackets().sendGameMessage(
					"Your friends chat channel has now been disabled!");
		}
	}

	public static List<Player> getLootSharingPeople(Player player) {
		if (!player.isToggleLootShare())
			return null;
		FriendChatsManager chat = player.getCurrentFriendChat();
		if (chat == null)
			return null;
		List<Player> players = new ArrayList<Player>();
		for (Player p2 : player.getCurrentFriendChat().getPlayers()) {
			if (p2.isToggleLootShare() && p2.withinDistance(player)) {
				players.add(p2);
			}
		}
		return players;

	}

	public static void init() {
		FriendChatsManager.cachedFriendChats = new HashMap<String, FriendChatsManager>();
	}

	public static void joinChat(String ownerName, Player player) {
		synchronized (FriendChatsManager.cachedFriendChats) {
			if (player.getCurrentFriendChat() != null)
				return;
			player.getPackets()
					.sendGameMessage("Attempting to join channel...");
			String formatedName = Utilities
					.formatPlayerNameForProtocol(ownerName);
			FriendChatsManager chat = FriendChatsManager.cachedFriendChats
					.get(formatedName);
			if (chat == null) {
				Player owner = Engine.getPlayerByDisplayName(ownerName);
				if (owner == null) {
					owner = Engine.getLobbyPlayerByDisplayName(ownerName);
				}
				if (owner == null) {
					if (!SerializableFilesManager.containsPlayer(formatedName)) {
						player.getPackets()
								.sendGameMessage(
										"The channel you tried to join does not exist.");
						return;
					}
					owner = SerializableFilesManager.loadPlayer(formatedName);
					if (owner == null) {
						player.getPackets()
								.sendGameMessage(
										"The channel you tried to join does not exist.");
						return;
					}
					owner.setUsername(formatedName);
				}
				FriendsIgnores settings = owner.getFriendsIgnores();
				if (!settings.hasFriendChat()) {
					player.getPackets().sendGameMessage(
							"The channel you tried to join does not exist.");
					return;
				}
				if (!player.getUsername().equals(ownerName)
						&& !settings.hasRankToJoin(player.getUsername())
						&& player.getRights() < 2) {
					player.getPackets()
							.sendGameMessage(
									"You do not have a enough rank to join this friends chat channel.");
					return;
				}
				chat = new FriendChatsManager(owner);
				FriendChatsManager.cachedFriendChats.put(ownerName, chat);
				chat.joinChatNoCheck(player);
			} else {
				chat.joinChat(player);
			}
		}

	}

	public static void linkSettings(Player player) {
		synchronized (FriendChatsManager.cachedFriendChats) {
			FriendChatsManager chat = FriendChatsManager.cachedFriendChats
					.get(player.getUsername());
			if (chat == null)
				return;
			chat.settings = player.getFriendsIgnores();
		}
	}

	public static void refreshChat(Player player) {
		synchronized (FriendChatsManager.cachedFriendChats) {
			FriendChatsManager chat = FriendChatsManager.cachedFriendChats
					.get(player.getUsername());
			if (chat == null)
				return;
			chat.refreshChannel();
		}
	}

	public static void toggleLootShare(Player player) {
		if (player.getCurrentFriendChat() == null) {
			player.getPackets()
					.sendGameMessage(
							"You need to be in a Friends Chat channel to activate LootShare.");
			player.refreshToggleLootShare();
			return;
		}
		if (!player.getUsername().equals(
				player.getCurrentFriendChat().getOwnerName())
				&& !player.getCurrentFriendChat().settings
						.hasRankToLootShare(player.getUsername())) {
			player.getPackets()
					.sendGameMessage(
							"You must be on channel owner's Friend List ot use LootShare on this channel.");
			player.refreshToggleLootShare();
			return;
		}
		player.toggleLootShare();
		if (player.isToggleLootShare()) {
			player.getPackets().sendGameMessage("LootShare is now active.");
		}
	}

	public void destroyChat() {
		synchronized (this) {
			for (Player player : players) {
				player.setCurrentFriendChat(null);
				player.setCurrentFriendChatOwner(null);
				player.disableLootShare();
				player.getPackets().sendFriendsChatChannel();
				player.getPackets().sendGameMessage(
						"You have been removed from this channel!");
			}
		}
		synchronized (FriendChatsManager.cachedFriendChats) {
			FriendChatsManager.cachedFriendChats.remove(owner);
		}

	}

	public String getChannelName() {
		return settings.getChatName().replaceAll("<img=", "");
	}

	/**
	 * Gets the clanWars.
	 *
	 * @return The clanWars.
	 */
	public ClanWars getClanWars() {
		return clanWars;
	}

	/**
	 * Sets the clanWars.
	 *
	 * @param clanWars
	 *            The clanWars to set.
	 */
	public void setClanWars(ClanWars clanWars) {
		this.clanWars = clanWars;
	}

	public byte[] getDataBlock() {
		return dataBlock;
	}

	public String getOwnerDisplayName() {
		return ownerDisplayName;
	}

	public String getOwnerName() {
		return owner;
	}

	public Player getPlayerByDisplayName(String username) {
		String formatedUsername = Utilities
				.formatPlayerNameForProtocol(username);
		for (Player player : players) {
			if (player.getUsername().equals(formatedUsername)
					|| player.getDisplayName().equals(username))
				return player;
		}
		return null;
	}

	public CopyOnWriteArrayList<Player> getPlayers() {
		return players;
	}

	public int getRank(int rights, String username) {
		if (rights == 2)
			return 127;
		if (username.equals(owner))
			return 7;
		return settings.getRank(username);
	}

	public int getWhoCanKickOnChat() {
		return settings.getWhoCanKickOnChat();
	}

	private void joinChat(Player player) {
		synchronized (this) {
			if (!player.getUsername().equals(owner)
					&& !settings.hasRankToJoin(player.getUsername())
					&& player.getRights() < 2) {
				player.getPackets()
						.sendGameMessage(
								"You do not have a enough rank to join this friends chat channel.");
				return;
			}
			if (players.size() >= 100) {
				player.getPackets().sendGameMessage("This chat is full.");
				return;
			}
			Long bannedSince = bannedPlayers.get(player.getUsername());
			if (bannedSince != null) {
				if (bannedSince + 3600000 > Utilities.currentTimeMillis()) {
					player.getPackets().sendGameMessage(
							"You have been banned from this channel.");
					return;
				}
				bannedPlayers.remove(player.getUsername());
			}
			joinChatNoCheck(player);
		}
	}

	private void joinChatNoCheck(Player player) {
		synchronized (this) {
			players.add(player);
			player.setCurrentFriendChat(this);
			player.setCurrentFriendChatOwner(owner);
			player.getPackets().sendGameMessage(
					"You are now talking in the friends chat channel "
							+ settings.getChatName());
			refreshChannel();
		}
	}

	public void kickPlayerFromChat(Player player, String username) {
		String name = "";
		for (char character : username.toCharArray()) {
			name += Utilities.containsInvalidCharacter(character) ? " "
					: character;
		}
		synchronized (this) {
			int rank = getRank(player.getRights(), player.getUsername());
			if (rank < getWhoCanKickOnChat())
				return;
			Player kicked = getPlayerByDisplayName(name);
			if (kicked == null) {
				player.getPackets().sendGameMessage(
						"This player is not this channel.");
				return;
			}
			if (rank <= getRank(kicked.getRights(), kicked.getUsername()))
				return;
			kicked.setCurrentFriendChat(null);
			kicked.setCurrentFriendChatOwner(null);
			player.disableLootShare();
			players.remove(kicked);
			bannedPlayers.put(kicked.getUsername(),
					Utilities.currentTimeMillis());
			kicked.getPackets().sendFriendsChatChannel();
			kicked.getPackets().sendGameMessage(
					"You have been kicked from the friends chat channel.");
			player.getPackets().sendGameMessage(
					"You have kicked " + kicked.getUsername()
							+ " from friends chat channel.");
			refreshChannel();

		}
	}

	public void leaveChat(Player player, boolean logout) {
		synchronized (this) {
			player.setCurrentFriendChat(null);
			players.remove(player);
			if (players.size() == 0) {
				synchronized (FriendChatsManager.cachedFriendChats) {
					FriendChatsManager.cachedFriendChats.remove(owner);
				}
			} else {
				refreshChannel();
			}
			if (!logout) {
				player.setCurrentFriendChatOwner(null);
				player.getPackets().sendGameMessage(
						"You have left the channel.");
				player.getPackets().sendFriendsChatChannel();
				player.disableLootShare();
			}
			if (clanWars != null) {
				clanWars.leave(player, false);
			}
		}
	}

	private void refreshChannel() {
		synchronized (this) {
			OutputStream stream = new OutputStream();
			stream.writeString(ownerDisplayName);
			String ownerName = Utilities.formatPlayerNameForDisplay(owner);
			stream.writeByte(getOwnerDisplayName().equals(ownerName) ? 0 : 1);
			if (!getOwnerDisplayName().equals(ownerName)) {
				stream.writeString(ownerName);
			}
			stream.writeLong(Utilities.stringToLong(getChannelName()));
			int kickOffset = stream.getOffset();
			stream.writeByte(0);
			stream.writeByte(getPlayers().size());
			for (Player player : getPlayers()) {
				String displayName = player.getDisplayName();
				String name = Utilities.formatPlayerNameForDisplay(player
						.getUsername());
				stream.writeString(displayName);
				stream.writeByte(displayName.equals(name) ? 0 : 1);
				if (!displayName.equals(name)) {
					stream.writeString(name);
				}
				stream.writeShort(1);
				int rank = getRank(player.getRights(), player.getUsername());
				stream.writeByte(rank);
				stream.writeString(GameConstants.SERVER_NAME);
			}
			dataBlock = new byte[stream.getOffset()];
			stream.setOffset(0);
			stream.getBytes(dataBlock, 0, dataBlock.length);
			for (Player player : players) {
				dataBlock[kickOffset] = (byte) (player.getUsername().equals(
						owner) ? 0 : getWhoCanKickOnChat());
				player.getPackets().sendFriendsChatChannel();
			}
		}
	}

	public void sendDiceMessage(Player player, String message) {
		synchronized (this) {
			if (!player.getUsername().equals(owner)
					&& !settings.canTalk(player) && player.getRights() < 2) {
				player.getPackets()
						.sendGameMessage(
								"You do not have a enough rank to talk on this friends chat channel.");
				return;
			}
			for (Player p2 : players) {
				p2.getPackets().sendGameMessage(message);
			}
		}
	}

	public void sendMessage(Player player, String message) {
		synchronized (this) {
			if (!player.getUsername().equals(owner)
					&& !settings.canTalk(player) && player.getRights() < 2) {
				player.getPackets()
						.sendGameMessage(
								"You do not have a enough rank to talk on this friends chat channel.");
				return;
			}
			String formatedName = Utilities.formatPlayerNameForDisplay(player
					.getUsername());
			String displayName = player.getDisplayName();
			int rights = player.getMessageIcon();
			for (Player p2 : players) {
				p2.getPackets().receiveFriendChatMessage(formatedName,
						displayName, rights, settings.getChatName(), message);
			}
		}
	}

	public void sendQuickMessage(Player player, QuickChatMessage message) {
		synchronized (this) {
			if (!player.getUsername().equals(owner)
					&& !settings.canTalk(player) && player.getRights() < 2) {
				player.getPackets()
						.sendGameMessage(
								"You do not have a enough rank to talk on this friends chat channel.");
				return;
			}
			String formatedName = Utilities.formatPlayerNameForDisplay(player
					.getUsername());
			String displayName = player.getDisplayName();
			int rights = player.getMessageIcon();
			for (Player p2 : players) {
				p2.getPackets().receiveFriendChatQuickMessage(formatedName,
						displayName, rights, settings.getChatName(), message);
			}
		}
	}
}


text:
// @ts-check

const testWebLocation = require.resolve('@vscode/test-web');

const fs = require('fs');
const path = require('path');
const cp = require('child_process');

const minimist = require('minimist');
const fancyLog = require('fancy-log');
const ansiColors = require('ansi-colors');
const remote = require('gulp-remote-retry-src');
const vfs = require('vinyl-fs');
const opn = require('opn');

const APP_ROOT = path.join(__dirname, '..');
const WEB_DEV_EXTENSIONS_ROOT = path.join(APP_ROOT, '.build', 'builtInWebDevExtensions');

const WEB_PLAYGROUND_VERSION = '0.0.13';

async function main() {

	const args = minimist(process.argv.slice(2), {
		boolean: [
			'help',
			'playground'
		],
		string: [
			'host',
			'port',
			'extensionPath',
			'browser',
			'browserType'
		],
	});

	if (args.help) {
		console.log(
			'./scripts/code-web.sh|bat [options]\n' +
			' --playground             Include the vscode-web-playground extension (added by default if no folderPath is provided)\n'
		);
		startServer(['--help']);
		return;
	}

	const serverArgs = [];

	const HOST = args['host'] ?? 'localhost';
	const PORT = args['port'] ?? '8080';

	if (args['host'] === undefined) {
		serverArgs.push('--host', HOST);
	}
	if (args['port'] === undefined) {
		serverArgs.push('--port', PORT);
	}
	if (args['playground'] === true || (args['_'].length === 0 && !args['folder-uri'])) {
		serverArgs.push('--extensionPath', WEB_DEV_EXTENSIONS_ROOT);
		serverArgs.push('--folder-uri', 'memfs:///sample-folder');
		await ensureWebDevExtensions(args['verbose']);
	}

	let openSystemBrowser = false;
	if (!args['browser'] && !args['browserType']) {
		serverArgs.push('--browserType', 'none');
		openSystemBrowser = true;
	}

	serverArgs.push('--sourcesPath', APP_ROOT);

	serverArgs.push(...process.argv.slice(2).filter(v => !v.startsWith('--playground') && v !== '--no-playground'));

	startServer(serverArgs);
	if (openSystemBrowser) {
		opn(`http://${HOST}:${PORT}/`);
	}
}

function startServer(runnerArguments) {
	const env = { ...process.env };

	console.log(`Starting @vscode/test-web: ${testWebLocation} ${runnerArguments.join(' ')}`);
	const proc = cp.spawn(process.execPath, [testWebLocation, ...runnerArguments], { env, stdio: 'inherit' });

	proc.on('exit', (code) => process.exit(code));

	process.on('exit', () => proc.kill());
	process.on('SIGINT', () => {
		proc.kill();
		process.exit(128 + 2); // https://nodejs.org/docs/v14.16.0/api/process.html#process_signal_events
	});
	process.on('SIGTERM', () => {
		proc.kill();
		process.exit(128 + 15); // https://nodejs.org/docs/v14.16.0/api/process.html#process_signal_events
	});
}

async function directoryExists(path) {
	try {
		return (await fs.promises.stat(path)).isDirectory();
	} catch {
		return false;
	}
}

async function ensureWebDevExtensions(verbose) {

	// Playground (https://github.com/microsoft/vscode-web-playground)
	const webDevPlaygroundRoot = path.join(WEB_DEV_EXTENSIONS_ROOT, 'vscode-web-playground');
	const webDevPlaygroundExists = await directoryExists(webDevPlaygroundRoot);

	let downloadPlayground = false;
	if (webDevPlaygroundExists) {
		try {
			const webDevPlaygroundPackageJson = JSON.parse(((await fs.promises.readFile(path.join(webDevPlaygroundRoot, 'package.json'))).toString()));
			if (webDevPlaygroundPackageJson.version !== WEB_PLAYGROUND_VERSION) {
				downloadPlayground = true;
			}
		} catch (error) {
			downloadPlayground = true;
		}
	} else {
		downloadPlayground = true;
	}

	if (downloadPlayground) {
		if (verbose) {
			fancyLog(`${ansiColors.magenta('Web Development extensions')}: Downloading vscode-web-playground to ${webDevPlaygroundRoot}`);
		}
		await new Promise((resolve, reject) => {
			remote(['package.json', 'dist/extension.js', 'dist/extension.js.map'], {
				base: 'https://raw.githubusercontent.com/microsoft/vscode-web-playground/main/'
			}).pipe(vfs.dest(webDevPlaygroundRoot)).on('end', resolve).on('error', reject);
		});
	} else {
		if (verbose) {
			fancyLog(`${ansiColors.magenta('Web Development extensions')}: Using existing vscode-web-playground in ${webDevPlaygroundRoot}`);
		}
	}
}

main();


text:
package org.apache.shardingsphere.underlying.common.database.type;

/**
 * Branch database type.
 */
public interface BranchDatabaseType extends DatabaseType {

    /**
     * Get trunk database type.
     *
     * @return trunk database type
     */
    DatabaseType getTrunkDatabaseType();
}


text:
__all__ = ["memoize", "timer", "primes", "prime", "is_prime",
           "GCD", "LCM", "DivisorSigma", "FactorInteger", "PrimeQ", "PrimePi",
           "fst", "snd", "tco", "Seq"]

from euler import memoize, timer, primes, prime, is_prime, GCD, LCM, DivisorSigma, FactorInteger, fst, snd, PrimeQ, PrimePi

from tco import tco

import Seq