text:
/** API viewer for Sendanor REST Daemon */
module.exports = function(opts) {
	opts = opts || {};

	if(opts.url) {
		opts.url = require('url').parse(opts.url);
	}

	var util = require('util');
	var express = require('express');
	var path = require('path');
	var app = module.exports = express();

	app.set('views', __dirname + '/views');
	app.set('view engine', 'hjs');

	Object.keys(opts).forEach(function(key) {
		app.set('plugin ' + key, opts[key]);
	});

	app.locals({'plugin': opts});

	app.use(express.favicon());
	//app.use(express.logger('dev'));
	//app.use(express.bodyParser());
	app.use(express.json());
	app.use(express.urlencoded());
	app.use(express.methodOverride());

	app.use(app.router);

	app.use(express.static(path.join(__dirname, 'public')));

	// development only
	if ('development' === app.get('env')) {
		app.use(express.errorHandler());
	}

	app.use(function(req, res, next) {

		req.locals.body = JSON.stringify(req.locals.body, null, 2).replace(/\"(https?:[^\"]+)\"/g, '"$1"');

		res.render('index', { title: req.url, 'code':req.locals.body, 'codelang':'javascript' });
	});

	return app;
};
/* EOF */


text:
package com.musicbubble.model;

import javax.persistence.*;

/**
 * Created by happyfarmer on 12/16/2016.
 */
@Entity
@Table(name = "image", schema = "db_03", catalog = "")
public class ImageEntity {
    private int imageId;
    private String imageType;
    private String imageUri;

    @Id
    @Column(name = "image_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    @Basic
    @Column(name = "image_type", nullable = true, length = 1)
    public String getImageType() {
        return imageType;
    }

    public void setImageType(String imageType) {
        this.imageType = imageType;
    }

    @Basic
    @Column(name = "image_uri", nullable = true, length = 255)
    public String getImageUri() {
        return imageUri;
    }

    public void setImageUri(String imageUri) {
        this.imageUri = imageUri;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ImageEntity that = (ImageEntity) o;

        if (imageId != that.imageId) return false;
        if (imageType != null ? !imageType.equals(that.imageType) : that.imageType != null) return false;
        if (imageUri != null ? !imageUri.equals(that.imageUri) : that.imageUri != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = imageId;
        result = 31 * result + (imageType != null ? imageType.hashCode() : 0);
        result = 31 * result + (imageUri != null ? imageUri.hashCode() : 0);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/ commands;
- (void)showAsyncWithSuccess:(void (^)(RTObject<WUPIUICommand>*))success failure:(void (^)(NSError*))failure;
@end

#endif // __WUPMessageDialog_DEFINED__

// Windows.UI.Popups.UICommand
#ifndef __WUPUICommand_DEFINED__
#define __WUPUICommand_DEFINED__

OBJCUWPWINDOWSUIPOPUPSEXPORT
@interface WUPUICommand : RTObject <WUPIUICommand>
+ (instancetype)make __attribute__ ((ns_returns_retained));
+ (WUPUICommand*)make:(NSString *)label ACTIVATOR;
+ (WUPUICommand*)makeWithHandler:(NSString *)label action:(WUPUICommandInvokedHandler)action ACTIVATOR;
+ (WUPUICommand*)makeWithHandlerAndId:(NSString *)label action:(WUPUICommandInvokedHandler)action commandId:(RTObject*)commandId ACTIVATOR;
#if defined(__cplusplus)
+ (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased));
#endif
@property (retain) NSString * label;
@property (copy) WUPUICommandInvokedHandler invoked;
@property (retain) RTObject* id;
@end

#endif // __WUPUICommand_DEFINED__

// Windows.UI.Popups.UICommandSeparator
#ifndef __WUPUICommandSeparator_DEFINED__
#define __WUPUICommandSeparator_DEFINED__

OBJCUWPWINDOWSUIPOPUPSEXPORT
@interface WUPUICommandSeparator : RTObject <WUPIUICommand>
+ (instancetype)make __attribute__ ((ns_returns_retained));
#if defined(__cplusplus)
+ (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased));
#endif
@property (retain) NSString * label;
@property (copy) WUPUICommandInvokedHandler invoked;
@property (retain) RTObject* id;
@end

#endif // __WUPUICommandSeparator_DEFINED__

// Windows.UI.Popups.PopupMenu
#ifndef __WUPPopupMenu_DEFINED__
#define __WUPPopupMenu_DEFINED__

OBJCUWPWINDOWSUIPOPUPSEXPORT
@interface WUPPopupMenu : RTObject
+ (instancetype)make __attribute__ ((ns_returns_retained));
#if defined(__cplusplus)
+ (instancetype)createWith:(IInspectable*)obj __attribute__ ((ns_returns_autoreleased));
#endif
@property (readonly) NSMutableArray* /* RTObject<WUPIUICommand>* */ commands;
- (void)showAsync:(WFPoint*)invocationPoint success:(void (^)(RTObject<WUPIUICommand>*))success failure:(void (^)(NSError*))failure;
- (void)showAsyncWithRect:(WFRect*)selection success:(void (^)(RTObject<WUPIUICommand>*))success failure:(void (^)(NSError*))failure;
- (void)showAsyncWithRectAndPlacement:(WFRect*)selection preferredPlacement:(WUPPlacement)preferredPlacement success:(void (^)(RTObject<WUPIUICommand>*))success failure:(void (^)(NSError*))failure;
@end

#endif // __WUPPopupMenu_DEFINED__


text:
/**
 * @file otf格式转ttf格式对象
 * @author mengke01(kekee000@gmail.com)
 */

import error from './error';
import OTFReader from './otfreader';
import otfContours2ttfContours from './util/otfContours2ttfContours';
import {computePathBox} from '../graphics/computeBoundingBox';

/**
 * otf格式转ttf格式对象
 *
 * @param  {ArrayBuffer|otfObject} otfBuffer 原始数据或者解析后的otf数据
 * @param  {Object} options   参数
 * @return {Object}          ttfObject对象
 */
export default function otf2ttfobject(otfBuffer, options) {
    let otfObject;
    if (otfBuffer instanceof ArrayBuffer) {
        const otfReader = new OTFReader(options);
        otfObject = otfReader.read(otfBuffer);
        otfReader.dispose();
    }
    else if (otfBuffer.head && otfBuffer.glyf && otfBuffer.cmap) {
        otfObject = otfBuffer;
    }
    else {
        error.raise(10111);
    }

    // 转换otf轮廓
    otfObject.glyf.forEach((g) => {
        g.contours = otfContours2ttfContours(g.contours);
        const box = computePathBox(...g.contours);
        if (box) {
            g.xMin = box.x;
            g.xMax = box.x + box.width;
            g.yMin = box.y;
            g.yMax = box.y + box.height;
            g.leftSideBearing = g.xMin;
        }
        else {
            g.xMin = 0;
            g.xMax = 0;
            g.yMin = 0;
            g.yMax = 0;
            g.leftSideBearing = 0;
        }
    });

    otfObject.version = 0x1;

    // 修改maxp相关配置
    otfObject.maxp.version = 1.0;
    otfObject.maxp.maxZones = otfObject.maxp.maxTwilightPoints ? 2 : 1;

    delete otfObject.CFF;
    delete otfObject.VORG;

    return otfObject;
}


text:
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://14.63.213.32');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>


text:
import React from 'react';

import { FilterSelection, Box } from '../..';
import { Status } from './FilterSelection';

export default {
  component: FilterSelection,
  title: 'FilterSelection',
};

const Wrapper = ({ ...props }) =>
;

export const Main = () => (

    {Object.keys(Status).map((status) => (
      <Wrapper key={status}>
        <Box marginRight={2}>
          <FilterSelection status={Status[status]} label={Status[status]} onClick={() => {}} />
        </Box>
        <Box marginRight={2}>
          <FilterSelection status={Status[status]} label={Status[status]} onClick={() => {}} applied />
        </Box>
        <Box marginRight={2}>
          <FilterSelection
            status={Status[status]}
            label={Status[status]}
            onClick={() => {}}
            applied
            amountApplied={3}
          />
        </Box>
      </Wrapper>
    ))}

);


text:
$LOAD_PATH << File.dirname(__FILE__)

require "rubygems"
require "json"
require "time"
require "shelbytv/base"
require "shelbytv/broadcast"
require "shelbytv/channel"
require "shelbytv/channel_proxy"
require "shelbytv/user"
require "shelbytv/user_proxy"

module Shelbytv
end


text:
package cmd

import (
	"os"
	"path"
	"testing"

	"github.com/cilium/cilium/pkg/option"

	"github.com/stretchr/testify/assert"
	"github.com/tidwall/gjson"
)

func TestInstallCNIConfFile(t *testing.T) {
	workdir := t.TempDir()
	opts := &option.DaemonConfig{
		Debug:                          false,
		CNILogFile:                     "/opt\"/cni.log", // test escaping :-)
		CNIChainingMode:                "none",
		CNIExclusive:                   true,
		WriteCNIConfigurationWhenReady: path.Join(workdir, "05-cilium.conflist"),
	}

	touch(t, workdir, "other.conflist")
	touch(t, workdir, "05-cilium.conf") // older config file we no longer create

	err := installCNIConfFile(opts)
	assert.NoError(t, err)

	filenames := ls(t, workdir)

	assert.ElementsMatch(t, filenames, []string{
		"05-cilium.conflist",
		"other.conflist.cilium_bak",
	})

	data, err := os.ReadFile(path.Join(workdir, "05-cilium.conflist"))
	assert.NoError(t, err)
	val := gjson.GetBytes(data, "plugins.0.type")
	assert.Equal(t, val.String(), "cilium-cni")

}

func TestMergeExistingAWSConfig(t *testing.T) {
	opts := &option.DaemonConfig{
		Debug:           false,
		CNILogFile:      "/opt\"/cni.log", // test escaping :-)
		CNIChainingMode: "aws-cni",
	}

	workdir := t.TempDir()
	// write an "existing" AWS config
	existing := `
{
	"cniVersion": "0.4.0",
	"name": "foo",
	"plugins": [
		{
			"type": "a"
		},
		{
			"type": "b"
		}
	]
}
`
	assert.NoError(t, os.WriteFile(path.Join(workdir, "10-aws.conflist"), []byte(existing), 0644))

	res, err := renderCNIConf(opts, workdir)
	assert.NoError(t, err)

	val := gjson.GetBytes(res, `plugins.#`)
	assert.Equal(t, val.Int(), int64(3))

	val = gjson.GetBytes(res, `plugins.@reverse.0.type`)
	assert.Equal(t, val.String(), "cilium-cni")

}

func TestRenderCNIConf(t *testing.T) {
	opts := &option.DaemonConfig{
		Debug:      false,
		CNILogFile: "/opt\"/cni.log", // test escaping :-)
	}
	// check that all templates compile
	for mode := range cniConfigs {
		opts.CNIChainingMode = mode
		conf, err := renderCNIConf(opts, "/")
		assert.NoError(t, err)
		res := gjson.GetBytes(conf, `plugins.#(type=="cilium-cni").log-file`)
		assert.True(t, res.Exists(), mode)
		assert.Equal(t, res.String(), "/opt\"/cni.log", mode)
	}

	assert.Equal(t,
		string(renderCNITemplate(awsCNIEntry, opts)),
		`
{
	"type": "cilium-cni",
	"enable-debug": false,
	"log-file": "/opt\"/cni.log"
}
`,
	)

}

func TestFindFile(t *testing.T) {
	workdir := t.TempDir()

	_, err := findFile(workdir, []string{"a", "b"})
	assert.Error(t, err)

	touch(t, workdir, "b")

	found, _ := findFile(workdir, []string{"a", "b"})
	assert.Equal(t, found, path.Join(workdir, "b"))

	touch(t, workdir, "a")
	found, _ = findFile(workdir, []string{"a", "b"})
	assert.Equal(t, found, path.Join(workdir, "a"))
}

func TestCleanupOtherCNI(t *testing.T) {

	workdir := t.TempDir()

	for _, name := range []string{
		"01-someoneelse.conf",
		"99-test.conflist",
		"42-keep.json",
		"44-dontkeep.json",
	} {
		touch(t, workdir, name)
	}

	if err := cleanupOtherCNI(workdir, "42-keep.json"); err != nil {
		t.Fatal(err)
	}

	filenames := ls(t, workdir)
	assert.ElementsMatch(t, filenames, []string{
		"01-someoneelse.conf.cilium_bak",
		"99-test.conflist.cilium_bak",
		"42-keep.json",
		"44-dontkeep.json.cilium_bak",
	})
}

func touch(t *testing.T, dir, name string) {
	f, err := os.Create(path.Join(dir, name))
	assert.NoError(t, err)
	f.Close()
}

func ls(t *testing.T, dir string) []string {
	files, err := os.ReadDir(dir)
	assert.NoError(t, err)

	filenames := []string{}
	for _, f := range files {
		filenames = append(filenames, f.Name())
	}
	return filenames
}


text:
FROM ubuntu:latest
# Run as soon as the containers starts-up
# Running a command
CMD echo "First custom Docker App by Wojciech, 2018-05-30."


text:
import AsyncStorage from '@react-native-async-storage/async-storage';
import { length, lineString } from '@turf/turf';
import { Button, Card, Divider, Modal, Text, useTheme } from '@ui-kitten/components';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import propTypes from 'prop-types';
import React, { useEffect } from 'react';
import { Alert, StyleSheet, View } from 'react-native';
import { useMutation, useQueryClient } from 'react-query';
import * as Sentry from 'sentry-expo';
import { useAPI } from '../services/api';
import backgroundLocationService from '../services/backgroundLocation';
import config from '../services/config';
import { getIcon } from '../services/icons';
import { useOfflineCache } from '../services/offline';
import { PADDING, RADIUS } from '../services/styles';
import { dateToString, lineCoordinatesToString } from '../services/utilities';
import Spinner from './Spinner';

const STORAGE_KEY = 'wvcr-vehicle-tracking-state';

TaskManager.defineTask(backgroundLocationService.taskName, async ({ data, error }) => {
  if (error) {
    console.log(error);
    Sentry.captureException(error);

    return;
  }

  if (data) {
    const { locations } = data;

    if (locations) {
      backgroundLocationService.notify(locations);
    }
  }
});

const buttonStatuses = {
  idle: 'basic',
  tracking: 'success',
  paused: 'danger',
};

export const initialVehicleTrackingState = {
  status: 'idle',
  isModalVisible: false,
  routeCoordinates: [],
  start: null,
  pickups: [],

  // these are derived...
  isPaused: false,
  isTracking: false,
  buttonStatus: buttonStatuses.idle,
};

export const vehicleTrackingReducer = (draft, action) => {
  switch (action.type) {
    case 'SHOW':
      draft.isModalVisible = true;

      break;

    case 'HIDE':
      draft.isModalVisible = false;

      break;

    case 'START':
      draft.status = 'tracking';
      draft.start = new Date();

      break;

    case 'PAUSE':
      draft.status = 'paused';
      draft.isModalVisible = false;

      break;

    case 'RESUME':
      draft.status = 'tracking';

      break;

    case 'ADD_PICKUP': {
      draft.pickups.push(action.payload);

      break;
    }

    case 'ADD_ROUTE_COORDINATES':
      draft.routeCoordinates = draft.routeCoordinates.concat(action.payload);

      break;
    case 'RESET':
      AsyncStorage.removeItem(STORAGE_KEY);

      return initialVehicleTrackingState;

    case 'RESTORE_FROM_STORAGE':
      return action.payload;

    default:
      throw new Error(`Unhandled action type: ${action.type}`);
  }

  // derived...
  draft.isPaused = draft.status === 'paused';
  draft.isTracking = draft.status === 'tracking' || draft.isPaused;
  draft.buttonStatus = buttonStatuses[draft.status];

  // backup in case phone crashes
  AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(draft));
};

const getDistance = (coords) => {
  if (coords.length < 2) {
    return 'n/a';
  }

  const arrayCoords = coords.map(({ latitude, longitude }) => [longitude, latitude]);

  const line = lineString(arrayCoords);

  const miles = length(line, { units: 'miles' });

  return `${miles.toFixed(2)} miles`;
};

export default function VehicleTracking({ state, dispatch, startTracking, resumeRoute }) {
  const theme = useTheme();

  useEffect(() => {
    return () => {
      backgroundLocationService.unsubscribe();
    };
  }, []);

  useEffect(() => {
    const checkStorage = async () => {
      const backup = await AsyncStorage.getItem(STORAGE_KEY);

      if (backup && JSON.stringify(state) !== backup) {
        const parsedBackup = JSON.parse(backup);
        parsedBackup.start = new Date(parsedBackup.start);

        dispatch({ type: 'RESTORE_FROM_STORAGE', payload: parsedBackup });

        if (parsedBackup.isTracking && !parsedBackup.isPaused) {
          startTracking();
        }
      }
    };

    checkStorage();
  }, []);

  const stopTracking = async () => {
    console.log('stopTracking');

    backgroundLocationService.unsubscribe();

    try {
      const hasStarted = await Location.hasStartedLocationUpdatesAsync(backgroundLocationService.taskName);

      if (hasStarted) {
        await Location.stopLocationUpdatesAsync(backgroundLocationService.taskName);
      }
    } catch (error) {
      console.log(error);
      Sentry.captureException(error);
    }
  };

  const pauseRoute = async () => {
    console.log('pauseRoute');

    await stopTracking();

    dispatch({ type: 'PAUSE' });
  };

  const cancelRoute = () => {
    console.log('cancelRoute');

    Alert.alert('Are you sure?', "Canceled routes are deleted and can't be submitted.", [
      {
        text: 'Cancel',
        style: 'cancel',
      },
      {
        text: 'Discard route',
        onPress: async () => {
          await stopTracking();

          dispatch({ type: 'RESET' });
        },
      },
    ]);
  };

  const { postReport, postRoute } = useAPI();
  const completeRoute = async () => {
    console.log('completeRoute');

    await stopTracking();

    dispatch({ type: 'HIDE' });

    mutation.mutate();
  };

  const confirmCompleteRoute = () => {
    if (state.routeCoordinates.length < 2) {
      Alert.alert('You must have tracked at least two positions to submit a route!');

      return;
    }

    Alert.alert(
      'Are you sure?',
      `Are you sure that you want to stop tracking and submit this route with ${state.pickups.length} pickups?`,
      [
        {
          text: 'Cancel',
          style: 'cancel',
        },
        {
          text: 'Submit route',
          onPress: completeRoute,
        },
      ]
    );
  };
  const [spinnerMessage, setSpinnerMessage] = React.useState('');

  const { isConnected, cacheRoute, cacheReport } = useOfflineCache();
  const submitRoute = async () => {
    const submitValues = {
      start_time: state.start,
      end_time: new Date(),
      geog: lineCoordinatesToString(state.routeCoordinates),
      submit_date: new Date().toISOString(),
    };

    if (!isConnected) {
      await cacheRoute(submitValues, state.pickups);

      dispatch({ type: 'RESET' });

      return;
    }

    setSpinnerMessage('submitting route...');

    let responseJson;
    try {
      responseJson = await postRoute(submitValues);
    } catch (error) {
      await cacheRoute(submitValues, state.pickups, error);

      dispatch({ type: 'RESET' });

      return;
    }

    const submitErrors = [];
    for (let index = 0; index < state.pickups.length; index++) {
      // create a new object since we are adding a prop
      const pickup = { ...state.pickups[index], route_id: responseJson.route_id };

      setSpinnerMessage(`submitting pickup ${index + 1} of ${state.pickups.length}...`);

      try {
        await postReport(pickup, config.REPORT_TYPES.pickup);
      } catch (error) {
        await cacheReport(pickup, error);
        submitErrors.push(error);
      }
    }

    if (submitErrors.length) {
      Alert.alert(
        'Error',
        `Your route has been submitted successfully, but there were errors submitting your pickups. They have been cached on your device for later submission. \n\n${submitErrors
          .map((error) => error.message)
          .join('\n')}`
      );
    } else {
      Alert.alert('Success!', 'Your route has been submitted successfully.');
    }
  };

  const queryClient = useQueryClient();
  const mutation = useMutation(submitRoute, {
    onSuccess: () => {
      queryClient.invalidateQueries(config.QUERY_KEYS.submissions);
      queryClient.invalidateQueries(config.QUERY_KEYS.profile);

      dispatch({ type: 'RESET' });
    },
    onError: (error) => {
      Alert.alert('Error', error.message);
    },
  });

  const CloseIcon = getIcon({
    pack: 'material-community',
    name: 'close',
    size: 25,
    color: theme['color-basic-700'],
  });
  const getHeader = (title) => (
    <View>
      <View style={styles.header}>
        <Text category="h5">{title}</Text>
        <Button accessoryLeft={CloseIcon} size="tiny" appearance="ghost" onPress={close} style={styles.closeButton} />
      </View>
    </View>
  );

  const close = () => {
    console.log('close pressed');
    dispatch({ type: 'HIDE' });
  };

  return (
    <>
      <Modal
        visible={state.isModalVisible}
        backdropStyle={{ backgroundColor: theme['color-basic-transparent-600'] }}
        onBackdropPress={close}
        style={styles.modal}
      >
        <Card disabled={true} header={getHeader('Route')} style={styles.modal}>
          <Text>Start: {state.start ? dateToString(state.start) : null}</Text>
          <Text>Status: {state.status}</Text>
          <Text>Distance: {getDistance(state.routeCoordinates)}</Text>
          <Text>Pickups: {state.pickups?.length}</Text>
          <Divider style={styles.divider} />
          {state.isPaused ? (
            <Button style={styles.button} onPress={resumeRoute}>
              Resume
            </Button>
          ) : (
            <Button style={styles.button} onPress={pauseRoute} status="danger">
              Pause Route
            </Button>
          )}
          <Button style={styles.button} onPress={confirmCompleteRoute} status="info">
            Finish and Submit Route
          </Button>
          <Button style={styles.button} onPress={cancelRoute} appearance="ghost">
            Cancel Route
          </Button>
        </Card>
      </Modal>
      <Spinner show={mutation.isLoading} message={spinnerMessage} />
    </>
  );
}

VehicleTracking.propTypes = {
  state: propTypes.object.isRequired,
  dispatch: propTypes.func.isRequired,
  startTracking: propTypes.func.isRequired,
  resumeRoute: propTypes.func.isRequired,
};

const styles = StyleSheet.create({
  modal: {
    borderRadius: RADIUS,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  divider: {
    marginVertical: PADDING,
  },
  button: {
    marginTop: PADDING,
  },
  closeButton: {
    marginRight: -10,
  },
});


text:
Package.describe({
    name:"qinghai:accounts-entry",
    summary: "Make signin and signout their own pages with routes.",
    version:"0.7.1_8",
    git:"https://github.com/qing-hai/accounts-entry.git#noteon"
});

Package.on_use(function(api) {
  api.versionsFrom('METEOR@0.9.4');

  // CLIENT
  api.use([
    'deps@1.0.5',
    'service-configuration@1.0.2',
    'accounts-base@1.1.2',
    'underscore@1.0.1',
    'templating@1.0.8',
    'handlebars@1.0.1',
    'session@1.0.3',
    'coffeescript@1.0.4']
  , 'client');

  api.add_files([
    'client/entry.coffee',
    'client/entry.css',
    'client/helpers.coffee',
    'client/views/signIn/signIn.html',
    'client/views/signIn/signIn.coffee',
    'client/views/signUp/signUp.html',
    'client/views/signUp/signUp.coffee',
    'client/views/forgotPassword/forgotPassword.html',
    'client/views/forgotPassword/forgotPassword.coffee',
    'client/views/resetPassword/resetPassword.html',
    'client/views/resetPassword/resetPassword.coffee',
    'client/views/social/social.html',
    'client/views/social/social.coffee',
    'client/views/error/error.html',
    'client/views/error/error.coffee',
    'client/views/accountButtons/accountButtons.html',
    'client/views/accountButtons/_wrapLinks.html',
    'client/views/accountButtons/accountButtons.coffee',
    'client/i18n/english.coffee',
    'client/i18n/german.coffee',
    'client/i18n/spanish.coffee'
  ], 'client');

  // SERVER
  api.use([
    'deps@1.0.5',
    'service-configuration@1.0.2',
    'accounts-password@1.0.3',
    'accounts-base@1.1.2',
    'underscore@1.0.1',
    'coffeescript@1.0.4'
  ], 'server');

  api.add_files(['server/entry.coffee'], 'server');

  // CLIENT and SERVER
  api.imply('accounts-base', ['client', 'server']);
  api.export('AccountsEntry', ['client', 'server']);
  api.use('iron:router@0.9.4', ['client', 'server']);
  api.use('anti:i18n@0.4.3', ['client', 'server']);
  api.add_files(['shared/router.coffee'], ['client', 'server']);

});


text:
// Infinite list that can be scrolled up or down
// with more data being fetched as necessary
//

/* eslint-env browser */
/* global $ */

'use strict';

const _      = require('lodash');
const Steady = require('steady');

// Delays after successful and failed xhr request respectively.
//
// For example, suppose user continuously scrolls. If server is up, each
// subsequent request will be sent each 100 ms. If server goes down, the
// interval between request initiations goes up to 2000 ms.
//
const DELAY_AFTER_SUCCESS = 100;
const DELAY_AFTER_ERROR   = 2000;

// Size of the area on the border of the list (in pixels) where
// prefetch starts when user scrolls into it.
//
const ACTIVE_AREA_SIZE = 500;

function ScrollableList(options) {
  this.N = options.N;

  this.options = {
    // Container selector
    //
    list_selector: options.list_selector,

    // Selector of each item directly inside the container
    //
    item_selector: options.item_selector,

    // Selectors used to show/hide loading placeholders
    //
    placeholder_top_selector:    options.placeholder_top_selector,
    placeholder_bottom_selector: options.placeholder_bottom_selector,

    // Function used to get element identifier used for fetching,
    // it can be mongo _id, search skip or last post id depending on content.
    //
    // Syntax: get_content_id(item) -> String
    //
    get_content_id: options.get_content_id,

    // Function used to load more content when user scrolls
    //
    // Syntax: load(start, direction) -> { $html, locals, reached_end }
    //
    // Arguments:
    //  - start - content id of current element (as returned by get_content_id)
    //  - direction - "top" or "bottom"
    //
    // Returns:
    //  - $html - jquery-wrapped rendered html
    //  - locals - server response (used in navigate.content_update)
    //  - offset - index of the first element in html (optional)
    //  - reached_end - flag whether further loading in that direction is possible
    //
    load: options.load || (() => null),

    // Function used to specify item cutting behaviour on large pages
    //
    // Syntax: need_gc(item_count) -> cut_item_count
    //
    // Argument: number of items currently on the page
    // Returns: number of items allowed to cut
    //
    need_gc: options.need_gc || null,

    // Optional event handler that is called on every scroll (debounced),
    //
    // Syntax: on_list_scroll(element, index, offset) -> void
    //
    // If user scrolls inside the list:
    //  - element - top fully visible element as specified by item_selector,
    //              or null if user sees above the list
    //  - index   - 0-based index of said element
    //  - offset  - number of pixels from the element to top of the page
    //              (i.e. navbar), or 0 if user sees above the list
    //
    on_list_scroll: options.on_list_scroll || (() => {}),

    // Vertical position in a viewport at which item is considered to be
    // current for pagination purposes (usually navbar size plus some padding).
    //
    navbar_height: options.navbar_height || 0
  };

  // Approximate number of items not yet fetched at the at the top,
  // used to calculate current item index.
  //
  this.index_offset = options.index_offset || 0;

  // Flags defining whether further loading in respective direction is possible
  //
  this.reached_top    = options.reached_top;
  this.reached_bottom = options.reached_bottom;

  this.top_loading_start    = 0;
  this.bottom_loading_start = 0;

  this.steady_top    = null;
  this.steady_bottom = null;
  this.destroyed     = false;
  this.list = $(options.list_selector)[0];
  this.init();
}

ScrollableList.prototype.init = function () {
  if (this.list) this.add_tracker($(this.list));

  this.scroll_handler = _.debounce(() => {
    let posts = $(this.list).find(this.options.item_selector),
        index;

    // Get offset of the first post in the viewport,
    // "-1" means user sees navigation above all entries
    //
    index = _.sortedIndexBy(posts.toArray(), null, post => {
      if (!post) return this.options.navbar_height;
      return post.getBoundingClientRect().bottom;
    });

    // user sees above the list
    if (index === 0 && posts.length > 0) {
      if (posts[0].getBoundingClientRect().top > this.options.navbar_height) {
        index--;
      }
    }

    // user sees below the list, just change to last element
    if (index >= posts.length) index--;

    let offset = index >= 0 ?
                 this.options.navbar_height - posts[index].getBoundingClientRect().top :
                 $(window).scrollTop();

    this.options.on_list_scroll.call(
      this,
      index >= 0 ? posts[index] : null,
      index + this.index_offset,
      offset
    );
  }, DELAY_AFTER_SUCCESS, { maxWait: DELAY_AFTER_SUCCESS });

  this.scroll_handler();
  $(window).on('scroll', this.scroll_handler);

  // those should be correct already, but check them just in case
  this.reset_loading_placeholders();
};

ScrollableList.prototype.load_top = function () {
  if (this.destroyed) return;
  if (this.reached_top) return;

  let now = Date.now();

  // `top_loading_start` is the last request start time, which is reset to 0 on success
  //
  // Thus, successful requests can restart immediately, but failed ones
  // will have to wait `DELAY_AFTER_ERROR` ms.
  //
  if (Math.abs(this.top_loading_start - now) < DELAY_AFTER_ERROR) return;

  let list = $(this.list);
  let first_element = list.find(this.options.item_selector + ':first')[0];

  // fetch is not supported for an empty list
  if (!first_element) return;

  let content_id = this.options.get_content_id(first_element);

  this.top_loading_start = now;

  Promise.resolve(this.options.load.call(this, content_id, 'top')).then(res => {
    if (this.destroyed) return;

    if (!res || res.reached_end) {
      this.reached_top = true;
      this.reset_loading_placeholders();
    }

    if (!res) {
      this.top_loading_start = 0;
      return;
    }

    // update index of the first element
    if (typeof res.offset !== 'undefined') {
      this.index_offset = res.offset;
    }

    let old_offset_top = first_element.getBoundingClientRect().top;

    // Cut duplicate post, used to display date intervals properly,
    // here's an example showing how it works:
    //
    //   DOM                + fetched           = result
    //                    | ...            |  | ...            |
    //                    +----------------+  +----------------+
    //                    | before         |  | before         |
    //                    | post#37        |  | post#37        |
    //                    | after          |  | after          |
    // +---------------+  +----------------+  +----------------+
    // | before  (cut) |  | before         |  | before         |
    // | post#38       |  | post#38  (cut) |  | post#38        |
    // | after         |  | after    (cut) |  | after          |
    // +---------------+  +----------------+  +----------------+
    // | before        |                      | before         |
    // | post#39       |                      | post#39        |
    // | after         |                      | after          |
    // +---------------+                      +----------------+
    // | ...           |                      | ...            |
    //
    // Reason for this: we don't have the data to display post intervals
    //                  for the first post in the DOM.
    //
    let overlapping_element = res.$html.filter(this.options.item_selector + ':last')[0];

    if (overlapping_element && this.options.get_content_id(overlapping_element) === content_id) {
      let idx = res.$html.index(overlapping_element);
      res.$html = res.$html.slice(0, idx);
      $(first_element).prevAll().remove();
    }

    // deduplication by id
    res.$html.find(this.options.item_selector).each((index, item) => {
      list.remove('#' + item.id);
    });

    return this.N.wire.emit('navigate.content_update', {
      $: res.$html,
      locals: res.locals,
      $before: $(this.options.list_selector + ' > :first')
    }).then(() => {
      if (this.destroyed) return;

      // update scroll so it would point at the same spot as before
      $(window).scrollTop($(window).scrollTop() + first_element.getBoundingClientRect().top - old_offset_top);

      // Limit total amount of posts in DOM
      //
      if (this.options.need_gc) {
        let posts     = $(this.list).find(this.options.item_selector);
        let cut_count = this.options.need_gc(posts.length);

        if (cut_count > 0) {
          // make sure to never remove posts visible on screen,
          // or within active area (so prefetch won't get triggered)
          let last_visible = _.sortedIndexBy(posts.toArray(), null, post => {
            if (!post) return ACTIVE_AREA_SIZE + window.innerHeight;
            return post.getBoundingClientRect().top;
          });

          let cut_start = Math.max(last_visible, posts.length - cut_count - 1);

          if (cut_start < posts.length - 1) {
            $(posts[cut_start]).nextAll().remove();

            this.reached_bottom = false;
            this.reset_loading_placeholders();
          }
        }
      }

      // update scroll so it would point at the same spot as before
      $(window).scrollTop($(window).scrollTop() + first_element.getBoundingClientRect().top - old_offset_top);

      // reset lock
      this.top_loading_start = 0;
    }).catch(err => this.error(err));
  });
};

ScrollableList.prototype.load_bottom = function () {
  if (this.destroyed) return;
  if (this.reached_bottom) return;

  let now = Date.now();

  // `bottom_loading_start` is the last request start time, which is reset to 0 on success
  //
  // Thus, successful requests can restart immediately, but failed ones
  // will have to wait `DELAY_AFTER_ERROR` ms.
  //
  if (Math.abs(this.bottom_loading_start - now) < DELAY_AFTER_ERROR) return;

  let list = $(this.list);
  let last_element = list.find(this.options.item_selector + ':last')[0];

  // fetch is not supported for an empty list
  if (!last_element) return;

  let content_id = this.options.get_content_id(last_element);

  this.bottom_loading_start = now;

  Promise.resolve(this.options.load.call(this, content_id, 'bottom')).then(res => {
    if (this.destroyed) return;

    if (!res || res.reached_end) {
      this.reached_bottom = true;
      this.reset_loading_placeholders();
    }

    if (!res) {
      this.bottom_loading_start = 0;
      return;
    }

    // update index of the first element
    if (typeof res.offset !== 'undefined') {
      this.index_offset = res.offset - list.find(this.options.item_selector).length;
    }

    let old_offset_top = last_element.getBoundingClientRect().top;

    // Cut duplicate post, used to display date intervals properly,
    // here's an example showing how it works:
    //
    //   DOM                + fetched           = result
    // | ...           |                      | ...            |
    // +---------------+                      +----------------+
    // | before        |                      | before         |
    // | post#37       |                      | post#37        |
    // | after         |                      | after          |
    // +---------------+  +----------------+  +----------------+
    // | before        |  | before   (cut) |  | before         |
    // | post#38       |  | post#38  (cut) |  | post#38        |
    // | after   (cut) |  | after          |  | after          |
    // +---------------+  +----------------+  +----------------+
    //                    | before         |  | before         |
    //                    | post#39        |  | post#39        |
    //                    | after          |  | after          |
    //                    +----------------+  +----------------+
    //                    | ...            |  | ...            |
    //
    // Reason for this: we don't have the data to display post intervals
    //                  for the first post in the DOM.
    //
    let overlapping_element = res.$html.filter(this.options.item_selector + ':first')[0];

    if (overlapping_element && this.options.get_content_id(overlapping_element) === content_id) {
      let idx = res.$html.index(overlapping_element);
      res.$html = res.$html.slice(idx + 1);
      $(last_element).nextAll().remove();
    }

    // deduplication by id
    res.$html.find(this.options.item_selector).each((index, item) => {
      list.remove('#' + item.id);
    });

    return this.N.wire.emit('navigate.content_update', {
      $: res.$html,
      locals: res.locals,
      $after: $(this.options.list_selector + ' > :last')
    }).then(() => {
      if (this.destroyed) return;

      // Limit total amount of posts in DOM
      //
      if (this.options.need_gc) {
        let posts     = $(this.list).find(this.options.item_selector);
        let cut_count = this.options.need_gc(posts.length);

        if (cut_count > 0) {
          // make sure to never remove posts visible on screen,
          // or within active area (so prefetch won't get triggered)
          let first_visible = _.sortedIndexBy(posts.toArray(), null, post => {
            if (!post) return -ACTIVE_AREA_SIZE;
            return post.getBoundingClientRect().bottom;
          });

          let cut_start = Math.min(first_visible, cut_count);

          if (cut_start > 0) {
            $(posts[cut_start]).prevAll().remove();

            this.index_offset += cut_start;

            this.reached_top = false;
            this.reset_loading_placeholders();
          }
        }
      }

      // update scroll so it would point at the same spot as before
      $(window).scrollTop($(window).scrollTop() + last_element.getBoundingClientRect().top - old_offset_top);

      // reset lock
      this.bottom_loading_start = 0;
    }).catch(err => this.error(err));
  });
};

ScrollableList.prototype.reset_loading_placeholders = function () {
  if (this.options.placeholder_top_selector) {
    let placeholder = $(this.options.placeholder_top_selector);

    // if first item is loaded, hide top placeholder,
    // adjust scroll if necessary
    if (this.reached_top) {
      if (!placeholder.hasClass('d-none')) {
        $(window).scrollTop($(window).scrollTop() - placeholder.outerHeight(true));
      }

      placeholder.addClass('d-none');
    } else {
      if (placeholder.hasClass('d-none')) {
        $(window).scrollTop($(window).scrollTop() + placeholder.outerHeight(true));
      }

      placeholder.removeClass('d-none');
    }
  }

  if (this.options.placeholder_bottom_selector) {
    let placeholder = $(this.options.placeholder_bottom_selector);

    // if last item is loaded, hide bottom placeholder
    if (this.reached_bottom) {
      placeholder.addClass('d-none');
    } else {
      placeholder.removeClass('d-none');
    }
  }
};

ScrollableList.prototype.add_tracker = function () {
  this.steady_top = new Steady({
    throttle: DELAY_AFTER_SUCCESS,
    handler: (values, done) =>
      Promise.resolve(this.load_top()).then(done, done)
  });

  this.steady_bottom = new Steady({
    throttle: DELAY_AFTER_SUCCESS,
    handler: (values, done) =>
      Promise.resolve(this.load_bottom()).then(done, done)
  });

  this.steady_top.addTracker('list-top', () =>
    this.list.getBoundingClientRect().top
  );

  this.steady_bottom.addTracker('list-bottom', () =>
    this.list.getBoundingClientRect().bottom - window.innerHeight
  );

  this.steady_top.addCondition('min-list-top', -ACTIVE_AREA_SIZE);
  this.steady_bottom.addCondition('max-list-bottom', ACTIVE_AREA_SIZE);
};

ScrollableList.prototype.destroy = function () {
  if (this.steady_top)    this.steady_top.stop();
  if (this.steady_bottom) this.steady_bottom.stop();
  this.steady_top = null;
  this.steady_bottom = null;

  this.scroll_handler.cancel();
  $(window).off('scroll', this.scroll_handler);
  this.scroll_handler = null;

  this.destroyed = true;
};

ScrollableList.prototype.error = function (err) {
  this.N.wire.emit('error', err);
};

module.exports = ScrollableList;


text:
Thread::Thread(QObject* parent)
  : QThread{parent} {
}

Thread::~Thread() {
  quit();
  requestInterruption();
  wait();
}


text:
'use strict';

var R        = require('ramda'),
    apiUtils = require('alien-node-api-utils'),

    // TODO this--
    logUtils = require('alien-node-winston-utils');

var _createLocation = require('../../../models/location/methods/createLocation');

/**
 * Create a location in MySQL
 * @param {Object} req
 * @param {Object} res
 */
function createLocation(req, res) {

  var locationData = R.path(['body'], req);

  try {
    return _createLocation.bind(null, locationData)
      .then(apiUtils.jsonResponseSuccess(req, res))
      .catch(function(err) {
        return apiUtils.jsonResponseError(req, res, R.merge(err, {statusCode : 400}));
      });
  } catch (err) {
    return apiUtils.jsonResponseError(req, res, R.merge(err, {statusCode : 500}));
  }
}

module.exports = createLocation;


text:
plot:
	rst2html README.rst > index.html


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.Serialization;
using System.Threading;

namespace Microsoft.CodeAnalysis.EditAndContinue;

[DataContract]
internal readonly record struct DebuggingSessionId([property: DataMember] int Ordinal)
{
    public override string ToString()
        => Ordinal.ToString();
}


text:
package org.spockframework.runtime;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

import org.spockframework.runtime.model.*;
import org.spockframework.util.*;

import spock.lang.Specification;

/**
 * Builds a SpecInfo from a Class instance.
 *
 * @author Peter Niederwieser
 */
public class SpecInfoBuilder {
  private final Class<?> clazz;
  private final SpecInfo spec = new SpecInfo();

  public SpecInfoBuilder(Class<?> clazz) {
    this.clazz = clazz;
  }

  public SpecInfo build() {
    doBuild();
    int order = 0;
    for (SpecInfo curr : spec.getSpecsTopToBottom())
      for (FeatureInfo feature : curr.getFeatures()) {
        feature.setDeclarationOrder(order); // lift declaration order to spec hierarchy
        feature.setExecutionOrder(order);
        order++;
      }

    return spec;
  }

  private SpecInfo doBuild() {
    buildSuperSpec();
    buildSpec();
    buildFields();
    buildSharedInstanceField();
    buildFeatures();
    buildInitializerMethods();
    buildFixtureMethods();
    return spec;
  }

  private void buildSuperSpec() {
    Class<?> superClass = clazz.getSuperclass();
    if (superClass == Object.class || superClass == Specification.class) return;

    SpecInfo superSpec = new SpecInfoBuilder(superClass).doBuild();
    spec.setSuperSpec(superSpec);
    superSpec.setSubSpec(spec);
  }

  private void buildSpec() {
    SpecUtil.checkIsSpec(clazz);

    SpecMetadata metadata = clazz.getAnnotation(SpecMetadata.class);
    spec.setParent(null);
    spec.setName(clazz.getSimpleName());
    spec.setLine(metadata.line());
    spec.setReflection(clazz);
    spec.setFilename(metadata.filename());
  }

  private void buildFields() {
    for (Field field : clazz.getDeclaredFields()) {
      FieldMetadata metadata = field.getAnnotation(FieldMetadata.class);
      if (metadata == null) continue;

      FieldInfo fieldInfo = new FieldInfo();
      fieldInfo.setParent(spec);
      fieldInfo.setReflection(field);
      fieldInfo.setName(metadata.name());
      fieldInfo.setOrdinal(metadata.ordinal());
      fieldInfo.setLine(metadata.line());
      spec.addField(fieldInfo);
    }

    Collections.sort(spec.getFields(), new Comparator<FieldInfo>() {
      public int compare(FieldInfo f1, FieldInfo f2) {
        return f1.getOrdinal() - f2.getOrdinal();
      }
    });
  }

  private void buildSharedInstanceField() {
    Field field = getSharedInstanceField();
    FieldInfo fieldInfo = new FieldInfo();
    fieldInfo.setParent(spec);
    fieldInfo.setName(field.getName());
    fieldInfo.setReflection(field);
    spec.setSharedInstanceField(fieldInfo);
  }

  private Field getSharedInstanceField() {
    try {
      return clazz.getField(InternalIdentifiers.SHARED_INSTANCE_NAME);
    } catch (NoSuchFieldException e) {
      throw new InternalSpockError("cannot find shared instance field");
    }
  }

  private void buildFeatures() {
    for (Method method : clazz.getDeclaredMethods()) {
      FeatureMetadata metadata = method.getAnnotation(FeatureMetadata.class);
      if (metadata == null) continue;
      method.setAccessible(true);
      spec.addFeature(createFeature(method, metadata));
    }

    spec.sortFeatures(new IFeatureSortOrder() {
      public int compare(FeatureInfo m1, FeatureInfo m2) {
        return m1.getDeclarationOrder() - m2.getDeclarationOrder();
      }
    });
  }

  private FeatureInfo createFeature(Method method, FeatureMetadata featureMetadata) {
    FeatureInfo feature = new FeatureInfo();
    feature.setParent(spec);
    feature.setName(featureMetadata.name());
    feature.setLine(featureMetadata.line());
    feature.setDeclarationOrder(featureMetadata.ordinal());
    for (String name : featureMetadata.parameterNames())
      feature.addParameterName(name);

    MethodInfo featureMethod = new MethodInfo();
    featureMethod.setParent(spec);
    featureMethod.setName(featureMetadata.name());
    featureMethod.setLine(featureMetadata.line());
    featureMethod.setFeature(feature);
    featureMethod.setReflection(method);
    featureMethod.setKind(MethodKind.FEATURE);
    feature.setFeatureMethod(featureMethod);

    String processorMethodName = InternalIdentifiers.getDataProcessorName(method.getName());
    MethodInfo dataProcessorMethod = createMethod(processorMethodName, MethodKind.DATA_PROCESSOR, false);

    if (dataProcessorMethod != null) {
      feature.setDataProcessorMethod(dataProcessorMethod);
      int providerCount = 0;
      String providerMethodName = InternalIdentifiers.getDataProviderName(method.getName(), providerCount++);
      MethodInfo providerMethod = createMethod(providerMethodName, MethodKind.DATA_PROVIDER, false);
      while (providerMethod != null) {
        feature.addDataProvider(createDataProvider(feature, providerMethod));
        providerMethodName = InternalIdentifiers.getDataProviderName(method.getName(), providerCount++);
        providerMethod = createMethod(providerMethodName, MethodKind.DATA_PROVIDER, false);
      }
    }

    for (BlockMetadata blockMetadata : featureMetadata.blocks()) {
      BlockInfo block = new BlockInfo();
      block.setKind(blockMetadata.kind());
      block.setTexts(Arrays.asList(blockMetadata.texts()));
      feature.addBlock(block);
    }

    return feature;
  }

  private DataProviderInfo createDataProvider(FeatureInfo feature, MethodInfo method) {
    DataProviderMetadata metadata = method.getReflection().getAnnotation(DataProviderMetadata.class);

    DataProviderInfo provider = new DataProviderInfo();
    provider.setParent(feature);
    provider.setLine(metadata.line());
    provider.setDataVariables(Arrays.asList(metadata.dataVariables()));
    provider.setDataProviderMethod(method);
    return provider;
  }

  private MethodInfo createMethod(String name, MethodKind kind, boolean allowStub) {
    Method reflection = findMethod(name);
    if (reflection == null && !allowStub) return null;

    MethodInfo methodInfo = new MethodInfo();
    methodInfo.setParent(spec);
    methodInfo.setName(name);
    methodInfo.setReflection(reflection);
    methodInfo.setKind(kind);
    return methodInfo;
  }

  private Method findMethod(String name) {
    for (Method method : spec.getReflection().getDeclaredMethods())
      if (method.getName().equals(name)) {
        method.setAccessible(true);
        return method;
      }
    return null;
  }

  private void buildInitializerMethods() {
    spec.setInitializerMethod(createMethod(InternalIdentifiers.INITIALIZER_METHOD, MethodKind.INITIALIZER, true));
    spec.setSharedInitializerMethod(createMethod(InternalIdentifiers.SHARED_INITIALIZER_METHOD, MethodKind.SHARED_INITIALIZER, true));
  }

  private void buildFixtureMethods() {
    spec.setSetupMethod(createMethod(Identifiers.SETUP_METHOD, MethodKind.SETUP, true));
    spec.setCleanupMethod(createMethod(Identifiers.CLEANUP_METHOD, MethodKind.CLEANUP, true));
    spec.setSetupSpecMethod(createMethod(Identifiers.SETUP_SPEC_METHOD, MethodKind.SETUP_SPEC, true));
    spec.setCleanupSpecMethod(createMethod(Identifiers.CLEANUP_SPEC_METHOD, MethodKind.CLEANUP_SPEC, true));
  }
}


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../../../closure-library/closure/goog/base.js"></script>
    <script src="../../../my-deps.js"></script>
    <script>
        goog.require('recoil.db.DatabaseTest');
    </script>
</head>
<body>

</body>
</html>


text:
import mongoengine as me

from st2common.models.db import stormbase
from st2common.constants.types import ResourceType

class TimerDB(stormbase.StormFoundationDB, stormbase.UIDFieldMixin):
    """
    Note: Right now timer is a meta model which is not persisted in the database (it's only used
    for RBAC purposes).

    Attribute:
        name: Timer name - maps to the URL path (e.g. st2/ or my/webhook/one).
    """

    RESOURCE_TYPE = ResourceType.TIMER
    UID_FIELDS = ['pack', 'name']

    name = me.StringField(required=True)
    pack = me.StringField(required=True, unique_with='name')
    type = me.StringField()
    parameters = me.DictField()

    def __init__(self, *args, **values):
        super(TimerDB, self).__init__(*args, **values)
        self.uid = self.get_uid()


text:
#import <Foundation/NSObject.h>

@class NSArray;

@interface NSOrderedPerform : NSObject {
    SEL _selector;
    id _target;
    id _argument;
    NSUInteger _order;
    NSArray *_modes;
}

+ (NSOrderedPerform *)orderedPerformWithSelector:(SEL)selector target:target argument:argument order:(NSUInteger)order modes:(NSArray *)modes;

- (SEL)selector;
- (id)target;
- (id)argument;
- (NSUInteger)order;

- (BOOL)fireInMode:(NSString *)mode;

@end


text:
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Expressions;
using FluentMigrator.Model;
using FluentMigrator.Runner.Generators.Postgres;
using NUnit.Framework;
using NUnit.Should;

namespace FluentMigrator.Tests.Unit.Generators.Postgres
{
    [TestFixture]
    public class PostgresGeneratorTests
    {
        protected PostgresGenerator Generator;

        [SetUp]
        public void Setup()
        {
            Generator = new PostgresGenerator();
        }

        [Test]
        public void CanCreateAutoIncrementColumnForInt64()
        {
            var expression = GeneratorTestHelper.GetCreateTableWithAutoIncrementExpression();
            expression.Columns[0].Type = DbType.Int64;

            var result = Generator.Generate(expression);
            result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" bigserial NOT NULL, \"TestColumn2\" integer NOT NULL)");
        }

        [Test]
        public void CanCreateTableWithBinaryColumnWithSize()
        {
            var expression = GeneratorTestHelper.GetCreateTableExpression();
            expression.Columns[0].Type = DbType.Binary;
            expression.Columns[0].Size = 10000;

            var result = Generator.Generate(expression);
            result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" bytea NOT NULL, \"TestColumn2\" integer NOT NULL)"); // PostgreSQL does not actually use the configured size
        }

        [Test]
        public void CanCreateTableWithBoolDefaultValue()
        {
            var expression = GeneratorTestHelper.GetCreateTableExpression();
            expression.Columns[0].DefaultValue = true;

            var result = Generator.Generate(expression);
            result.ShouldBe("CREATE TABLE \"public\".\"TestTable1\" (\"TestColumn1\" text NOT NULL DEFAULT true, \"TestColumn2\" integer NOT NULL)");
        }

        [Test]
        public void CanUseSystemMethodCurrentUserAsADefaultValueForAColumn()
        {
            const string tableName = "NewTable";
            var columnDefinition = new ColumnDefinition { Name = "NewColumn", Size = 15, Type = DbType.String, DefaultValue = SystemMethods.CurrentUser };
            var expression = new CreateColumnExpression { Column = columnDefinition, TableName = tableName };

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(15) NOT NULL DEFAULT current_user");
        }

        [Test]
        public void CanUseSystemMethodCurrentUTCDateTimeAsADefaultValueForAColumn()
        {
            const string tableName = "NewTable";
            var columnDefinition = new ColumnDefinition { Name = "NewColumn", Size = 5, Type = DbType.String, DefaultValue = SystemMethods.CurrentUTCDateTime };
            var expression = new CreateColumnExpression { Column = columnDefinition, TableName = tableName };

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"public\".\"NewTable\" ADD \"NewColumn\" varchar(5) NOT NULL DEFAULT (now() at time zone 'UTC')");
        }

        [Test]
        public void ExplicitUnicodeStringIgnoredForNonSqlServer()
        {
            var expression = new InsertDataExpression {TableName = "TestTable"};
            expression.Rows.Add(new InsertionDataDefinition
                                    {
                                        new KeyValuePair<string, object>("NormalString", "Just'in"),
                                        new KeyValuePair<string, object>("UnicodeString", new ExplicitUnicodeString("codethinked'.com"))
                                    });

            var result = Generator.Generate(expression);
            result.ShouldBe("INSERT INTO \"public\".\"TestTable\" (\"NormalString\",\"UnicodeString\") VALUES ('Just''in','codethinked''.com');");
        }

        [Test]
        public void CanAlterColumnAndSetAsNullable()
        {
            var expression = new AlterColumnExpression
            {
                Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = true },
                SchemaName = "TestSchema",
                TableName = "TestTable1"
            };

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text, ALTER \"TestColumn1\" DROP NOT NULL");
        }

        [Test]
        public void CanAlterColumnAndSetAsNotNullable()
        {
            var expression = new AlterColumnExpression
            {
                Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = false },
                SchemaName = "TestSchema",
                TableName = "TestTable1"
            };

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text, ALTER \"TestColumn1\" SET NOT NULL");
        }

        [Test]
        public void CanAlterDefaultConstraintToNewGuid()
        {
            var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
            expression.DefaultValue = SystemMethods.NewGuid;
            expression.SchemaName = "TestSchema";

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT uuid_generate_v4()");
        }

        [Test]
        public void CanDeleteDefaultConstraint()
        {
            var expression = new DeleteDefaultConstraintExpression
            {
                ColumnName = "TestColumn1",
                SchemaName = "TestSchema",
                TableName = "TestTable1"
            };

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT");
        }

        [Test]
        public void CanAlterDefaultConstraintToCurrentUser()
        {
            var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
            expression.DefaultValue = SystemMethods.CurrentUser;
            expression.SchemaName = "TestSchema";

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT current_user");
        }

        [Test]
        public void CanAlterDefaultConstraintToCurrentDate()
        {
            var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
            expression.DefaultValue = SystemMethods.CurrentDateTime;
            expression.SchemaName = "TestSchema";

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT now()");
        }

        [Test]
        public void CanAlterDefaultConstraintToCurrentUtcDateTime()
        {
            var expression = GeneratorTestHelper.GetAlterDefaultConstraintExpression();
            expression.DefaultValue = SystemMethods.CurrentUTCDateTime;
            expression.SchemaName = "TestSchema";

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" DROP DEFAULT, ALTER \"TestColumn1\" SET DEFAULT (now() at time zone 'UTC')");
        }

        [Test]
        public void CanAlterColumnAndOnlySetTypeIfIsNullableNotSet()
        {
            var expression = new AlterColumnExpression
            {
                Column = new ColumnDefinition { Type = DbType.String, Name = "TestColumn1", IsNullable = null },
                SchemaName = "TestSchema",
                TableName = "TestTable1"
            };

            var result = Generator.Generate(expression);
            result.ShouldBe("ALTER TABLE \"TestSchema\".\"TestTable1\" ALTER \"TestColumn1\" TYPE text");
        }
    }
}


text:
$(function(){

	var filemanager = $('.filemanager'),
		breadcrumbs = $('.breadcrumbs'),
		fileList = filemanager.find('.data');

	//$.get('scan.php', function(data) {
	$.get('{{ path("archivos_ver") }}', function(data) {

		var response = [data],
			currentPath = '',
			breadcrumbsUrls = [];

		var folders = [],
			files = [];

		$(window).on('hashchange', function(){

			goto(window.location.hash);

		}).trigger('hashchange');

		filemanager.find('.search').click(function(){

			var search = $(this);

			search.find('span').hide();
			search.find('input[type=search]').show().focus();

		});

		filemanager.find('input').on('input', function(e){

			folders = [];
			files = [];

			var value = this.value.trim();

			if(value.length) {

				filemanager.addClass('searching');

				window.location.hash = 'search=' + value.trim();

			}

			else {

				filemanager.removeClass('searching');
				window.location.hash = encodeURIComponent(currentPath);

			}

		}).on('keyup', function(e){

			var search = $(this);

			if(e.keyCode == 27) {

				search.trigger('focusout');

			}

		}).focusout(function(e){

			var search = $(this);

			if(!search.val().trim().length) {

				window.location.hash = encodeURIComponent(currentPath);
				search.hide();
				search.parent().find('span').show();

			}

		});

		fileList.on('click', 'li.folders', function(e){
			e.preventDefault();

			var nextDir = $(this).find('a.folders').attr('href');

			if(filemanager.hasClass('searching')) {

				breadcrumbsUrls = generateBreadcrumbs(nextDir);

				filemanager.removeClass('searching');
				filemanager.find('input[type=search]').val('').hide();
				filemanager.find('span').show();
			}
			else {
				breadcrumbsUrls.push(nextDir);
			}

			window.location.hash = encodeURIComponent(nextDir);
			currentPath = nextDir;
		});

		breadcrumbs.on('click', 'a', function(e){
			e.preventDefault();

			var index = breadcrumbs.find('a').index($(this)),
				nextDir = breadcrumbsUrls[index];

			breadcrumbsUrls.length = Number(index);

			window.location.hash = encodeURIComponent(nextDir);

		});

		function goto(hash) {

			hash = decodeURIComponent(hash).slice(1).split('=');

			if (hash.length) {
				var rendered = '';

				if (hash[0] === 'search') {

					filemanager.addClass('searching');
					rendered = searchData(response, hash[1].toLowerCase());

					if (rendered.length) {
						currentPath = hash[0];
						render(rendered);
					}
					else {
						render(rendered);
					}

				}

				else if (hash[0].trim().length) {

					rendered = searchByPath(hash[0]);

					if (rendered.length) {

						currentPath = hash[0];
						breadcrumbsUrls = generateBreadcrumbs(hash[0]);
						render(rendered);

					}
					else {
						currentPath = hash[0];
						breadcrumbsUrls = generateBreadcrumbs(hash[0]);
						render(rendered);
					}

				}

				else {
					currentPath = data.path;
					breadcrumbsUrls.push(data.path);
					render(searchByPath(data.path));
				}
			}
		}

		function generateBreadcrumbs(nextDir){
			var path = nextDir.split('/').slice(0);
			for(var i=1;i<path.length;i++){
				path[i] = path[i-1]+ '/' +path[i];
			}
			return path;
		}

		function searchByPath(dir) {
			var path = dir.split('/'),
				demo = response,
				flag = 0;

			for(var i=0;i<path.length;i++){
				for(var j=0;j<demo.length;j++){
					if(demo[j].name === path[i]){
						flag = 1;
						demo = demo[j].items;
						break;
					}
				}
			}

			demo = flag ? demo : [];
			return demo;
		}

		function searchData(data, searchTerms) {

			data.forEach(function(d){
				if(d.type === 'folder') {

					searchData(d.items,searchTerms);

					if(d.name.toLowerCase().match(searchTerms)) {
						folders.push(d);
					}
				}
				else if(d.type === 'file') {
					if(d.name.toLowerCase().match(searchTerms)) {
						files.push(d);
					}
				}
			});
			return {folders: folders, files: files};
		}

		function render(data) {

			var scannedFolders = [],
				scannedFiles = [];

			if(Array.isArray(data)) {

				data.forEach(function (d) {

					if (d.type === 'folder') {
						scannedFolders.push(d);
					}
					else if (d.type === 'file') {
						scannedFiles.push(d);
					}

				});

			}
			else if(typeof data === 'object') {

				scannedFolders = data.folders;
				scannedFiles = data.files;

			}

			fileList.empty().hide();

			if(!scannedFolders.length && !scannedFiles.length) {
				filemanager.find('.nothingfound').show();
			}
			else {
				filemanager.find('.nothingfound').hide();
			}

			if(scannedFolders.length) {

				scannedFolders.forEach(function(f) {

					var itemsLength = f.items.length,
						name = escapeHTML(f.name),
						icon = '';

					if(itemsLength) {
						icon = '';
					}

					if(itemsLength == 1) {
						itemsLength += ' item';
					}
					else if(itemsLength > 1) {
						itemsLength += ' items';
					}
					else {
						itemsLength = 'Empty';
					}

					var folder = $('
'+icon+'' + name + ' ' + itemsLength + '
');
					folder.appendTo(fileList);
				});

			}

			if(scannedFiles.length) {

				scannedFiles.forEach(function(f) {

					var fileSize = bytesToSize(f.size),
						name = escapeHTML(f.name),
						fileType = name.split('.'),
						icon = '';

					fileType = fileType[fileType.length-1];

					icon = '.'+fileType+'';

					var file = $('
'+icon+''+ name +' '+fileSize+'
');
					file.appendTo(fileList);
				});

			}

			var url = '';

			if(filemanager.hasClass('searching')){

				url = 'Search results: ';
				fileList.removeClass('animated');

			}
			else {

				fileList.addClass('animated');

				breadcrumbsUrls.forEach(function (u, i) {

					var name = u.split('/');

					if (i !== breadcrumbsUrls.length - 1) {
						url += '' + name[name.length-1] + ' → ';
					}
					else {
						url += '' + name[name.length-1] + '';
					}

				});

			}

			breadcrumbs.text('').append(url);

			fileList.animate({'display':'inline-block'});

		}

		function escapeHTML(text) {
			return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
		}

		function bytesToSize(bytes) {
			var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
			if (bytes == 0) return '0 Bytes';
			var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
			return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
		}

	});
});


text:
<!DOCTYPE html>
<html>

  {% include head.html %}

  <body id="page-top" class="index">

    {% include gtm.html %}

    {% include navbar.html %}

    {% include header.html %}

    {% include playgrounds.html %}

    {% include about.html %}

    {% include footer.html %}

    {% include modals.html %}

    {% include javascript.html %}

  </body>

</html>