text:
// Settings handling
define(["sugar-web/datastore"], function (datastore) {
	var settings = {};

	// Default value
	settings.init = function() {
		this.name = "<No name>";
		this.color = 22;
		this.colorvalue = null;
		this.activities = [];
		this.view = 0;
		this.language = "en";
		var navigatorLanguage = navigator.language;
		if (navigatorLanguage) {
			if (navigatorLanguage.indexOf("fr") != -1)
				this.language = "fr";
			else if (navigatorLanguage.indexOf("es") != -1)
				this.language = "es";
			else if (navigatorLanguage.indexOf("de") != -1)
				this.language = "de";
			else if (navigatorLanguage.indexOf("ar") != -1)
				this.language = "ar";
			else if (navigatorLanguage.indexOf("ja") != -1)
				this.language = "ja";
			else if (navigatorLanguage.indexOf("pl") != -1)
				this.language = "pl";
			else if (navigatorLanguage.indexOf("pt") != -1)
				this.language = "pt";
		}
		this.connected = false;
		this.server = null;
		this.networkId = null;
		this.privateJournal = null;
		this.sharedJournal = null;
		this.genericActivity = {directory: "icons", icon: "application-x-generic.svg"};
	}
	settings.init();

	// Load settings from local storage
	settings.load = function(then) {
		// Load settings
		var that = this;
		datastore.localStorage.load(function() {
			var preferences = datastore.localStorage.getValue('sugar_settings');
			if (preferences == null || preferences.name === undefined) {
				if (then) {
					then(false);
				}
				return;
			}
			that.name = preferences.name;
			that.color = preferences.color;
			that.colorvalue = preferences.colorvalue;
			that.view = preferences.view;
			if (preferences.language !== undefined) {
				that.language = preferences.language;
			}
			if (preferences.connected !== undefined) {
				that.connected = preferences.connected;
			}
			if (preferences.server !== undefined) {
				that.server = preferences.server;
			}
			if (preferences.networkId !== undefined) {
				that.networkId = preferences.networkId;
			}

			// Set language
			l10n.language.code = that.language;

			// Load activities
			that.activities = preferences.activities;

			// Load datastore entries for each activity
			that.updateEntries();
			if (then) {
				then(true);
			}
		});
	};

	// Update entries for each activity
	settings.updateEntries = function() {
		for (var i = 0 ; i < this.activities.length ; i++) {
			var activity = this.activities[i];
			activity.instances = datastore.find(activity.id);
			activity.instances.sort(function(e0, e1) {
				return parseInt(e1.metadata.timestamp) - parseInt(e0.metadata.timestamp);
			});
		}
	};

	// Save settings to local storage
	settings.save = function() {
		datastore.localStorage.setValue('sugar_settings', {
			name: this.name,
			color: this.color,
			colorvalue: xoPalette.colors[this.color],
			activities: this.activities,
			view: app.getView(),
			language: this.language,
			connected: this.connected,
			server: this.server,
			networkId: this.networkId
		});
	};

	// Save settings to the server
	settings.saveToServer = function(remoteserver, then) {
		if (this.networkId != null) {
			var that = this;
			remoteserver.putUser(
				this.networkId,
				{
					name: that.name,
					color: xoPalette.colors[that.color],
					language: that.language,
					favorites: that.getFavoritesActivitiesName()
				},
				function(inSender, inResponse) {
					if (then) {
						then();
					}
				},
				function() {
					console.log("WARNING: Error updating network user");
					if (then) {
						then();
					}
				}
			);
		}
		else {
			if (then) {
				then();
			}
		}
	};

	// Merge current settings with the one in parameter
	settings.merge = function(preferences) {
		var changed = false;
		if (preferences.name !== undefined && preferences.name != this.name) { this.name = preferences.name; changed = true; }
		if (preferences.color !== undefined && (preferences.color.fill != this.colorvalue.fill || preferences.color.stroke != this.colorvalue.stroke)) {
			this.colorvalue = preferences.color;
			this.color = util.getColorIndex(this.colorvalue);
			changed = true;
		}
		if (preferences.language !== undefined && preferences.language != this.language) { this.language = preferences.language; changed = true; }
		if (preferences.favorites !== undefined) {
			var favoriteCount = 0;
			for(var i = 0 ; i < this.activities.length ; i++) {
				var wasfavorite = this.activities[i].favorite;
				this.activities[i].favorite = false;
				for (var j = 0 ; j < preferences.favorites.length ; j++) {
					if (preferences.favorites[j] == this.activities[i].id) {
						this.activities[i].favorite = true;
					}
				}
				changed = changed || (wasfavorite != this.activities[i].favorite);
			}
		}
		if (preferences.server !== undefined && preferences.server != this.server) { this.server = preferences.server; changed = true; }
		if (preferences.networkId !== undefined && preferences.networkId != this.networkId) { this.networkId = preferences.networkId; changed = true; }
		if (preferences.private_journal !== undefined && preferences.private_journal != this.privateJournal) { this.privateJournal = preferences.private_journal; }
		if (preferences.shared_journal !== undefined && preferences.shared_journal != this.sharedJournal) { this.sharedJournal = preferences.shared_journal; }
		return changed;
	};

	// Reset settings
	settings.reset = function() {
		datastore.localStorage.removeValue('sugar_settings');
	};

	// Get properties
	settings.getName = function() {
		return this.name;
	};
	settings.getColor = function() {
		return xoPalette.colors[this.color];
	};
	settings.getView = function() {
		return this.view;
	};
	settings.getLanguage = function() {
		return this.language;
	};
	settings.getActivities = function() {
		return this.activities;
	};
	settings.getActivitiesByName = function(name) {
		if (name === undefined || name == null || name.length == 0) {
			return this.activities;
		}
		var activities = this.activities;
		var matching = [];
		for (var i = 0 ; i < activities.length ; i++) {
			if (activities[i].name.toLowerCase().indexOf(name) != -1) {
				matching.push(activities[i]);
			}
		}
		return matching;
	};
	settings.getActivity = function(id) {
		for(var i = 0 ; i < this.activities.length ; i++) {
			if (this.activities[i].id == id) {
				return this.activities[i];
			}
		}
		return this.genericActivity;
	};
	settings.getFavoritesActivities = function() {
		var favorites = [];
		for(var i = 0 ; i < this.activities.length ; i++) {
			if (this.activities[i].favorite) {
				favorites.push(this.activities[i]);
			}
		}
		return favorites;
	};
	settings.getFavoritesActivitiesName = function() {
		var favorites = this.getFavoritesActivities();
		var names = [];
		for(var i = 0 ; i < favorites.length ; i++) {
			names.push(favorites[i].id);
		}
		return names;
	};
	settings.isConnected = function() {
		return this.connected || util.getClientType() == constant.webAppType;
	};
	settings.getServer = function() {
		return this.server;
	};
	settings.getNetworkId = function() {
		return this.networkId;
	};
	settings.getPrivateJournal = function() {
		return this.privateJournal;
	};
	settings.getSharedJournal = function() {
		return this.sharedJournal;
	};

	// Set properties
	settings.setName = function(newname) {
		this.name = newname;
	};
	settings.setColor = function(newcolor) {
		if (newcolor >= 0 && newcolor < xoPalette.colors.length) {
			this.color = newcolor;
		}
	};
	settings.setLanguage = function(newlanguage) {
		this.language = newlanguage;
	};
	settings.setActivities = function(list) {
		this.activities = list;
	};
	settings.setConnected = function(connected) {
		this.connected = connected;
	};
	settings.setServer = function(server) {
		this.server = server;
	};
	settings.setNetworkId = function(nid) {
		this.networkId = nid;
	};
	settings.setPrivateJournal = function(privateJournal) {
		this.privateJournal = privateJournal;
	};
	settings.setSharedJournal = function(sharedJournal) {
		this.sharedJournal = sharedJournal;
	};

	// Update activities
	settings.updateActivities = function(list) {
		// Some activities updated, update it
		var updated = false;
		var seen = 0;
		for (var i = 0 ; i < list.length ; i++) {
			var found = false;
			for (var j = 0 ; !found && j < this.activities.length ; j++) {
				if (list[i].id == this.activities[j].id) {
					found = true;
					seen++;
					if (this.activities[j].version != list[i].version) {
						this.activities[j].name = list[i].name;
						this.activities[j].version = list[i].version;
						this.activities[j].directory = list[i].directory;
						this.activities[j].icon = list[i].icon;
						updated = true;
					}
				}
			}
			if (!found) {
				this.activities.push(list[i]);
				updated = true;
			}
		}

		// Some activities disappeared, remove it
		if (seen != this.activities.length) {
			updated = true;
			var newactivities = [];
			for (var i = 0 ; i < this.activities.length ; i++) {
				var found = false;
				for (var j = 0 ; !found && j < list.length ; j++) {
					if (this.activities[i].id == list[j].id || this.activities[i].type == "native") {
						found = true;
						newactivities.push(this.activities[i]);
					}
				}
			}
			this.activities = newactivities;
		}
		return updated;
	};

	// Color playing
	settings.nextColor = function() {
		this.color = (this.color+1)%xoPalette.colors.length;
	};

	// Activity handling
	settings.runActivity = function(activity, objectId, name, sharedId) {
		if (activity.type != null && activity.type == "native") {
			if (sugarizerOS) {
				sugarizerOS.runActivity(activity.id);
				sugarizerOS.addApplicationToJournal(sugarizerOS.log, activity, datastore);
				return;
			}
			console.log("No sugarizerOS instance found");
		}
		if (activity.activityId == null) {
			activity.activityId = datastore.createUUID();
		}
		this.save();
		var location = activity.directory+"/index.html?aid="+activity.activityId+"&a="+activity.id;
		if (objectId === undefined) {
			if (activity.instances != null && activity.instances.length > 0) {
				location = location + "&o="+activity.instances[0].objectId + "&n="+activity.instances[0].metadata.title;
			} else {
				location = location + "&n=" +activity.name;
			}
		} else if (objectId != null) {
			location = location + "&o=" + objectId + "&n="+name;
		} else {
			location = location + "&n=" +activity.name;
		}
		if (sharedId) {
			location = location + "&s=" + sharedId;
		}
		window.location = location;
	};
	settings.switchFavoriteActivity = function(activity) {
		activity.favorite = !activity.favorite;
		return activity.favorite;
	};
	return settings;
});


text:
jest.autoMockOff();
jest.useFakeTimers();

var CoreManager = require('../CoreManager');
var ParsePromise = require('../ParsePromise').default;
var RESTController = require('../RESTController');
var mockXHR = require('./test_helpers/mockXHR');

CoreManager.setInstallationController({
  currentInstallationId() {
    return ParsePromise.as('iid');
  }
});
CoreManager.set('APPLICATION_ID', 'A');
CoreManager.set('JAVASCRIPT_KEY', 'B');
CoreManager.set('VERSION', 'V');

describe('RESTController', () => {
  it('throws if there is no XHR implementation', () => {
    RESTController._setXHR(null);
    expect(RESTController.ajax.bind(null, 'GET', 'users/me', {})).toThrow(
      'Cannot make a request: No definition of XMLHttpRequest was found.'
    );
  });

  it('opens a XHR with the correct verb and headers', () => {
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.ajax('GET', 'users/me', {}, { 'X-Parse-Session-Token': '123' });
    expect(xhr.setRequestHeader.mock.calls[0]).toEqual(
      [ 'X-Parse-Session-Token', '123' ]
    );
    expect(xhr.open.mock.calls[0]).toEqual([ 'GET', 'users/me', true ]);
    expect(xhr.send.mock.calls[0][0]).toEqual({});
  });

  it('resolves with the result of the AJAX request', (done) => {
    RESTController._setXHR(mockXHR([{ status: 200, response: { success: true }}]));
    RESTController.ajax('POST', 'users', {}).then((response, status, xhr) => {
      expect(response).toEqual({ success: true });
      expect(status).toBe(200);
      done();
    });
  });

  it('retries on 5XX errors', (done) => {
    RESTController._setXHR(mockXHR([
      { status: 500 },
      { status: 500 },
      { status: 200, response: { success: true }}
    ]));
    RESTController.ajax('POST', 'users', {}).then((response, status, xhr) => {
      expect(response).toEqual({ success: true });
      expect(status).toBe(200);
      done();
    });
    jest.runAllTimers();
  });

  it('retries on connection failure', (done) => {
    RESTController._setXHR(mockXHR([
      { status: 0 },
      { status: 0 },
      { status: 0 },
      { status: 0 },
      { status: 0 },
    ]));
    RESTController.ajax('POST', 'users', {}).then(null, (err) => {
      expect(err).toBe('Unable to connect to the Parse API');
      done();
    });
    jest.runAllTimers();
  });

  it('returns a connection error on network failure', (done) => {
    RESTController._setXHR(mockXHR([
      { status: 0 },
      { status: 0 },
      { status: 0 },
      { status: 0 },
      { status: 0 },
    ]));
    RESTController.request('GET', 'classes/MyObject', {}, { sessionToken: '1234' }).then(null, (err) => {
      expect(err.code).toBe(100);
      expect(err.message).toBe('XMLHttpRequest failed: "Unable to connect to the Parse API"');
      done();
    });
    jest.runAllTimers();
  });

  it('aborts after too many failures', (done) => {
    RESTController._setXHR(mockXHR([
      { status: 500 },
      { status: 500 },
      { status: 500 },
      { status: 500 },
      { status: 500 },
      { status: 200, response: { success: true }}
    ]));
    RESTController.ajax('POST', 'users', {}).then(null, (xhr) => {
      expect(xhr).not.toBe(undefined);
      done();
    });
    jest.runAllTimers();
  });

  it('rejects 1XX status codes', (done) => {
    RESTController._setXHR(mockXHR([{ status: 100 }]));
    RESTController.ajax('POST', 'users', {}).then(null, (xhr) => {
      expect(xhr).not.toBe(undefined);
      done();
    });
    jest.runAllTimers();
  });

  it('can make formal JSON requests', () => {
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.request('GET', 'classes/MyObject', {}, { sessionToken: '1234' });
    jest.runAllTicks();
    expect(xhr.open.mock.calls[0]).toEqual(
      ['POST', 'https://api.parse.com/1/classes/MyObject', true]
    );
    expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({
      _method: 'GET',
      _ApplicationId: 'A',
      _JavaScriptKey: 'B',
      _ClientVersion: 'V',
      _InstallationId: 'iid',
      _SessionToken: '1234',
    });
  });

  it('handles request errors', (done) => {
    RESTController._setXHR(mockXHR([{
      status: 400, response: {
        code: -1,
        error: 'Something bad'
      }
    }]));
    RESTController.request('GET', 'classes/MyObject', {}, {})
      .then(null, (error) => {
        expect(error.code).toBe(-1);
        expect(error.message).toBe('Something bad');
        done();
      });
  });

  it('handles invalid responses', (done) => {
    var XHR = function() { };
    XHR.prototype = {
      open: function() { },
      setRequestHeader: function() { },
      send: function() {
        this.status = 200;
        this.responseText = '{';
        this.readyState = 4;
        this.onreadystatechange();
      }
    };
    RESTController._setXHR(XHR);
    RESTController.request('GET', 'classes/MyObject', {}, {})
      .then(null, (error) => {
        expect(error.code).toBe(100);
        expect(error.message.indexOf('XMLHttpRequest failed')).toBe(0);
        done();
      });
  });

  it('handles invalid errors', (done) => {
    var XHR = function() { };
    XHR.prototype = {
      open: function() { },
      setRequestHeader: function() { },
      send: function() {
        this.status = 400;
        this.responseText = '{';
        this.readyState = 4;
        this.onreadystatechange();
      }
    };
    RESTController._setXHR(XHR);
    RESTController.request('GET', 'classes/MyObject', {}, {})
      .then(null, (error) => {
        expect(error.code).toBe(107);
        expect(error.message).toBe('Received an error with invalid JSON from Parse: {');
        done();
      });
  });

  it('attaches the session token of the current user', () => {
    CoreManager.setUserController({
      currentUserAsync() {
        return ParsePromise.as({ getSessionToken: () => '5678' });
      },
      setCurrentUser() {},
      currentUser() {},
      signUp() {},
      logIn() {},
      become() {},
      logOut() {},
      requestPasswordReset() {},
      upgradeToRevocableSession() {},
      linkWith() {},
    });

    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.request('GET', 'classes/MyObject', {}, {});
    jest.runAllTicks();
    expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({
      _method: 'GET',
      _ApplicationId: 'A',
      _JavaScriptKey: 'B',
      _ClientVersion: 'V',
      _InstallationId: 'iid',
      _SessionToken: '5678',
    });
    CoreManager.set('UserController', undefined); // Clean up
  });

  it('attaches no session token when there is no current user', () => {
    CoreManager.setUserController({
      currentUserAsync() {
        return ParsePromise.as(null);
      },
      setCurrentUser() {},
      currentUser() {},
      signUp() {},
      logIn() {},
      become() {},
      logOut() {},
      requestPasswordReset() {},
      upgradeToRevocableSession() {},
      linkWith() {},
    });

    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.request('GET', 'classes/MyObject', {}, {});
    jest.runAllTicks();
    expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({
      _method: 'GET',
      _ApplicationId: 'A',
      _JavaScriptKey: 'B',
      _ClientVersion: 'V',
      _InstallationId: 'iid',
    });
    CoreManager.set('UserController', undefined); // Clean up
  });

  it('sends the revocable session upgrade header when the config flag is set', () => {
    CoreManager.set('FORCE_REVOCABLE_SESSION', true);
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.request('GET', 'classes/MyObject', {}, {});
    jest.runAllTicks();
    expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({
      _method: 'GET',
      _ApplicationId: 'A',
      _JavaScriptKey: 'B',
      _ClientVersion: 'V',
      _InstallationId: 'iid',
      _RevocableSession: '1'
    });
    CoreManager.set('FORCE_REVOCABLE_SESSION', false); // Clean up
  });

  it('sends the master key when requested', () => {
    CoreManager.set('MASTER_KEY', 'M');
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    RESTController.request('GET', 'classes/MyObject', {}, { useMasterKey: true });
    jest.runAllTicks();
    expect(JSON.parse(xhr.send.mock.calls[0][0])).toEqual({
      _method: 'GET',
      _ApplicationId: 'A',
      _MasterKey: 'M',
      _ClientVersion: 'V',
      _InstallationId: 'iid',
    });
  });

  it('throws when attempted to use an unprovided master key', () => {
    CoreManager.set('MASTER_KEY', undefined);
    var xhr = {
      setRequestHeader: jest.genMockFn(),
      open: jest.genMockFn(),
      send: jest.genMockFn()
    };
    RESTController._setXHR(function() { return xhr; });
    expect(function() {
      RESTController.request('GET', 'classes/MyObject', {}, { useMasterKey: true });
    }).toThrow(
      'Cannot use the Master Key, it has not been provided.'
    );
  });
});

redpajama_set_name: RedPajamaGithub


text:
import * as Container from '../../../../util/container'
import * as Constants from '../../../../constants/chat2'
import * as Types from '../../../../constants/types/chat2'
import * as WalletConstants from '../../../../constants/wallets'
import * as WalletTypes from '../../../../constants/types/wallets'
import * as Chat2Gen from '../../../../actions/chat2-gen'
import * as WalletsGen from '../../../../actions/wallets-gen'
import * as RouteTreeGen from '../../../../actions/route-tree-gen'
import AccountPayment from '.'

// Props for rendering the loading indicator
const loadingProps = {
  _paymentID: null,
  action: '',
  amount: '',
  approxWorth: '',
  balanceChange: '',
  balanceChangeColor: undefined,
  cancelButtonInfo: '',
  cancelButtonLabel: '',
  canceled: false,
  claimButtonLabel: '',
  icon: 'iconfont-stellar-send',
  loading: true,
  memo: '',
  pending: false,
  sendButtonLabel: '',
  showCoinsIcon: false,
  sourceAmount: '',
} as const

// Get action phrase for sendPayment msg
const makeSendPaymentVerb = (status: WalletTypes.StatusSimplified, youAreSender: boolean) => {
  switch (status) {
    case 'pending':
      return 'sending'
    case 'canceled': // fallthrough
    case 'claimable':
      return youAreSender ? 'sending' : 'attempting to send'
    case 'error':
      return youAreSender ? 'attempted to send' : 'attempted to send'
    default:
      return 'sent'
  }
}

type OwnProps = {
  message: Types.MessageSendPayment | Types.MessageRequestPayment
}

const ConnectedAccountPayment = Container.connect(
  (state, ownProps: OwnProps) => {
    const acceptedDisclaimer = WalletConstants.getAcceptedDisclaimer(state)
    const you = state.config.username
    const youAreSender = ownProps.message.author === you
    switch (ownProps.message.type) {
      case 'sendPayment': {
        const paymentInfo = Constants.getPaymentMessageInfo(state, ownProps.message)
        if (!paymentInfo) {
          // waiting for service to load it (missed service cache on loading thread)
          return loadingProps
        }

        // find the other participant's username
        const participantInfo = Constants.getParticipantInfo(state, ownProps.message.conversationIDKey)
        const theirUsername = participantInfo.name.find(p => p !== you) || ''

        const cancelable = paymentInfo.status === 'claimable'
        const pending = cancelable || paymentInfo.status === 'pending'
        const canceled = paymentInfo.status === 'canceled'
        const completed = paymentInfo.status === 'completed'
        const verb = makeSendPaymentVerb(paymentInfo.status, youAreSender)
        const sourceAmountDesc = `${paymentInfo.sourceAmount} ${paymentInfo.sourceAsset.code || 'XLM'}`
        const balanceChangeAmount =
          paymentInfo.sourceAmount.length && paymentInfo.delta === 'decrease'
            ? sourceAmountDesc
            : paymentInfo.amountDescription

        const amountDescription = paymentInfo.sourceAmount
          ? `${paymentInfo.amountDescription}/${paymentInfo.issuerDescription}`
          : paymentInfo.amountDescription
        const amount = paymentInfo.worth ? paymentInfo.worth : amountDescription
        return {
          _paymentID: paymentInfo.paymentID,
          action: paymentInfo.worth ? `${verb} Lumens worth` : verb,
          amount,
          approxWorth: paymentInfo.worthAtSendTime,
          balanceChange: completed
            ? `${WalletConstants.balanceChangeSign(paymentInfo.delta, balanceChangeAmount)}`
            : '',
          balanceChangeColor: WalletConstants.getBalanceChangeColor(paymentInfo.delta, paymentInfo.status),
          cancelButtonInfo: paymentInfo.showCancel ? WalletConstants.makeCancelButtonInfo(theirUsername) : '',
          cancelButtonLabel: paymentInfo.showCancel ? 'Cancel' : '',
          canceled,
          claimButtonLabel:
            !youAreSender && cancelable && !acceptedDisclaimer
              ? `Claim${paymentInfo.worth ? ' Lumens worth' : ''}`
              : '',
          icon: pending ? ('iconfont-clock' as const) : null,
          loading: false,
          memo: paymentInfo.note.stringValue(),
          pending: pending || canceled,
          sendButtonLabel: '',
          showCoinsIcon: completed,
          sourceAmount: paymentInfo.sourceAmount.length ? sourceAmountDesc : '',
        }
      }
      case 'requestPayment': {
        const message = ownProps.message
        const requestInfo = Constants.getRequestMessageInfo(state, message)
        if (!requestInfo) {
          // waiting for service to load it
          return loadingProps
        }
        const {amountDescription, asset, canceled, done} = requestInfo
        return {
          _paymentID: null,
          action: asset === 'currency' ? 'requested Lumens worth' : 'requested',
          amount: amountDescription,
          approxWorth: requestInfo.worthAtRequestTime,
          balanceChange: '',
          balanceChangeColor: undefined,
          cancelButtonInfo: '',
          cancelButtonLabel: '',
          canceled,
          claimButtonLabel: '',
          icon: 'iconfont-stellar-request' as const,
          loading: false,
          memo: message.note.stringValue(),
          pending: false,
          sendButtonLabel:
            youAreSender || canceled || done
              ? ''
              : `Send${requestInfo.asset === 'currency' ? ' Lumens worth ' : ' '}`,
          showCoinsIcon: false,
        }
      }
      default:
        // @ts-ignore message is type `never` correctly
        throw new Error(`AccountPayment: impossible case encountered: '${ownProps.message.type}'`)
    }
  },
  (dispatch, {message: {conversationIDKey, ordinal}}) => ({
    _onCancel: (paymentID: WalletTypes.PaymentID | null) => {
      if (paymentID) {
        dispatch(WalletsGen.createCancelPayment({paymentID}))
      }
    },
    onClaim: () => dispatch(RouteTreeGen.createNavigateAppend({path: ['walletOnboarding']})),
    onSend: () => dispatch(Chat2Gen.createPrepareFulfillRequestForm({conversationIDKey, ordinal})),
  }),
  (stateProps, dispatchProps, _: OwnProps) => ({
    action: stateProps.action,
    amount: stateProps.amount,
    approxWorth: stateProps.approxWorth,
    balanceChange: stateProps.balanceChange,
    balanceChangeColor: stateProps.balanceChangeColor,
    cancelButtonInfo: stateProps.cancelButtonInfo,
    cancelButtonLabel: stateProps.cancelButtonLabel,
    canceled: stateProps.canceled,
    claimButtonLabel: stateProps.claimButtonLabel,
    icon: stateProps.icon,
    loading: stateProps.loading,
    memo: stateProps.memo,
    onCancel: () => dispatchProps._onCancel(stateProps._paymentID),
    onClaim: dispatchProps.onClaim,
    onSend: dispatchProps.onSend,
    pending: stateProps.pending,
    sendButtonLabel: stateProps.sendButtonLabel || '',
    showCoinsIcon: stateProps.showCoinsIcon,
    sourceAmount: stateProps.sourceAmount,
  })
)(AccountPayment)
export default ConnectedAccountPayment


text:
001
018
019    package org.apache.hadoop.mapred.join;
020
021    import java.io.DataInput;
022    import java.io.DataOutput;
023    import java.io.IOException;
024    import java.util.HashSet;
025
026    import org.apache.hadoop.classification.InterfaceAudience;
027    import org.apache.hadoop.classification.InterfaceStability;
028    import org.apache.hadoop.io.Text;
029    import org.apache.hadoop.io.WritableUtils;
030    import org.apache.hadoop.mapred.InputSplit;
031    import org.apache.hadoop.util.ReflectionUtils;
032
033    /**
034     * This InputSplit contains a set of child InputSplits. Any InputSplit inserted
035     * into this collection must have a public default constructor.
036     */
037    @InterfaceAudience.Public
038    @InterfaceStability.Stable
039    public class CompositeInputSplit implements InputSplit {
040
041      private int fill = 0;
042      private long totsize = 0L;
043      private InputSplit[] splits;
044
045      public CompositeInputSplit() { }
046
047      public CompositeInputSplit(int capacity) {
048        splits = new InputSplit[capacity];
049      }
050
051      /**
052       * Add an InputSplit to this collection.
053       * @throws IOException If capacity was not specified during construction
054       *                     or if capacity has been reached.
055       */
056      public void add(InputSplit s) throws IOException {
057        if (null == splits) {
058          throw new IOException("Uninitialized InputSplit");
059        }
060        if (fill == splits.length) {
061          throw new IOException("Too many splits");
062        }
063        splits[fill++] = s;
064        totsize += s.getLength();
065      }
066
067      /**
068       * Get ith child InputSplit.
069       */
070      public InputSplit get(int i) {
071        return splits[i];
072      }
073
074      /**
075       * Return the aggregate length of all child InputSplits currently added.
076       */
077      public long getLength() throws IOException {
078        return totsize;
079      }
080
081      /**
082       * Get the length of ith child InputSplit.
083       */
084      public long getLength(int i) throws IOException {
085        return splits[i].getLength();
086      }
087
088      /**
089       * Collect a set of hosts from all child InputSplits.
090       */
091      public String[] getLocations() throws IOException {
092        HashSet<String> hosts = new HashSet<String>();
093        for (InputSplit s : splits) {
094          String[] hints = s.getLocations();
095          if (hints != null && hints.length > 0) {
096            for (String host : hints) {
097              hosts.add(host);
098            }
099          }
100        }
101        return hosts.toArray(new String[hosts.size()]);
102      }
103
104      /**
105       * getLocations from ith InputSplit.
106       */
107      public String[] getLocation(int i) throws IOException {
108        return splits[i].getLocations();
109      }
110
111      /**
112       * Write splits in the following format.
113       * {@code
114       * <count><class1><class2>...<classn><split1><split2>...<splitn>
115       * }
116       */
117      public void write(DataOutput out) throws IOException {
118        WritableUtils.writeVInt(out, splits.length);
119        for (InputSplit s : splits) {
120          Text.writeString(out, s.getClass().getName());
121        }
122        for (InputSplit s : splits) {
123          s.write(out);
124        }
125      }
126
127      /**
128       * {@inheritDoc}
129       * @throws IOException If the child InputSplit cannot be read, typically
130       *                     for faliing access checks.
131       */
132      @SuppressWarnings("unchecked")  // Generic array assignment
133      public void readFields(DataInput in) throws IOException {
134        int card = WritableUtils.readVInt(in);
135        if (splits == null || splits.length != card) {
136          splits = new InputSplit[card];
137        }
138        Class<? extends InputSplit>[] cls = new Class[card];
139        try {
140          for (int i = 0; i < card; ++i) {
141            cls[i] =
142              Class.forName(Text.readString(in)).asSubclass(InputSplit.class);
143          }
144          for (int i = 0; i < card; ++i) {
145            splits[i] = ReflectionUtils.newInstance(cls[i], null);
146            splits[i].readFields(in);
147          }
148        } catch (ClassNotFoundException e) {
149          throw (IOException)new IOException("Failed split init").initCause(e);
150        }
151      }
152
153    }


text:
#include "TTMuteSolo.h"

#define thisTTClass			TTMutesolo
#define thisTTClassName		"mutesolo"
#define thisTTClassTags		"dspEffectsLib, audio, processor"

TT_AUDIO_CONSTRUCTOR,
mInterpolated(0)
{
	TTChannelCount	initialMaxNumChannels = arguments;

	// Initially we have no information stored for any channels
	mStoredStateNumChannels = 0;

	// Register our attributes
	addAttribute(Interpolated,		kTypeBoolean);

	// Register messages
	addMessageWithArguments(setChannelMute);
	addMessageWithArguments(getChannelMute);
	addMessageWithArguments(setChannelSolo);
	addMessageWithArguments(getChannelSolo);
	addMessage(clear);

	// Register for notifications from the parent class so we can allocate memory as required
	addUpdates(MaxNumChannels);

	// Set defaults
	setAttributeValue(kTTSym_maxNumChannels,	initialMaxNumChannels);
	clear();
	setProcessMethod(processAudio);
}

TTMutesolo::~TTMutesolo()
{
	;
}

TTErr TTMutesolo::clear()
{
	mChannelMute.assign(mStoredStateNumChannels, 0.0);
	mChannelSolo.assign(mStoredStateNumChannels, 0.0);
	updateGains();
	return kTTErrNone;
}

TTErr TTMutesolo::updateGains()
{
	TTChannelCount numSoloedChannels = 0;

	// Mute channels, and count the number of soloed channels
	for (TTChannelCount i=0; i<mStoredStateNumChannels; i++) {
		gain[i] = 1.0 - mChannelMute[i];
		if (mChannelSolo[i])
			numSoloedChannels++;
	}
	// If at least one channel is soloed, soloing takes presedence over muting
	if (numSoloedChannels>0) {
		for (TTChannelCount i=0; i<mStoredStateNumChannels; i++) {
			gain[i] = mChannelSolo[i];
		}
	}

	if (mInterpolated)
		setProcessMethod(processAudioInterpolated);

	return kTTErrNone;
}

TTErr TTMutesolo::setChannelMute(const TTValue& aValue, TTValue&)
{
	TTChannelCount channel;

	if (aValue.size() < 2)
		return kTTErrWrongNumValues;
	else {
		channel = aValue[0];

		// It might be necessary to increase the number of channels tracked (channels count from 0, so adding 1)
		increaseStoredStateNumChannels(channel+1);

		// Need to test for floating point as well as integer
		if ((aValue[1] == 0.) || (aValue[1] == 0))
			mChannelMute[channel] = 0.;
		else
			mChannelMute[channel] = 1.;

		return updateGains();
	}
}

TTErr TTMutesolo::setChannelSolo(const TTValue& aValue, TTValue&)
{
	TTChannelCount channel;

	if (aValue.size() < 2)
		return kTTErrWrongNumValues;
	else {
		channel = aValue[0];

		// It might be necessary to increase the number of channels tracked (channels count from 0, so adding 1)
		increaseStoredStateNumChannels(channel+1);

		// Need to test for floating point as well as integer
		if ((aValue[1] == 0.) || (aValue[1] == 0))
			mChannelSolo[channel] = 0.;
		else
			mChannelSolo[channel] = 1.;

		return updateGains();
	}
}

TTErr TTMutesolo::getChannelMute(const TTValue&, TTValue& aMuteValues)
{
	// Report the state for all channels, even if not all of them cureently are being processed.
	aMuteValues.resize(mStoredStateNumChannels);

	for (TTChannelCount i=0; i<mStoredStateNumChannels; i++) {
		aMuteValues[i] = mChannelMute[i];
	}
	return kTTErrNone;
}

TTErr TTMutesolo::getChannelSolo(const TTValue&, TTValue& aSoloValues)
{
	// Report the state for all channels, even if not all of them cureently are being processed.
	aSoloValues.resize(mStoredStateNumChannels);

	for (TTChannelCount i=0; i<mStoredStateNumChannels; i++) {
		aSoloValues[i] = mChannelSolo[i];
	}
	return kTTErrNone;
}

TTErr TTMutesolo::updateMaxNumChannels(const TTValue& oldMaxNumChannels, TTValue&)
{
	// mStoredStateNumChannels might need to be increased.
	return increaseStoredStateNumChannels(mMaxNumChannels);
}

TTErr TTMutesolo::increaseStoredStateNumChannels(TTChannelCount aDesiredChannel)
{
	// Only resize if the vector size need to be increased
	// In the AudioGraph Max implementation (j.mutesolo=) this permits channel solo and mute values to be set before audio/AudioGraph has processed (and hence before the object knows how many channels are to be process).
	if (aDesiredChannel > mStoredStateNumChannels) {

		mStoredStateNumChannels = aDesiredChannel;

		// The resize() method maintains all pre-existing values
		mChannelMute.resize(mStoredStateNumChannels, 0.);
		mChannelSolo.resize(mStoredStateNumChannels, 0.);

		gain.resize(mStoredStateNumChannels, 0.);
		oldGain.resize(mStoredStateNumChannels, 0.);

		updateGains();
	}
	return kTTErrNone;
}

TTErr TTMutesolo::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&	in = inputs->getSignal(0);
	TTAudioSignal&	out = outputs->getSignal(0);
	TTUInt16		vs;
	TTSampleValue	*inSample, *outSample;
	TTChannelCount	numchannels = TTAudioSignal::getMinChannelCount(in, out);
	TTChannelCount	channel;

	for (channel=0; channel<numchannels; channel++) {
		inSample = in.mSampleVectors[channel];
		outSample = out.mSampleVectors[channel];
		vs = in.getVectorSizeAsInt();
		while (vs--)
			*outSample++ = (*inSample++) * gain[channel];
	}
	return kTTErrNone;
}

TTErr TTMutesolo::processAudioInterpolated(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&	in = inputs->getSignal(0);
	TTAudioSignal&	out = outputs->getSignal(0);
	TTUInt16		vs = in.getVectorSizeAsInt();
	TTSampleValue	*inSample, *outSample;
	TTChannelCount	numchannels = TTAudioSignal::getMinChannelCount(in, out);
	TTChannelCount	channel;
	TTFloat64		increment, temp;

	for (channel=0; channel<numchannels; channel++) {
		increment = (gain[channel] - oldGain[channel])/vs;
		TTAntiDenormal(increment);
		temp = oldGain[channel];

		inSample = in.mSampleVectors[channel];
		outSample = out.mSampleVectors[channel];
		vs = in.getVectorSizeAsInt();

		while (vs--){
			temp = temp + increment;
			*outSample++ = (*inSample++) * temp;
		}
		oldGain[channel] = gain[channel];
	}

	setProcessMethod(processAudio);
	return kTTErrNone;
}


text:
Fractions are the bane of existence for many elementary and middle-schoolers. They're sort-of hard to get your head around (though thinking of them as pizza slices turned out to be very helpful for me), but even worse is that they're so hard to calculate with! Even adding them together is no picknick.
Take, for instance, the two fractions 1/6 and 3/10. If they had the same denominator, you could simply add the numerators together, but since they have different denominators, you can't do that. First, you have to make the denominators equal. The easiest way to do that is to use cross-multiplication to make both denominators 60 (i.e. the original denominators multiplied together, 6 * 10). Then the two fractions becomes 10/60 and 18/60, and you can then add those two together to get 28/60.
(if you were a bit more clever, you might have noticed that the lowest common denominator of those fractions is actually 30, not 60, but it doesn't really make much difference).
You might think you're done here, but you're not! 28/60 has not been reduced yet, those two numbers have factors in common! The greatest common divisor of both is 4, so we divide both numerator and denominator with 4 to get 7/15, which is the real answer.
For today's challenge, you will get a list of fractions which you will add together and produce the resulting fraction, reduced as far as possible.
NOTE: Many languages have libraries for rational arithmetic that would make this challenge really easy (for instance, Python's fractions module does exactly this). You are allowed to use these if you wish, but the spirit of this challenge is to try and implement the logic yourself. I highly encourage you to only use libraries like that if you can't figure out how to do it any other way.
Formal inputs & outputs

##Inputs

The input will start with a single number N, specifying how many fractions there are to be added.
After that, there will follow N rows, each one containing a fraction that you are supposed to add into the sum. Each fraction comes in the form "X/Y", so like "1/6" or "3/10", for instance.

##Output

The output will be a single line, containing the resulting fraction reduced so that the numerator and denominator has no factors in common.
Sample inputs & outputs

##Input 1
```
2
1/6
3/10
```

##Output 1
```
7/15
```

##Input 2
```
3
1/3
1/4
1/12
```

##Output 2
```
2/3
```

#Challenge inputs

##Input 1
```
5
2/9
4/35
7/34
1/2
16/33
```

##Input 2
```
10
1/7
35/192
61/124
90/31
5/168
31/51
69/179
32/5
15/188
10/17
```


text:
package crawlr

import (
	"bytes"
	"net/url"
	"strings"

	"golang.org/x/net/html"
)

// -----------------------------------------------------------------------------

// Pipe is an alias for functions used in `Slave`s data pipeline.
type Pipe func(<-chan *RewindInputStream, chan<- *RewindInputStream)

// -----------------------------------------------------------------------------

// getLink is an helper function used to retrieve link URLs from a web page. It
// uses `t` as the token to analyse and its `tokenType`. It returns the link
// value or an empty `string` the `t` does not correspond to a link.
func getLink(t html.Token, tokenType html.TokenType) string {
	if tokenType == html.StartTagToken && t.Data == "a" {
		for _, att := range t.Attr {
			if att.Key == "href" {
				return att.Val
			}
		}
	}
	return ""
}

// getImg is an helper function used to retrieve img URLs from a web page. It
// uses `t` as the token to analyse and its `tokenType`. It returns the link
// value or an empty `string` the `t` does not correspond to a link.
func getImg(t html.Token, tokenType html.TokenType) string {
	if tokenType == html.StartTagToken && t.Data == "img" {
		for _, att := range t.Attr {
			if att.Key == "src" {
				return att.Val
			}
		}
	}
	return ""
}

// formatLink is an helper function used to format an URL in the proper way.
// It uses `URL` as the URL where the `link` was retrieved from. It returns
// a string representing a valid `URL` or an empty `string` if an `error`
// occurs.
func formatLink(URL, link string) string {
	baseURL, err := url.Parse(URL)
	if err != nil || link == "" {
		return ""
	}
	linkURL, err := url.Parse(link)
	if err != nil {
		return ""
	}

	if len(linkURL.Scheme) >= 4 && linkURL.Scheme[:4] == "http" {
		return link
	}

	if link[0] == '/' || link[0] == '.' {
		return strings.Join([]string{
			baseURL.Scheme,
			"://",
			baseURL.Host,
			"/",
			strings.Trim(link, "/"),
		}, "")
	}

	finalLink := strings.Join([]string{
		baseURL.Scheme,
		"://",
		baseURL.Host,
		baseURL.Path,
	}, "")

	if baseURL.RawQuery != "" {
		finalLink += "?" + baseURL.RawQuery
	}
	return finalLink + link
}

// ExtractLinkPipe is a `Pipe` function extracting links from an `URL`.
// It fetches data from `in` and pushes them to `out` after processing.
//
// NOTE: This function is an infinite loop.
func ExtractLinkPipe(in <-chan *RewindInputStream, out chan<- *RewindInputStream) {
	defer close(out)
	for ris := range in {
		uniqueLinks := make(map[string]bool)
		tokenizer := html.NewTokenizer(bytes.NewReader(ris.content))

		for tokenType := tokenizer.Next(); tokenType != html.ErrorToken; tokenType = tokenizer.Next() {
			t := tokenizer.Token()
			if link := formatLink(ris.URL, getLink(t, tokenType)); link != "" {
				uniqueLinks[link] = true
			} else if link := formatLink(ris.URL, getImg(t, tokenType)); link != "" {
				uniqueLinks[link] = true
			}
		}

		ris.msg.Type = REAL
		for k := range uniqueLinks {
			ris.msg.Msg += ";" + k
		}

		out <- ris
	}
}


text:
class Datatype(object):

    _default = None

    def __init__(self, name, description, default=None):
        self.name = name
        self.description = description
        self.value = default or self._default

    def from_parser(self, parser):
        return self.value

class Integer(Datatype):
    _default = 0

class String(Datatype):
    _default = ""

class Class(Datatype):
    _default = None

class Object(Datatype):
    _default = None

class Boolean(Datatype):
    _default = False


text:
package com.paradisegardens.requi.paradisegardens.GUI;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.paradisegardens.requi.paradisegardens.Data.Data;
import com.paradisegardens.requi.paradisegardens.R;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class CardFiller extends Fragment {

    //Stuff for the cards
    private ArrayList<String> mItems;
    private ArrayList<String> imgUrls;
    List cardsInfo;

    private CardViewAdapter mAdapter;
    private RecyclerView recyclerView;
    private Data data = new Data();

    //our webService URLS
    private String IP = "192.168.0.5";
    private String ATRACTION_URL = "http://"+IP+"/~seth/rest/atractions.php";
    private String SHOWS_URL = "http://"+IP+"/~seth/rest/shows.php";
    private String RESTAURANT_URL = "http://"+IP+"/~seth/rest/restaurants.php";
    private String STORES_URL = "http://"+IP+"/~seth/rest/stores.php";
    private String PRODUCT_URL = "http://"+IP+"/~seth/rest/products.php?storeName=";
    private String PLATES_URL = "http://"+IP+"/~seth/rest/plates.php?storeName=";
    private String SEARCH_URL = "http://"+IP+"/~seth/rest/search.php?item=";

    //names of data we want from webService
    ArrayList <String> params = new ArrayList<>();

    //Reference to main activity
    Main main;
    String productURL;

    //set a reference to main activity
    public void setMain(Main main){
        this.main = main;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_activity,container,false);

        //clear our array of params, we might have used it on another tab
        params.clear();

        //get the tab position from our values
        int position = getArguments().getInt("pos");
        String storeName = getArguments().getString("storeName");

        //which attraction tab are we on?
        switch (position){
            case 0:
                params.add("name");
                params.add("Descripción");
                params.add("Horario");
                params.add("Estado");
                params.add("Capacidad");
                //load up the cards
                cardsInfo = data.getCardData(ATRACTION_URL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                break;
            case 1:
                params.add("name");
                params.add("Descripción");
                params.add("Horario");
                params.add("Lugar");
                //load up the cards
                cardsInfo = data.getCardData(SHOWS_URL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                break;
            case 2:
                params.add("name");
                params.add("Horario");
                //load up the cards
                cardsInfo = data.getCardData(RESTAURANT_URL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                break;
            case 3:
                params.add("name");
                params.add("Horario");
                //load up the cards
                cardsInfo = data.getCardData(STORES_URL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                break;
            case 4: //product page show all products
                params.add("name");
                params.add("Descripción");

                try {
                    storeName = URLEncoder.encode(storeName, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                productURL = PLATES_URL + storeName;

                cardsInfo = data.getCardData(productURL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                Log.e("Product Name", productURL);
                break;

            case 5: //product page show all products
                params.add("name");
                params.add("Precio");
                params.add("Disponible");

                try {
                    storeName = URLEncoder.encode(storeName, "UTF-8");
                }catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                productURL = PRODUCT_URL + storeName;

                cardsInfo = data.getCardData(productURL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                Log.e("Product Name", productURL);
                break;
            case 6: //search case
                params.add("name");
                params.add("Descripción");
                params.add("Categoria");
                params.add("Horario");
                params.add("Lugar");
                params.add("Estado");

                productURL = SEARCH_URL + storeName;
                cardsInfo = data.getCardData(productURL, params);
                imgUrls = (ArrayList<String>) cardsInfo.get(0);
                mItems = (ArrayList<String>) cardsInfo.get(1);
                Log.e("Product Name", productURL);
                break;
        }

        mAdapter = new CardViewAdapter(main, mItems, imgUrls, position);
        //fill the recyclerView with the cards
        recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(v.getContext()));
        recyclerView.setAdapter(mAdapter);

        return v;
    }
}


text:
package pad

import (
	"testing"
	"time"
)

func TestPomodoroStart(t *testing.T) {
	const expectedTicks = 100

	ticks := make(chan byte, expectedTicks)
	p := NewPomodoro(time.Millisecond*100, ticks)

	p.Start()
	time.Sleep(time.Millisecond * 200)
	if len(ticks) != expectedTicks {
		t.Errorf("Expected %d ticks, got %d", expectedTicks, len(ticks))
		return
	}
	var i byte
	for i = 0; i < expectedTicks; i++ {
		b := <-ticks
		if b != i {
			t.Errorf("Expected tick %d to be %d but got %d", i, i, b)
			return
		}
	}
}

func TestPomodoroCancel(t *testing.T) {
	const maxTicks = 100

	ticks := make(chan byte, maxTicks)
	p := NewPomodoro(time.Millisecond, ticks)

	p.Start()
	time.Sleep(time.Millisecond / 10)
	p.Cancel()
	time.Sleep(time.Millisecond * 2)
	if len(ticks) > maxTicks {
		t.Errorf("Expected less than %d ticks, got %d", maxTicks, len(ticks))
		return
	}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.init_logging = init_logging;
exports.get_logging = get_logging;

/*
 * Logging/debug routines
 */

var _log_level = 'warn';

var Debug = function (msg) {};
var Info = function (msg) {};
var Warn = function (msg) {};
var Error = function (msg) {};

function init_logging(level) {
    if (typeof level === 'undefined') {
        level = _log_level;
    } else {
        _log_level = level;
    }

    exports.Debug = Debug = exports.Info = Info = exports.Warn = Warn = exports.Error = Error = function (msg) {};
    if (typeof window.console !== "undefined") {
        /* jshint -W086 */
        switch (level) {
            case 'debug':
                exports.Debug = Debug = console.debug.bind(window.console);
            case 'info':
                exports.Info = Info = console.info.bind(window.console);
            case 'warn':
                exports.Warn = Warn = console.warn.bind(window.console);
            case 'error':
                exports.Error = Error = console.error.bind(window.console);
            case 'none':
                break;
            default:
                throw new Error("invalid logging type '" + level + "'");
        }
        /* jshint +W086 */
    }
};
function get_logging() {
    return _log_level;
};
exports.Debug = Debug;
exports.Info = Info;
exports.Warn = Warn;
exports.Error = Error;

// Initialize logging level

init_logging();


text:
<?php

namespace Cosa\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;

class FrontendUserForgotChangeType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('currentPassword', 'text')
            ->add('password', 'repeated',array('type' => 'password','constraints' => new Length(array('min'=>8)), 'invalid_message' => 'Passwords do not match'))
            ->add('save', 'submit', array('label' => 'Submit', 'attr'=> array( 'class'=>'btn btn-primary')));
    }

    public function getName()
    {
        return 'frontend_user_login';
    }

}


text:
<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
?>

Gallery

About Vyspro-India

Vysya Professional Association (VYSPRO) came into existences after a VANA MAHOTSAVAM Meet at the Chacha Nehru Park in 1998. The members then decided to formalize this vision into a society in November 1998 which was formally done with the name "VYSPRO - INDIA"

Contact

#flat No 4, Topaz Plaza, CM Camp office exit Road,
Panjjagutta, Hyderabad - 500082

+91 868 882 8969

database.vysproindia@gmail.com

Religion

Story of Vasavi Matha

Arya vysya Gotrams

Arya vysya Satrams

About Us

Spirit of VysPro-India

About Vyspro

Committee Members

President Message

Past Presidents

Committee

                    © <?PHP echo date('Y'); ?> Vypro-India. All Rights Reserved.
                    Designed & Maintained by Lada Technologies   For Technical support Contact: 9441820017

<?PHP
if (isset($customJsFooter)) {
    echo $customJsFooter;
}
?>


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

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:padding="8dp"
        tools:context="trictionary.jumproper.com.jumpropetrictionary.activities.Rafiki">

        <ScrollView
            android:id="@+id/scrollView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:alpha=".75"
            android:background="@drawable/rounded_corner_shadow">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/rafiki_logo"
                    android:layout_width="wrap_content"
                    android:layout_height="200dp"
                    android:layout_alignParentTop="true"
                    android:layout_centerHorizontal="true"
                    android:alpha=".75"
                    android:background="@color/white"
                    android:padding="10dp"
                    android:scaleType="fitCenter"
                    app:srcCompat="@drawable/rafiki_logo" />

                <TextView
                    android:id="@+id/rafiki_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/rafiki_logo"
                    android:layout_centerHorizontal="true"
                    android:padding="20dp"
                    android:text="What is the Rafiki Outreach Program?"
                    android:textColor="@android:color/black"
                    android:textSize="16dp" />

                <TextView
                    android:id="@+id/rafiki_description"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="false"
                    android:layout_below="@+id/rafiki_1"
                    android:layout_centerHorizontal="true"
                    android:padding="10dp"
                    android:text="The Rafiki mission is to educate children and provide everything needed for he or she to become a successful jumper and a successful student in school.  The program connects everyone: coaches, teachers, students, and jumpers.  Rafiki currently includes coaches and jumpers in Kenya, Tanzania, Morocco, South Africa, Mozambique, India, Trinidad and Tobago, Dominican Republic, and Puerto Rico.  If you are interested in participating, helping, or would like to know more you can email rhodyropers@gmail.com"
                    android:textSize="16dp" />

                <TextView
                    android:id="@+id/rafiki_meaning"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/rafiki_title"
                    android:layout_centerHorizontal="true"
                    android:text="In Swahili, Rafiki means Friend\n"
                    android:textSize="16dp" />

                <ImageView
                    android:id="@+id/rafiki_1"
                    android:layout_width="wrap_content"
                    android:layout_height="200dp"
                    android:layout_below="@+id/rafiki_meaning"
                    android:layout_centerHorizontal="true"
                    android:scaleType="fitCenter"
                    app:srcCompat="@drawable/rafiki_1" />

                <ImageView
                    android:id="@+id/rafiki_2"
                    android:layout_width="wrap_content"
                    android:layout_height="200dp"
                    android:layout_below="@+id/rafiki_description"
                    android:scaleType="fitCenter"
                    app:srcCompat="@drawable/rafiki_2" />

                <ImageView
                    android:id="@+id/rafiki_3"
                    android:layout_width="wrap_content"
                    android:layout_height="200dp"
                    android:layout_below="@+id/textView14"
                    android:scaleType="fitCenter"
                    app:srcCompat="@drawable/rafiki_3" />

                <TextView
                    android:id="@+id/textView15"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/rafiki_2"
                    android:layout_centerHorizontal="true"
                    android:padding="20dp"
                    android:text="How can you help?"
                    android:textColor="@android:color/black"
                    android:textSize="16dp" />

                <TextView
                    android:id="@+id/textView14"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="false"
                    android:layout_below="@+id/textView15"
                    android:layout_centerHorizontal="true"
                    android:padding="10dp"
                    android:text="Rafiki is always interested in donations of shoes, gym equipment, and especially ropes.  All types, sizes, colors, and conditions of ropes are welcome.  If you are on a team, please talk to your coaches about gathering old team ropes to donate.  Contact rhodyropers@gmail.com for more information or to start sending your ropes!"
                    android:textSize="16dp" />

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:padding="50dp">

                    <Space
                        android:id="@+id/space4"
                        android:layout_width="20px"
                        android:layout_height="20px"
                        android:layout_alignParentTop="true"
                        android:layout_centerHorizontal="true" />
                </RelativeLayout>

                <ImageView
                    android:id="@+id/imageView20"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_alignStart="@+id/textView15"
                    android:layout_below="@+id/rafiki_3"
                    android:layout_margin="16dp"
                    android:onClick="sendEmail"
                    app:srcCompat="@android:drawable/ic_dialog_email"
                    android:tint="@android:color/black" />

                <ImageView
                    android:id="@+id/imageView18"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_alignEnd="@+id/textView15"
                    android:layout_below="@+id/rafiki_3"
                    android:layout_margin="16dp"
                    android:onClick="openFacebook"
                    app:srcCompat="@drawable/ic_public_black_24dp" />

            </RelativeLayout>
        </ScrollView>

    </RelativeLayout>
</ScrollView>


text:
{% extends "zerver/base.html" %}

{% block content %}

<form id="register" action="/accounts/register/" method="post">
    {{ csrf_input }}
    <input type="hidden" value="{{ key }}" name="key"/>
    <input type="hidden" value="1" name="from_confirmation"/>
</form>

<script type="text/javascript">
    $("#register").submit();
</script>
{% endblock %}


text:
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */

'use strict';

exports.Paging = require('./paging');


text:
var ping = require('net-ping');
var events = require('events');
var _ = require('underscore');
var ejs = require('ejs');
var fs = require('fs');
var Plugin = function() {};
Plugin.prototype = new events.EventEmitter;

Plugin.prototype.NAME = "ednt-plugin-ping";
Plugin.prototype.FRIENDLY_NAME = "ping";
Plugin.prototype.VERSION = "0.0.1";
Plugin.prototype.MOUNTPOINT = "ping";
Plugin.prototype.SU_REQUIRED = true;

Plugin.prototype.ROUTES = {
  "/": {
    "method": "GET",
    "params": {
      "target": {
        "mandatory": true,
        "type": "String"
      },
      "count": {
        "type": "Integer",
        "default": 5
      },
      "interval": {
        "type": "Integer",
        "default": 1000
      },
      "timeout": {
        "type": "Integer"
      }
    }
  }
};

Plugin.prototype.init = function(options) {
  this.session = ping.createSession();
  this.session.on('error', function(e) {
    console.log('session error');
    console.dir(e);
  });
  return true;
}

Plugin.prototype.newRequest = function(params) {
  var self = this;
  params['count'] = params['count'] || this.ROUTES['/'].params.count.default;
  params['interval'] = params['interval'] || this.ROUTES['/'].params.interval.default;
  if(params['target'] === undefined || params['target'] === '') {
    self.emit('output', null, self.getView());
    self.emit('end');
  }
  var count = params['count'];
  self.emit('output', null, 'test');

  self.ping(params, count, function(err) {
    self.emit('end', null);
  });
}

Plugin.prototype.ping = function(params, i, callback) {
  var self = this;
  var delay = (i === params['count']) ? 0 : params['interval'];
  var nextCallback = _.bind(self.ping, this);
  var nextPing = _.bind(self.executePing, this);
  i--;
  if(i < 0) callback();
  else setTimeout(nextPing, delay, params, i, callback, nextCallback);
}

Plugin.prototype.executePing = function(params, i, finalCallback, callback) {
  var self = this;
  this.session.pingHost (params['target'], function (err, target, sent, rcvd) {
    var ms = rcvd - sent;
    if (err)
        result = target + ": " + err.toString ();
     else
        result = target + ": Alive (ms=" + ms + ")";
    //callback(null, result);
    //console.log(result);
    self.emit('output', null, result);
    callback(params, i, finalCallback);
  });
}

Plugin.prototype.cancelRequest = function(requestId) {

}

Plugin.prototype.getView = function(viewName) {
  viewName = viewName || "default";
  switch(viewName) {
    case "default":
      return ejs.render(fs.readFileSync(__dirname+'/views/index.ejs', 'utf8'), null);
      break;
  }
}

module.exports = new Plugin();


text:
#pragma once
#include <aws/cloudformation/CloudFormation_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace CloudFormation
{
namespace Model
{
  enum class HookTargetType
  {
    NOT_SET,
    RESOURCE
  };

namespace HookTargetTypeMapper
{
AWS_CLOUDFORMATION_API HookTargetType GetHookTargetTypeForName(const Aws::String& name);

AWS_CLOUDFORMATION_API Aws::String GetNameForHookTargetType(HookTargetType value);
} // namespace HookTargetTypeMapper
} // namespace Model
} // namespace CloudFormation
} // namespace Aws


text:
// Copyright (c) 2014 Baidu.com, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: qinzuoyan01@baidu.com (Qin Zuoyan)

// This file is modified from boost.
//
// Copyright Beman Dawes 2002, 2006
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See library home page at http://www.boost.org/libs/system

#ifndef _SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_POOL_
#define _SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_POOL_

//
//  spinlock_pool<0> is reserved for atomic<>, when/if it arrives
//  spinlock_pool<1> is reserved for shared_ptr reference counts
//  spinlock_pool<2> is reserved for shared_ptr atomic access
//

#include <sofa/pbrpc/smart_ptr/detail/spinlock.hpp>

#include <cstddef>

namespace sofa {
namespace pbrpc {
namespace detail {

template< int I > class spinlock_pool
{
private:

    static spinlock pool_[ 41 ];

public:

    static spinlock & spinlock_for( void const * pv )
    {
        std::size_t i = reinterpret_cast< std::size_t >( pv ) % 41;
        return pool_[ i ];
    }

    class scoped_lock
    {
    private:

        spinlock & sp_;

        scoped_lock( scoped_lock const & );
        scoped_lock & operator=( scoped_lock const & );

    public:

        explicit scoped_lock( void const * pv ): sp_( spinlock_for( pv ) )
        {
            sp_.lock();
        }

        ~scoped_lock()
        {
            sp_.unlock();
        }
    };
};

template< int I > spinlock spinlock_pool< I >::pool_[ 41 ] =
{
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT, SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT,
    SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_INIT
};

} // namespace detail
} // namespace pbrpc
} // namespace sofa

#endif // _SOFA_PBRPC_SMART_PTR_DETAIL_SPINLOCK_POOL_

/* vim: set ts=4 sw=4 sts=4 tw=100 */


text:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface RNVkontakteLoginUtils : NSObject

/**
 returns currently displayed top view controller.
 */
+ (UIViewController *)topMostViewController;

@end


text:
namespace OpenTissue
{
  namespace polymesh
  {

    template<typename mesh_type,typename real_type>
    bool is_concave(PolyMeshHalfEdge<mesh_type> const & e,real_type const & tolerance)
    {
      real_type radian;
      compute_dihedral_angle(e,radian);
      if( radian >= tolerance )
        return false;
      return true;
    }

    template<typename mesh_type>
    bool is_concave(PolyMeshHalfEdge<mesh_type> const & e)
    {
      typedef typename mesh_type::math_types::value_traits  value_traits;

      return is_concave(e,value_traits::zero());
    }

    template<typename mesh_type,typename real_type>
    bool is_concave(PolyMeshVertex<mesh_type> const & v,real_type const & tolerance)
    {
      typedef typename mesh_type::vertex_halfedge_circulator  vertex_halfedge_circulator;
      if(valency(v)==0)
        return false;
      vertex_halfedge_circulator h(v), end;
      for(;h!=end;++h)
      {
        if( !is_concave(*h,tolerance) )
          return false;
      }
      return true;
    }

    template<typename mesh_type>
    bool is_concave(PolyMeshVertex<mesh_type> const & v)
    {
      typedef typename mesh_type::math_types::value_traits  value_traits;

      return is_concave(v,value_traits::zero());
    }

  } // namespace polymesh
} // namespace OpenTissue

//OPENTISSUE_CORE_CONTAINERS_MESH_POLYMESH_UTIL_POLYMESH_IS_CONCAVE_H
#endif


text:
@interface CRProductionDetailView ()
{
    CRDemoInfoModel         *_infoModel;
    UIScrollView            *_mainScrollView;

    UIView                  *_topView;
    UILabel                 *_productNameLabel;

    UIView                  *_bodyView;
    UIView                  *_bodyUpView;
    UIView                  *_bodyDownView;

    CGFloat                 _offX_start;
    CGFloat                 _offX_end;

    CRBaseViewController    *_inVC;
}

@end

@implementation CRProductionDetailView

+ (CRProductionDetailView *)commonDetailViewWithInfoModel:(CRDemoInfoModel *)infoModel inVC:(__weak CRBaseViewController *)inVC
{
    CRProductionDetailView *detailView = [[CRProductionDetailView alloc] initWithFrame:CGRectMake(0, 0, XX_6N(544), HEIGHT)
                                                                             infoModel:infoModel
                                                                                inVC:inVC];
    return detailView;
}

- (instancetype)initWithFrame:(CGRect)frame
                    infoModel:(CRDemoInfoModel *)infoModel
                         inVC:(__weak CRBaseViewController *)inVC
{
    self = [super initWithFrame:frame];

    if (self) {
        _inVC = inVC;
        _infoModel = infoModel;
        _offX_start = XX_6N(40);
        _offX_end = XX_6N(70);
        [self createUI];
    }

    return self;
}

- (void)createUI
{
    self.backgroundColor = [UIColor clearColor];

    _mainScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _mainScrollView.showsVerticalScrollIndicator = NO;
    _mainScrollView.backgroundColor = [UIColor clearColor];
    [self addSubview:_mainScrollView];

    [self createTopView];
    [self createBodyView];
    [self resizeScrollView];
}

- (void)createTopView
{
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _mainScrollView.width, YY_6N(236))];
    _topView.backgroundColor = [color_323341 colorWithAlphaComponent:0.95];
    [_mainScrollView addSubview:_topView];

    _productNameLabel = [UILabel new];
    _productNameLabel.font = BoldFont(18);
    _productNameLabel.textColor = color_5868f2;
    _productNameLabel.text = _infoModel.demoName;
    [_productNameLabel sizeToFit];
    [_topView addSubview:_productNameLabel];
    [_productNameLabel BearSetCenterToParentViewWithAxis:kAXIS_X_Y];
}

- (void)createBodyView
{
    _bodyView = [[UIView alloc] initWithFrame:CGRectMake(0, _topView.maxY, _mainScrollView.width, 1000)];
    _bodyView.backgroundColor = [UIColor whiteColor];
    [_mainScrollView addSubview:_bodyView];

    [self createBodyUpView];
    [self createBodyDownView];
    [_bodyView setHeight:_bodyDownView.maxY];
}

- (void)createBodyUpView
{
    UILabel     *_CRIDTitleLable;
    UILabel     *_CRIDContentLable;
    UILabel     *_codeLanguageTitleLabel;
    UILabel     *_codeLanguageContentLabel;
    UILabel     *_briefTitleLabel;
    UILabel     *_briefContentLabel;
    UIView      *_sepLineV;

    _bodyUpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _bodyView.width, 0)];
    [_bodyView addSubview:_bodyUpView];

    //  _CRID
    _CRIDTitleLable = [UILabel new];
    [self setTitleLabel:_CRIDTitleLable text:@"CRID:" inView:_bodyUpView];
    [_CRIDTitleLable setY:YY_6N(55)];

    _CRIDContentLable = [UILabel new];
    [self setContentLabel:_CRIDContentLable text:_infoModel.CRID inView:_bodyUpView];
    [_CRIDContentLable setY:_CRIDTitleLable.maxY + YY_6N(20)];

    //  _codeLanguage
    NSString *codeLanguage = @"";
    switch (_infoModel.codeLanguage) {
        case kCRLanguageTypeSwift: codeLanguage = @"Swift"; break;
        case kCRLanguageTypeObjectiveC: codeLanguage = @"ObjectiveC"; break;
        default: break;
    }

    _codeLanguageTitleLabel = [UILabel new];
    [self setTitleLabel:_codeLanguageTitleLabel text:@"开发语言:" inView:_bodyUpView];
    [_codeLanguageTitleLabel setY:_CRIDContentLable.maxY + YY_6N(40)];

    _codeLanguageContentLabel = [UILabel new];
    [self setContentLabel:_codeLanguageContentLabel text:codeLanguage inView:_bodyUpView];
    [_codeLanguageContentLabel setY:_codeLanguageTitleLabel.maxY + YY_6N(20)];

    _briefTitleLabel = [UILabel new];
    [self setTitleLabel:_briefTitleLabel text:@"动效简介:" inView:_bodyUpView];
    [_briefTitleLabel setY:_codeLanguageContentLabel.maxY + YY_6N(50)];

    _briefContentLabel = [UILabel new];
    [self setContentLabel:_briefContentLabel text:_infoModel.demoSummary inView:_bodyUpView textColor:color_777777 font:[UIFont systemFontOfSize:15]];
    [_briefContentLabel setY:_briefTitleLabel.maxY + YY_6N(30)];

    _sepLineV = [[UIView alloc] initWithFrame:CGRectMake(_offX_start, _briefContentLabel.maxY + YY_6N(40), _mainScrollView.width - _offX_start, 0.5)];
    _sepLineV.backgroundColor = color_e5e5e5;
    [_bodyUpView addSubview:_sepLineV];

    [_bodyUpView setHeight:_sepLineV.maxY];
}

- (void)createBodyDownView
{
    UILabel         *_CRCoderTitleLabel;
    CRParticipateMembersView *_CRCoderHeadersView;
    UILabel         *_CRDesignerTitleLabel;
    CRParticipateMembersView *_CRDesignerHeadersView;
    UILabel         *_urlTitleLabel;
    UILabel         *_urlDetailsLabel;
    CGFloat         maxWidth = _mainScrollView.width - _offX_start - _offX_end;

    _bodyDownView = [[UIView alloc] initWithFrame:CGRectMake(0, _bodyUpView.maxY, _bodyView.width, 0)];
    [_bodyView addSubview:_bodyDownView];

    _CRCoderTitleLabel = [UILabel new];
    [self setTitleLabel:_CRCoderTitleLabel text:@"CRCoder:" inView:_bodyDownView];
    [_CRCoderTitleLabel setY:YY_6N(30)];

    _CRCoderHeadersView = [CRParticipateMembersView commonHeadersViewWithWidth:maxWidth inVC:_inVC];
    [_CRCoderHeadersView setMemberInfoModelArray:_infoModel.developAuthors];
    [_bodyDownView addSubview:_CRCoderHeadersView];
    [_CRCoderHeadersView setOrigin:CGPointMake(_CRCoderTitleLabel.x, _CRCoderTitleLabel.maxY + YY_6N(30))];

    _CRDesignerTitleLabel = [UILabel new];
    [self setTitleLabel:_CRDesignerTitleLabel text:@"CRDesigner:" inView:_bodyDownView];
    [_CRDesignerTitleLabel setY:_CRCoderHeadersView.maxY + YY_6N(44)];

    _CRDesignerHeadersView = [CRParticipateMembersView commonHeadersViewWithWidth:maxWidth inVC:_inVC];
    [_CRDesignerHeadersView setMemberInfoModelArray:_infoModel.designAuthors];
    [_bodyDownView addSubview:_CRDesignerHeadersView];
    [_CRDesignerHeadersView setOrigin:CGPointMake(_CRDesignerTitleLabel.x, _CRDesignerTitleLabel.maxY + YY_6N(30))];

    _urlTitleLabel = [UILabel new];
    [self setTitleLabel:_urlTitleLabel text:@"项目源地址" inView:_bodyDownView];
    [_urlTitleLabel setY:_CRDesignerHeadersView.maxY + YY_6N(60)];

    _urlDetailsLabel = [UILabel new];
    [self setContentLabel:_urlDetailsLabel text:_infoModel.originGitHubAddress inView:_bodyDownView textColor:color_354ff1 font:[UIFont systemFontOfSize:15]];
    _urlDetailsLabel.userInteractionEnabled = YES;
    [_urlDetailsLabel setY:_urlTitleLabel.maxY + YY_6N(20)];

    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(urlTapEvent)];
    [_urlDetailsLabel addGestureRecognizer:tapGR];

    [_bodyDownView setHeight:_urlDetailsLabel.maxY + YY_6N(55)];
}

- (void)setTitleLabel:(UILabel *)label text:(NSString *)text inView:(UIView *)inView
{
    label.textColor = color_c5c5c5;
    label.font = [UIFont systemFontOfSize:14];
    label.text = text;
    [label setX:_offX_start];
    [label sizeToFit];
    [inView addSubview:label];
}

- (void)setContentLabel:(UILabel *)label text:(NSString *)text inView:(UIView *)inView
{
    [self setContentLabel:label
                     text:text
                   inView:inView
                textColor:color_323341
                     font:[UIFont systemFontOfSize:19]];
}

- (void)setContentLabel:(UILabel *)label
                   text:(NSString *)text
                 inView:(UIView *)inView
              textColor:(UIColor *)textColor
                   font:(UIFont *)font
{
    label.textColor = textColor;
    label.font = font;
    label.text = text;
    label.numberOfLines = 0;
    [label setX:_offX_start];
    [label setWidth:_mainScrollView.width - _offX_start - _offX_end];
    [label sizeToFit];
    [inView addSubview:label];
}

- (void)resizeScrollView
{
    _mainScrollView.contentSize = CGSizeMake(_mainScrollView.width, _bodyView.maxY);
}

#pragma mark - TapEvent

- (void)urlTapEvent
{
    [[CRJumpWebViewManager new] jumpToUrlStr:_infoModel.originGitHubAddress inVC:_inVC];
}

@end


text:
---
title: Getting started with PostCSS
author: Cathy Dutton
layout: external-post
category: external
link: http://blog.mrfrontend.org/2016/03/an-introduction-to-postcss/
site: Mr Frontend
---

Before diving straight into PostCSS it is first necessary to look at CSS processing in general. Processors like Less, Sass and Stylus allow you to start re-using CSS properties and patterns, keeping stylesheets DRY and easier to maintain. Each preprocessor has a slightly different syntax but all support the original vanilla CSS syntax as well.

#### Benefits of Pre Processors

*   Fewer HTTP requests with the use of @import
*   Re-usable properties with variables
*   modular code blocks
*   Re-usable patterns with mixins
*   Scalable projects
*   Maintainable code

## So why stop now?

Despite the advantages listed above, numerous disadvantages have emerged from the mis-use of Pre processors. Each language comes with numerous features (Extends, Functions, Mixins, Variables, Nesting) some more harmful then others. In each case it is not possible to restrict usage of an offending feature, making codebases harder to maintain and keep clean.

#### Disadvantages of Pre Processors

*   Bloated stylesheets
*   Overly specific selectors created from excessive nesting
*   Confusing or overly complicated mixins and functions
*   Excessive config

## What is PostCSS?

PostCSS makes it possible to transform and extend the features of CSS using JavaScript plugins. Each plugin is installed individually allowing teams to create there own processors with the exact features they need and nothing more. This allows developers to take much greater control over the features used and as a result the output CSS.

#### Syntax sugar

PostCSS has plugins available to replicate all of the features developers have become accustomed to with pre processors. Variables, Mixins, Functions, Extends and even Nesting can be accomplished with existing plugins...

*   postcss-mixins - Enables mixins more powerful than Sass.
*   postcss-nested - Unwraps nested rules.
*   postcss-simple-extend - Lightweight extending of silent classes, like Sass' @extend.
*   postcss-simple-vars - Support for Sass-style variables.
*   postcss-nested-vars - Supports nested Sass-style variables.
*   postcss-precss - Plugin pack that allows you to use Sass-like CSS.

#### Maintainable CSS

PostCSS offers more then just the syntax changes associated with Sass, Less and Stylus. With PostCSS you can also extend the functionality of CSS and begin to tackle some of the languages shortcomings.

"…the single hardest problem in CSS: Getting your rules to match the elements you want, without them accidentally
matching the elements you don't."
Philip Walton, Engineer at Google

Quotes like the one above accurately sum up the struggles all developers have had with CSS inheritance, scope and specificity, with PostCSS these issues and more can be resolved. There are also plugins to help with readability, linting and implementing the latest CSS properties safely.

*   postcss-use - Enable PostCSS plugins directly in your stylesheet.
*   postcss-modules - Allows to use CSS Modules everywhere.
*   postcss-autoreset - Automatically adds reset styles.
*   postcss-cssnext - Plugin pack that allows you to use future CSS features today.
*   cq-prolyfill - Adds support for CSS container queries (aka element query) like `:container(width > 100px)`.

#### Customisable

Because PostCSS uses Javascript to transform CSS, it is much more accessible for front end developers to create their own plugins. Projects can therefore be customised to create the optimum workflow with no limitations or boundaries set by language choices.

Plugins can be created for any CSS task large or small, a collection of current plugins can be found
[here](http://postcss.parts/). More information will be provided on how to create a plugin later in this article

## Why use PostCSS?

PostCSS has many benefits when compared to other CSS processors, including speed, performance, adaptability and innovation. Perhaps its biggest advantage though is that it is not attempting to compete with these languages and can instead be used alongside them.

To begin using PostCSS you do not have to abandon your current front end set up and can continue to use the Functions, Mixins and Variables you already have, whatever language they are in. This allows the more forward thinking PostCSS plugins to be added to legacy projects, not just new builds.

#### Benefits

*   Use tomorrow's CSS syntax, today.
*   Easy to contribute to in the form of custom plugins.
*   More control over the features used.
*   Faster compile times.

## Getting started

Another plus point for PostCSS is the ease with which it can be integrated into your current workflow. PostCSS has a JavaScript API and integrates seamlessly with task runners like Gulp, Grunt and webpack.

#### JS API

```
var postcss = require('postcss');
postcss([ require('autoprefixer'), require('cssnano') ])
    .process(css, { from: 'src/app.css', to: 'app.css' })
    .then(function (result) {
        fs.writeFileSync('app.css', result.css);
        if ( result.map ) fs.writeFileSync('app.css.map', result.map);
    });
```

#### Gulp

```
gulp.task('css', function () {
    var postcss    = require('gulp-postcss');
    var sourcemaps = require('gulp-sourcemaps');

    return gulp.src('src/**/*.css')
        .pipe( sourcemaps.init() )
        .pipe( postcss([ require('autoprefixer'), require('precss') ]) )
        .pipe( sourcemaps.write('.') )
        .pipe( gulp.dest('build/') );
});
```

PostCSS also has a command line interface available for those who don't wish to use a task runner. By installing postcss-cli CSS can be compiled with the following command...

```
postcss -c config.json -o result.css input.css
```

## Demo

To demonstrate how PostCSS works we will look at the simple PostCSS Clearfix plugin. The plugin adds fix and fix-legacy values to the clear property. With the plugin installed you can set the clear property to fix or fix-legacy depending on your level of browser support.

```
.foo {
  clear: fix; /* IE8+ */
}

.bar {
  clear: fix-legacy; /* IE6+ */
}
```
The CSS above would compile to...

```
.foo:after{
  content: '';
  display: block;
  clear: both;
}

.bar:before,
.bar:after {
  content: '';
  display: table;
}
.bar:after {
  clear: both;
}
.bar {
  zoom: 1;
}
```

The plugin iterates through each declaration in the input CSS file matching values of fix of fix-legacy. In the output CSS these declarations are removed and replaced with the relevant CSS.


text:
function callCloudinary (dispatch) {
  cloudinary.openUploadWidget({ cloud_name: 'top-of-the-flops', upload_preset: 'clientuploads',
  stylesheet: '#cloudinary-overlay {background-color: #f64161 !important}' } ,
    function(error, result){
      if(error) console.log("There was an error", error);
      dispatch({ type: 'SAVE_PHOTO_URL', payload: result[0].secure_url })
    }
  )
}

module.exports = callCloudinary


text:
ace.define("ace/mode/ada_highlight_rules",[], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var AdaHighlightRules = function() {
var keywords = "abort|else|new|return|abs|elsif|not|reverse|abstract|end|null|accept|entry|select|" +
"access|exception|of|separate|aliased|exit|or|some|all|others|subtype|and|for|out|synchronized|" +
"array|function|overriding|at|tagged|generic|package|task|begin|goto|pragma|terminate|" +
"body|private|then|if|procedure|type|case|in|protected|constant|interface|until|" +
"|is|raise|use|declare|range|delay|limited|record|when|delta|loop|rem|while|digits|renames|with|do|mod|requeue|xor";

    var builtinConstants = (
        "true|false|null"
    );

    var builtinFunctions = (
        "count|min|max|avg|sum|rank|now|coalesce|main"
    );

    var keywordMapper = this.createKeywordMapper({
        "support.function": builtinFunctions,
        "keyword": keywords,
        "constant.language": builtinConstants
    }, "identifier", true);

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "--.*$"
        }, {
            token : "string",           // " string
            regex : '".*?"'
        }, {
            token : "string",           // character
            regex : "'.'"
        }, {
            token : "constant.numeric", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\/|\\/\\/|%|<@>|@>|<@|&|\\^|~|<|>|<=|=>|==|!=|<>|="
        }, {
            token : "paren.lparen",
            regex : "[\\(]"
        }, {
            token : "paren.rparen",
            regex : "[\\)]"
        }, {
            token : "text",
            regex : "\\s+"
        } ]
    };
};

oop.inherits(AdaHighlightRules, TextHighlightRules);

exports.AdaHighlightRules = AdaHighlightRules;
});

ace.define("ace/mode/ada",[], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var AdaHighlightRules = require("./ada_highlight_rules").AdaHighlightRules;
var Range = require("../range").Range;

var Mode = function() {
    this.HighlightRules = AdaHighlightRules;
    this.$behaviour = this.$defaultBehaviour;
};
oop.inherits(Mode, TextMode);

(function() {

    this.lineCommentStart = "--";

    this.getNextLineIndent = function(state, line, tab) {
        var indent = this.$getIndent(line);

        var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
        var tokens = tokenizedLine.tokens;

        if (tokens.length && tokens[tokens.length-1].type == "comment") {
            return indent;
        }
        if (state == "start") {
            var match = line.match(/^.*(begin|loop|then|is|do)\s*$/);
            if (match) {
                indent += tab;
            }
        }

        return indent;
    };

    this.checkOutdent = function(state, line, input) {
        var complete_line = line + input;
        if (complete_line.match(/^\s*(begin|end)$/)) {
            return true;
        }

        return false;
    };

    this.autoOutdent = function(state, session, row) {

        var line = session.getLine(row);
        var prevLine = session.getLine(row - 1);
        var prevIndent = this.$getIndent(prevLine).length;
        var indent = this.$getIndent(line).length;
        if (indent <= prevIndent) {
            return;
        }

        session.outdentRows(new Range(row, 0, row + 2, 0));
    };

    this.$id = "ace/mode/ada";
}).call(Mode.prototype);

exports.Mode = Mode;

});                (function() {
                    ace.require(["ace/mode/ada"], function(m) {
                        if (typeof module == "object" && typeof exports == "object" && module) {
                            module.exports = m;
                        }
                    });
                })();


text:
TimesTurn_of
============

OpenFrameworks segment of "Time's Turn" incarnation of the Time Distortion Machine.


text:
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class SomeTest {
  @Tag("selected")
  @Test
  public void testSomething() {
    // Breakpoint! suspendPolicy(SuspendNone) LogExpression("Debugger: testSomething() reached")
    assertEquals(2 * 2, 4);
  }
}


text:
// -----------------------------------------------------------------------------------------
// <copyright file="AZSStorageUri.m" company="Microsoft">
//    Copyright 2015 Microsoft Corporation
//
//    Licensed under the MIT License;
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//      http://spdx.org/licenses/MIT
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// -----------------------------------------------------------------------------------------

#import "AZSStorageUri.h"

@interface AZSStorageUri()

-(instancetype)init AZS_DESIGNATED_INITIALIZER;

@end

@implementation AZSStorageUri

+ (NSURL *) appendToUrl:(NSURL *)url pathToAppend:(NSString *)pathToAppend
{
    if (url)
    {
        NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
        NSString * path = components.path;
        if (path == nil)
        {
            path = @"";
        }
        path = [[path stringByAppendingString:@"/"] stringByAppendingString:pathToAppend];
        [components setPath:path];
        return components.URL;
    }
    return nil;
}

+ (AZSStorageUri *) appendToStorageUri:(AZSStorageUri *)storageUri pathToAppend:(NSString *)pathToAppend
{
    return [[AZSStorageUri alloc] initWithPrimaryUri:[AZSStorageUri appendToUrl:storageUri.primaryUri pathToAppend:pathToAppend] secondaryUri:[AZSStorageUri appendToUrl:storageUri.secondaryUri pathToAppend:pathToAppend]];
}

-(instancetype)init
{
    return nil;
}

-(instancetype) initWithPrimaryUri:(NSURL *)primaryUri
{
    return [self initWithPrimaryUri:primaryUri secondaryUri:nil];
}

-(instancetype) initWithPrimaryUri:(NSURL *)primaryUri secondaryUri:(NSURL *)secondaryUri
{
    self = [super init];
    if (self)
    {
        _primaryUri = primaryUri;
        _secondaryUri = secondaryUri;
    }
    return self;
}

-(NSURL *) urlWithLocation:(AZSStorageLocation)storageLocation
{
    if (storageLocation == AZSStorageLocationPrimary)
    {
        return self.primaryUri;
    }
/*    else if (storageLocation == AZSStorageLocationSecondary)
    {
        return self.secondaryUri;
    }
 */
    else
    {
        NSException* myException = [NSException
                                    exceptionWithName:@"NotImplementedException"
                                    reason:@"Not implemented"
                                    userInfo:nil];
        @throw myException;
    }
}

@end


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once(APPPATH . "libraries/core/ImpulseController.php");

class Welcome extends ImpulseController {
	public function index()
	{
		if($this->impulselib->getViewMode() == "Advanced") {
			$content = $this->load->view('welcome_message',null,true);
		} else {
			$content = $this->load->view('welcome_message_simple',array('helpContact'=>$this->api->get->site_configuration('HELP_CONTACT')),true);
		}
		#$sidebar = $this->load->view('core/sidebar',null,true);
		$this->sidebar = "";
		$this->_render($content);
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2014 by Cloudsoft Corporation Limited

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>brooklyn-couchbase-parent</artifactId>
        <groupId>io.cloudsoft.couchbase</groupId>
        <version>0.1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>brooklyn-couchbase</artifactId>
    <name>Brooklyn Couchbase Entity</name>
    <description>Brooklyn entity for Couchbase</description>

    <dependencies>
        <dependency>
            <groupId>io.brooklyn</groupId>
            <artifactId>brooklyn-software-base</artifactId>
            <version>${brooklyn.version}</version>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>


text:
===============
Team operations
===============

This is internal information about development and operations for the IaaS team.

.. toctree::
    :glob:
    :maxdepth: 2

    getting_started/index
    development/index
    operations/index
    installation/index
    tips_and_tricks/index


text:
<?php

namespace Magento\Theme\Ui\Component\Design\Config;

use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\ReportingInterface;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\App\RequestInterface;
use Magento\Store\Model\StoreManagerInterface;

class DataProvider extends \Magento\Framework\View\Element\UiComponent\DataProvider\DataProvider
{
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param ReportingInterface $reporting
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param RequestInterface $request
     * @param FilterBuilder $filterBuilder
     * @param StoreManagerInterface $storeManager
     * @param array $meta
     * @param array $data
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        ReportingInterface $reporting,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        RequestInterface $request,
        FilterBuilder $filterBuilder,
        StoreManagerInterface $storeManager,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct(
            $name,
            $primaryFieldName,
            $requestFieldName,
            $reporting,
            $searchCriteriaBuilder,
            $request,
            $filterBuilder,
            $meta,
            $data
        );
        $this->storeManager = $storeManager;
    }

    /**
     * Get data
     *
     * @return array
     */
    public function getData()
    {
        if ($this->storeManager->isSingleStoreMode()) {
            $websites = $this->storeManager->getWebsites();
            $singleStoreWebsite = array_shift($websites);

            $this->addFilter(
                $this->filterBuilder->setField('store_website_id')
                    ->setValue($singleStoreWebsite->getId())
                    ->create()
            );
            $this->addFilter(
                $this->filterBuilder->setField('store_group_id')
                    ->setConditionType('null')
                    ->create()
            );
        }
        $data = parent::getData();
        foreach ($data['items'] as & $item) {
            $item += ['default' => __('Global')];
        }

        return $data;
    }
}


text:
date:   2015-09-13 12:00:00
---

# Pun of the day ({{ page.date | date: "%F" }})

When I was in the supermarket I saw a man and a woman wrapped in a barcode. I asked "Are you two an item?"