text:
FOUNDATION_EXPORT double ABCircularProgressViewVersionNumber;

//! Project version string for ABCircularProgressView.
FOUNDATION_EXPORT const unsigned char ABCircularProgressViewVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <ABCircularProgressView/PublicHeader.h>

redpajama_set_name: RedPajamaGithub


text:
package io.crate.metadata;

import com.google.common.base.Predicate;
import io.crate.analyze.symbol.Reference;
import io.crate.analyze.symbol.Symbol;
import io.crate.metadata.doc.DocSysColumns;

import javax.annotation.Nullable;

/**
 * Visitor to change regular column references into references using the DOC sys column.
 * <p/>
 * e.g.   s.t.colname -> s.t._DOC['colname']
 */
public class DocReferenceConverter {

    private final static Visitor VISITOR = new Visitor();

    private final static Predicate<Reference> DEFAULT_PREDICATE = new Predicate<Reference>() {
        @Override
        public boolean apply(@Nullable Reference input) {
            assert input != null;

            ReferenceIdent ident = input.info().ident();
            String schema = ident.tableIdent().schema();
            return ReferenceInfos.isDefaultOrCustomSchema(schema);
        }
    };

    /**
     * will convert any references that are analyzed or not indexed to doc-references
     */
    public static Symbol convertIf(Symbol symbol) {
        return VISITOR.process(symbol, DEFAULT_PREDICATE);
    }

    public static Reference toSourceLookup(Reference reference) {
        ReferenceIdent ident = reference.info().ident();
        if (ident.columnIdent().isSystemColumn()) {
            return reference;
        }
        if (reference.info().granularity() == RowGranularity.DOC) {
            return new Reference(reference.info().getRelocated(
                    new ReferenceIdent(ident.tableIdent(), ident.columnIdent().prepend(DocSysColumns.DOC.name()))));
        }
        return reference;
    }

    private static class Visitor extends ReplacingSymbolVisitor<Predicate<Reference>> {

        public Visitor() {
            super(false);
        }

        @Override
        public Symbol visitReference(Reference symbol, Predicate<Reference> predicate) {
            if (predicate.apply(symbol)) {
                return toSourceLookup(symbol);
            }
            return symbol;
        }
    }

    private DocReferenceConverter() {
    }
}


text:
package vs.js;

import java.util.function.Consumer;

class A {
    public String name = "Apple";
    public Consumer<Integer> hello;

    public A() {
        hello = (Integer it) -> System.out.println(it + ": Hello " + this.name);
    }
}

class B {
    // 无法使用 private Consumer hello = A.hello ;  因为A中没有一个static方法叫Hello
    public String name = "Banana";
    public Consumer<Integer> hello;
}

public class This天坑 {
    public static void main(String[] args) {
        A obj1 = new A();
        B obj2 = new B();
        obj2.hello = obj1.hello;
        obj2.hello.accept(20); //=> 20: Hello Apple
    }
}

/*
[js]
let obj1 = {
  name: "apple",
  hello: function() {
    console.log(`hello, ${this.name}`);
  }
};

let obj2 = {
  name: "banana",
  hello: obj1.hello
};

obj1.hello();  //=> hello, apple
obj2.hello();  //=> hello, banana
 */


text:
<!DOCTYPE html>

  <title>Edit Threshold Constants</title>
  <link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='styles/pagestyle.css') }}">

        {% if username %}

Hello! {{ username }}

        {% else %}

Login

        {% endif %}

Home

Help

        {% if accType == 'admin' %}

Add new user

Delete user

Show all account details

        {% endif %}
        {% if accType == 'patient' %}

Add new entry

Upload Photo

Suggest a MCQ

        {% endif %}
        {% if username %}

Logout

        {% endif %}

      <form action="{{ url_for('editconstants') }}" method="POST">

          Record Limit:
          Sets limit of records that are analyzed for critical counts of assessments which are shown in each critical report

          Critical Count:
          Sets threshold for number of assessments that should fall in critical range before notification is triggered

          Parameter Name:

              <select class="button second" name="replaceParam" id="replaceParam">
                {% for param in paramList %}
                {% if param == replaceParam %}
                <option selected value="{{ param }}">{{ param }}</option>
                {% else %}
                <option value="{{ param }}">{{ param }}</option>
                {% endif %}
                {% endfor %}
              </select>

          {% for param in paramList %}

            {% if param == "recordLimit" %}
              New record limit:
              <input type="number" name="replaceValue1" placeholder="10" min="5" max="100">
            {% elif param == "CriticalCount" %}
              New critical count:
              <input type="number" name="replaceValue2" placeholder="3" min="3" max="100">
            {% else %}
            {% endif %}

          {% endfor %}

              <input class="button second" type="submit" name="submit" value="Change">

      </form>
      {% if error %}

Error! {{ error }}

      {% endif %}
      {% if msg %}

Success! {{ msg }}

      {% endif %}

  Developed by Vivek, Piyush, Chaitanya


text:
export {ContainWrapper} from './contain';
export {Wrapper} from './wrapper';
export {useValueRef} from './value-ref';
export {useDOMHandle} from './dom-handle';


text:
RouteTranslator.config do |config|
  config.force_locale = true
end


text:
/*
 * IDK Game Server by Steve Winfield
 * https://github.com/WinfieldSteve
 */
package org.stevewinfield.suja.idk.game.moderation;

public enum ModerationPresetMessageType {
    PLAYER_MESSAGE,
    ROOM_MESSAGE
}


text:
<resources>

    <!--
        Base application theme for API 19+.
    -->
    <style name="FullscreenTheme" parent="Theme.AppCompat.NoActionBar">
        <item name="android:windowTranslucentStatus">false</item>
    </style>

</resources>


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace ProtocolGateway.Samples.Console
{
    using System;
    using System.Diagnostics.Tracing;
    using System.Security.Cryptography.X509Certificates;
    using System.Threading;
    using System.Threading.Tasks;
    using DotNetty.Codecs.Mqtt;
    using DotNetty.Common.Concurrency;
    using DotNetty.Transport.Bootstrapping;
    using DotNetty.Transport.Channels;
    using Microsoft.Azure.Devices.ProtocolGateway;
    using Microsoft.Azure.Devices.ProtocolGateway.Instrumentation;
    using Microsoft.Azure.Devices.ProtocolGateway.Providers.CloudStorage;
    using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
    using ProtocolGateway.Samples.Common;

    class Program
    {
        static void Main(string[] args)
        {
            // optimizing IOCP performance
            int minWorkerThreads;
            int minCompletionPortThreads;
            ThreadPool.GetMinThreads(out minWorkerThreads, out minCompletionPortThreads);
            ThreadPool.SetMinThreads(minWorkerThreads, Math.Max(16, minCompletionPortThreads));

            int threadCount = Environment.ProcessorCount;
            if (args.Length > 0)
            {
                threadCount = int.Parse(args[0]);
            }

            var eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(BootstrapperEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttIotHubAdapterEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ChannelEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(BootstrapEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(ExecutorEventSource.Log, EventLevel.Verbose);
            eventListener.EnableEvents(MqttEventSource.Log, EventLevel.Verbose);

            try
            {
                var cts = new CancellationTokenSource();

                var certificate = new X509Certificate2("protocol-gateway.contoso.com.pfx", "password");
                var settingsProvider = new AppConfigSettingsProvider();
                BlobSessionStatePersistenceProvider blobSessionStateProvider = BlobSessionStatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("BlobSessionStatePersistenceProvider.StorageContainerName")).Result;

                TableQos2StatePersistenceProvider tableQos2StateProvider = TableQos2StatePersistenceProvider.CreateAsync(
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageConnectionString"),
                    settingsProvider.GetSetting("TableQos2StatePersistenceProvider.StorageTableName")).Result;

                var bootstrapper = new Bootstrapper(settingsProvider, blobSessionStateProvider, tableQos2StateProvider);
                Task.Run(() => bootstrapper.RunAsync(certificate, threadCount, cts.Token), cts.Token);

                while (true)
                {
                    string input = Console.ReadLine();
                    if (input != null && input.ToLowerInvariant() == "exit")
                    {
                        break;
                    }
                }

                cts.Cancel();
                bootstrapper.CloseCompletion.Wait(TimeSpan.FromSeconds(20));
            }
            finally
            {
                eventListener.Dispose();
            }
        }
    }
}


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

namespace GlobalcachingApplication.Plugins.SqlServer
{
    public partial class DatabaseSelectionForm : Form
    {
        public const string STR_SERVER = "Server";
        public const string STR_DATABASE = "Database";
        public const string STR_TITLE = "Sql server database";
        public const string STR_NTIS = "Use Windows authentification";
        public const string STR_USERNAME = "User name";
        public const string STR_PASSWROD = "Password";

        public DatabaseSelectionForm()
        {
            InitializeComponent();

            this.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_TITLE);
            this.label1.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_SERVER);
            this.label4.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_DATABASE);
            this.label6.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_USERNAME);
            this.label8.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_PASSWROD);
            this.checkBox1.Text = Utils.LanguageSupport.Instance.GetTranslation(STR_NTIS);

            textBox1.Text = Properties.Settings.Default.SqlServer;
            textBox2.Text = Properties.Settings.Default.Database;
            textBox3.Text = Properties.Settings.Default.SqlServerUsername;
            textBox4.Text = Properties.Settings.Default.SqlServerPwd;
            checkBox1.Checked = Properties.Settings.Default.SqlServerUseIS;
        }

        public string SqlServer
        {
            get { return textBox1.Text; }
        }
        public string Database
        {
            get { return textBox2.Text; }
        }
        public string Username
        {
            get { return textBox3.Text; }
        }
        public string Password
        {
            get { return textBox4.Text; }
        }
        public bool IntegratedSecurity
        {
            get { return checkBox1.Checked; }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            button1.Enabled = (textBox1.Text.Length > 0 && textBox2.Text.Length > 0);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            textBox3.Enabled = !checkBox1.Checked;
            textBox4.Enabled = !checkBox1.Checked;
        }
    }
}


text:
Description

Extends 404 error page with the notfound.org code.

Thanks for using eSyndiCat Directory Software!


text:
/************************************************
 interfaces.cpp
 Fodder Factory Monitoring and Control

 (c) Brendan McLearie - bmclearie@mclearie.com

 Interface Processing
 ************************************************/

/************************************************
  Includes
************************************************/
#include <build_config.h>
//#include <debug_ff.h>
#include <events.h>
//#include <HAL.h>
#include <interfaces.h>
#include <registry.h>
#include <string_consts.h>
//#include <block_common.h>
#include <utils.h>

//#ifdef ARDUINO_VEDIRECT
//#include <VEDirect.h>
//#endif //ARDUINO_VEDIRECT

#include <OneWire.h>                // comms to Dallas temprature sensors
#include <DallasTemperature.h>

/************************************************
  Data Structures
************************************************/

/************************************************
  Globals
************************************************/

/************************************************
  Interface Processing Functions
************************************************/

void ScanAndMatchDallasSensors(InterfaceNode* i, uint8_t report) {
	// Scan the OneWire port specified by bus and iterate the
	// 	DallasTemperature devices dicovered.
	// For each device, lookup the interface list for DS1820B
	//  interface types and compare the addresses of the devices
	// If report == 0, raise an EventMsg warning for any unmatched
	//  devices.
	// IF report == 1, write verbose information via ITCH.

	InterfaceONEWIRE_BUS *ifs;
	ifs = (InterfaceONEWIRE_BUS *)i->IFSettings;
	OneWire one_wire(ifs->bus_pin);            		// oneWire instance to communicate with any OneWire devices
	DallasTemperature sensors(&one_wire);     // Pass our one_wire reference to Dallas Temperature

	DeviceAddress addr;
	uint8_t count;
	uint8_t res;
	uint16_t match;

	float tempC;
	char fmt[12];
	char out[MAX_LOG_LINE_LENGTH];

	sensors.begin();
	count = sensors.getDeviceCount();

	if (report) {
		ITCHWrite(F("Bus"));
		strcpy_hal(fmt, F(" %d"));
		sprintf(out, fmt, ifs->bus_pin);
		ITCHWrite(out);

		ITCHWrite(F(" Device Count:"));
		sprintf(out, fmt, count);
		ITCHWriteLine(out);
	}

	for (uint8_t index = 0; index < count; index++) {
		sensors.getAddress(addr, index);
		sensors.setResolution(addr, 12);
		sensors.setCheckForConversion(true);
		sensors.setWaitForConversion(true);
		//delay(300);
		sensors.requestTemperaturesByIndex(index);
		//delay(500);
		tempC = sensors.getTempCByIndex(index);
		//delay(300);
		res = sensors.getResolution(addr);
		sensors.setWaitForConversion(true);

		if (report) {
			ITCHWrite(F("Bus:"));
			strcpy_hal(fmt, F(" %d"));
			sprintf(out, fmt, ifs->bus_pin);
			ITCHWrite(out);

			ITCHWrite(F(" Index:"));
			strcpy_hal(fmt, F(" %d Addr: "));
			sprintf(out, fmt, index);
			ITCHWrite(out);

			DallasAddressArrayToString(out, addr);
			ITCHWrite(out);

			ITCHWrite(F(" Resolution:"));
			strcpy_hal(fmt, F(" %d TempC: "));
			sprintf(out, fmt, res);
			ITCHWrite(out);

			FFFloatToCString(out, tempC);
			ITCHWrite(out);
		}

		match = GetInterfaceWithMatchingDallas(addr);
		if (match) {
			if (report) {
				ITCHWrite(F(" - Matched To: "));
				strcpy_hal(fmt, F("%d "));
				sprintf(out, fmt, match);
				ITCHWrite(out);
				ITCHWriteLine(GetBlockLabelString(match));
			} else {
				EventMsg(i->id, E_INFO, M_DALLAS_DETECTED);
			}
		} else {
			if (report) {
				ITCHWriteLine(F(" - NOT MATCHED."));
				//ITCHWriteLine(F(" - Assign first unmatched with: \"INTERFACE ONEWIRE ASSIGN <bus_id> <device_id>\""));
			} else {
				EventMsg(i->id, E_WARNING, M_UNASSIGNED_DALLAS);
			}
		}

	}
}

void AssignDallasSensor(InterfaceNode *s, InterfaceNode *t, uint8_t report) {
	InterfaceONEWIRE_BUS *ifs_s;
	InterfaceDS1820B *ifs_t;
	ifs_s = (InterfaceONEWIRE_BUS *)s->IFSettings;
	ifs_t = (InterfaceDS1820B *)t->IFSettings;

	OneWire one_wire(ifs_s->bus_pin);            		// oneWire instance to communicate with any OneWire devices
	DallasTemperature sensors(&one_wire);     // Pass our one_wire reference to Dallas Temperature

	DeviceAddress addr;
	uint8_t count;

	uint16_t match;

	char fmt[11];
	char out[MAX_LOG_LINE_LENGTH];

	sensors.begin();
	count = sensors.getDeviceCount();

	for (uint8_t index = 0; index < count; index++) {
		sensors.getAddress(addr, index);
		match = GetInterfaceWithMatchingDallas(addr);
		if (match) {
			if (report) {
				ITCHWrite(F("Bus:"));
				strcpy_hal(fmt, F(" %d"));
				sprintf(out, fmt, ifs_s->bus_pin);
				ITCHWrite(out);

				ITCHWrite(F(" Index:"));
				strcpy_hal(fmt, F(" %d Addr: "));
				sprintf(out, fmt, index);
				ITCHWrite(out);

				DallasAddressArrayToString(out, addr);
				ITCHWrite(out);
				ITCHWrite(F(" - Matched to: "));
				strcpy_hal(fmt, F("%d "));
				sprintf(out, fmt, match);
				ITCHWrite(out);
				ITCHWriteLine(GetBlockLabelString(match));
			}
		} else {
			// assign it to the Dallas interface
			ifs_t->bus_pin = ifs_s->bus_pin;
			DallasCopy(addr, ifs_t->dallas_address);
			if (report) {
				ITCHWrite(F("Bus:"));
				strcpy_hal(fmt, F(" %d"));
				sprintf(out, fmt, ifs_s->bus_pin);
				ITCHWrite(out);

				ITCHWrite(F(" Index:"));
				strcpy_hal(fmt, F(" %d Addr: "));
				sprintf(out, fmt, index);
				ITCHWrite(out);
				DallasAddressArrayToString(out, addr);
				ITCHWrite(out);
				ITCHWrite(F(" - Assigned to "));
				ITCHWriteLine(t->label);
			}
			return; // only assign the first unmatched device
		}
		//delay(500);
	}

}

void InterfaceONEWIRE_BUS_Setup(InterfaceNode* b) {
	ScanAndMatchDallasSensors(b, 0);
}

void InterfaceDS1820B_Setup(InterfaceNode *b) {
	InterfaceDS1820B* ifs;
	ifs = (InterfaceDS1820B *)b->IFSettings;
	float tempC;

	OneWire one_wire(ifs->bus_pin); // oneWire instance to communicate with any OneWire devices
	DallasTemperature sensors(&one_wire);     // Pass our one_wire reference to Dallas Temperature

	sensors.begin();
	if (sensors.isConnected(ifs->dallas_address)) {
		sensors.setResolution(ifs->dallas_address, 12);
		sensors.setCheckForConversion(true);
		sensors.setWaitForConversion(true);
		sensors.requestTemperaturesByAddress(ifs->dallas_address);
		tempC = sensors.getTempC(ifs->dallas_address);
		EventMsg(b->id, E_INFO, M_DS1820B_INIT, tempC, FLOAT_INIT);
		sensors.setWaitForConversion(false);
		ifs->in_progress = 0;
	} else {
		EventMsg(b->id, E_WARNING, M_DS1820B_INIT_FAIL);
		ifs->in_progress = 0;
	}
}

uint8_t InterfaceDS1820B_Read(float* tempC, uint16_t id, uint8_t wait) {
	// Read the temperature in degrees C of the Dallas DS1820B device
	// configured as an interface identified by id.
	// If successful update the result in *tempC
	// If wait is specified as true (1), wait for the result after
	// 	requesting a conversion (ie telling device to read and convert temp)
	// If wait is false (0), request a conversion and return immediately
	// Returns:
	//	0 - Error - device disconnected or result out of range
	//  1 - Conversion completed and *tempC has been updated
	//  2 - if wait is false - conversion requested or in progress, not yet available

	InterfaceNode* b;
	InterfaceDS1820B* ifs;
	float temptempC = FLOAT_INIT;

	b = GetInterfaceByID(id);
	if (b != NULL) {
		ifs = (InterfaceDS1820B *)b->IFSettings;

		OneWire one_wire(ifs->bus_pin);            		// oneWire instance to communicate with any OneWire devices
		DallasTemperature sensors(&one_wire);     // Pass our one_wire reference to Dallas Temperature

		//sensors.begin();

		if (wait) {
			sensors.setWaitForConversion(true);
			sensors.setResolution(12);
			if (sensors.requestTemperaturesByAddress(ifs->dallas_address)) {
				temptempC = sensors.getTempC(ifs->dallas_address);
				if ( (temptempC > (float)TEMP_C_LOW) && temptempC < (float)TEMP_C_HIGH) {
					*tempC = temptempC;
					b->status = STATUS_ENABLED_RUN;
					ifs->in_progress = 0;
					return 1;
				} else {
					EventMsg(b->id, E_WARNING, M_BAD_TEMPERATURE_READ, 0, temptempC);
					b->status = STATUS_ENABLED_INVALID_DATA;
					ifs->in_progress = 0;
					return 0;
				}
			} else {
				EventMsg(b->id, E_ERROR, M_DS1820B_INIT_FAIL);
				b->status = STATUS_DISABLED_ERROR;
				ifs->in_progress = 0;
				return 0;
			}
		} else { // not wait
			if (ifs->in_progress == 1 && sensors.isConversionComplete()) {
				// requested previously and now available
				temptempC = sensors.getTempC(ifs->dallas_address);
				ifs->in_progress = 0;
				if ( (temptempC > (float)TEMP_C_LOW) && temptempC < (float)TEMP_C_HIGH) {
					*tempC = temptempC;
					b->status = STATUS_ENABLED_RUN;
					return 1;
				} else {
					EventMsg(b->id, E_WARNING, M_BAD_TEMPERATURE_READ, 0, temptempC);
					b->status = STATUS_ENABLED_INVALID_DATA;
					return 0;
				}
			} else {
				if (ifs->in_progress == 1) {
					// therefore isConversionAvailable was false - still converting
					b->status = STATUS_ENABLED_BUSY;
					return 2;
				} else {
					// not in_progress
					sensors.setWaitForConversion(false);
					sensors.setResolution(12);
					if (sensors.requestTemperaturesByAddress(ifs->dallas_address)) {
						b->status = STATUS_ENABLED_BUSY;
						ifs->in_progress = 1;
						return 2;
					} else {
						EventMsg(b->id, E_WARNING, M_BAD_TEMPERATURE_READ, 0, temptempC);
						ifs->in_progress = 0;
						b->status = STATUS_DISABLED_ERROR;
						return 0;
					}
				}
			}
		}
	} else {
		// b== NULL
		EventMsg(SSS, E_ERROR, M_DS1820B_BID_NULL);
		return 0;
	}
	return 0;
}

void InterfaceShow(InterfaceNode *b, void(Callback(const char *))) {
	char out_str[MAX_MESSAGE_STRING_LENGTH];
	char fmt_str[MAX_LABEL_LENGTH];
	char label_str[MAX_LABEL_LENGTH];

	strcpy_hal(out_str, F("Base Data"));
	Callback(out_str);

	strcpy_hal(fmt_str, F(" id:           %d"));
	sprintf(out_str, fmt_str, b->id);
	Callback(out_str);

	strcpy_hal(fmt_str, F(" cat:          %s (%d)"));
	strcpy_hal(label_str, block_cat_strings[FF_INTERFACE].text);
	sprintf(out_str, fmt_str, label_str, FF_INTERFACE);
	Callback(out_str);

	strcpy_hal(fmt_str, F(" type:         %s (%d)"));
	strcpy_hal(label_str, interface_type_strings[b->type].text);
	sprintf(out_str, fmt_str, label_str, b->type);
	Callback(out_str);

	strcpy_hal(fmt_str, F(" label:        %s"));
	sprintf(out_str, fmt_str, b->label);
	Callback(out_str);

#ifndef EXCLUDE_DISPLAYNAME
	strcpy_hal(fmt_str, F(" display_name: %s"));
	sprintf(out_str, fmt_str, b->display_name);
	Callback(out_str);
#endif
#ifndef EXCLUDE_DESCRIPTION
	strcpy_hal(fmt_str, F(" description:  %s"));
	sprintf(out_str, fmt_str, b->description);
	Callback(out_str);
#endif

	strcpy_hal(out_str, F("Operational Data"));
	Callback(out_str);

	strcpy_hal(fmt_str, F(" active:       %s"));
	strcpy_hal(label_str, F("NA"));
	sprintf(out_str, fmt_str, label_str);
	Callback(out_str);

	/*
	strcpy_hal(fmt_str, F(" bool_val:     %s (%d)"));
	if (b->bool_val == 1) {
		strcpy_hal(label_str, F("True"));
	} else {
		strcpy_hal(label_str, F("False"));
	}
	sprintf(out_str, fmt_str, label_str, b->bool_val);
	Callback(out_str);

	if (b->int_val == INT32_INIT) {
		strcpy_hal(out_str, F(" int_val:      INT32_INIT"));
	} else {
		strcpy_hal(fmt_str, F(" int_val:      %ld"));
		sprintf(out_str, fmt_str, b->int_val);
	}
	Callback(out_str);

	if (b->f_val == FLOAT_INIT) {
		strcpy_hal(out_str, F(" f_val:        FLOAT_INIT"));
	} else {
		FFFloatToCString(label_str, b->f_val);
		strcpy_hal(fmt_str, F(" f_val:        %s"));
		sprintf(out_str, fmt_str, label_str);
	}
	Callback(out_str);
	*/

	strcpy_hal(fmt_str, F(" status:       %s (%d)"));
	strcpy_hal(label_str, status_strings[b->status].text);
	sprintf(out_str, fmt_str, label_str, b->status);
	Callback(out_str);

	strcpy_hal(out_str, F("Interface:"));
	Callback(out_str);

	switch (b->type) {
		case IF_ONEWIRE_BUS: {
			InterfaceONEWIRE_BUS* ifs;
			ifs = (InterfaceONEWIRE_BUS *)b->IFSettings;

			strcpy_hal(fmt_str, F(" bus_pin:      %d"));
			sprintf(out_str, fmt_str, ifs->bus_pin);
			Callback(out_str);

			strcpy_hal(fmt_str, F(" device_count  %d"));
			sprintf(out_str, fmt_str, ifs->device_count);
			Callback(out_str);
		}
			break;
		case IF_DS1820B: {
			InterfaceDS1820B* ifs;
			ifs = (InterfaceDS1820B *)b->IFSettings;

			strcpy_hal(fmt_str, F(" bus_pin:      %d"));
			sprintf(out_str, fmt_str, ifs->bus_pin);
			Callback(out_str);

			strcpy_hal(fmt_str, F(" dallas_addr   %s"));
			DallasAddressArrayToString(label_str, ifs->dallas_address);
			sprintf(out_str, fmt_str, label_str);
			Callback(out_str);

		}
			break;
		default:
			break;
	}
}


text:
import React from 'react';
import { kebabCase, startCase } from 'lodash';
import PropTypes from 'prop-types';
import {
  Alert,
  Col,
  ControlLabel,
  FormControl,
  FormGroup,
  HelpBlock
} from '@freecodecamp/react-bootstrap';
import { Field } from 'react-final-form';

const propTypes = {
  fields: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired,
  options: PropTypes.shape({
    ignored: PropTypes.arrayOf(PropTypes.string),
    placeholders: PropTypes.objectOf(PropTypes.string),
    required: PropTypes.arrayOf(PropTypes.string),
    types: PropTypes.objectOf(PropTypes.string)
  })
};

function FormFields(props) {
  const { fields, options = {} } = props;
  const {
    ignored = [],
    placeholders = {},
    required = [],
    types = {}
  } = options;
  return (
    <div>
      {fields
        .filter(field => !ignored.includes(field))
        .map(name => (
          <Field key={`${name}-field`} name={name}>
            {({ input: { value, onChange }, meta: { pristine, error } }) => {
              const key = kebabCase(name);
              const type = name in types ? types[name] : 'text';
              const placeholder =
                name in placeholders ? placeholders[name] : '';
              return (
                <Col key={key} xs={12}>
                  <FormGroup>
                    {type === 'hidden' ? null : (
                      <ControlLabel htmlFor={key}>
                        {startCase(name)}
                      </ControlLabel>
                    )}
                    <FormControl
                      componentClass={type === 'textarea' ? type : 'input'}
                      id={key}
                      name={name}
                      onChange={onChange}
                      placeholder={placeholder}
                      required={required.includes(name)}
                      rows={4}
                      type={type}
                      value={value}
                    />
                    {error && !pristine ? (
                      <HelpBlock>
                        <Alert bsStyle='danger'>{error}</Alert>
                      </HelpBlock>
                    ) : null}
                  </FormGroup>
                </Col>
              );
            }}
          </Field>
        ))}
    </div>
  );
}

FormFields.displayName = 'FormFields';
FormFields.propTypes = propTypes;

export default FormFields;


text:
class CreateCatergorizedProducts < ActiveRecord::Migration
  def change
    create_table :catergorized_products do |t|
      t.integer :product_id
      t.integer :category_id

      t.timestamps
    end
  end
end


text:
package raftor

// Updater applies cluster change events
type Updater interface {

	// Update is called after the ClusterChangeEvent has been processed and stored by Raft.
	Update(ClusterChangeEvent)
}


text:
package edu.psu.swe.scim.spec.resources;

import java.io.Serializable;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import edu.psu.swe.scim.spec.annotation.ScimAttribute;
import edu.psu.swe.scim.spec.annotation.ScimResourceType;
import edu.psu.swe.scim.spec.schema.ResourceReference;
import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
@ScimResourceType(id = ScimGroup.RESOURCE_NAME, name = ScimGroup.RESOURCE_NAME, schema = ScimGroup.SCHEMA_URI, description = "Top level ScimGroup", endpoint = "/Groups")
@XmlRootElement(name = ScimGroup.RESOURCE_NAME)
@XmlAccessorType(XmlAccessType.NONE)
public class ScimGroup extends ScimResource implements Serializable {

  private static final long serialVersionUID = 4424638498347469070L;
  public static final String RESOURCE_NAME = "Group";
  public static final String SCHEMA_URI = "urn:ietf:params:scim:schemas:core:2.0:Group";

  @XmlElement
  @ScimAttribute(description="A human-readable name for the Group.", required=true)
  String displayName;

  @XmlElement
  @ScimAttribute(description = "A list of members of the Group.")
  List<ResourceReference> members;

  public ScimGroup() {
    super(SCHEMA_URI);
  }

  @Override
  public String getResourceType() {
    return RESOURCE_NAME;
  }
}


text:
namespace NServiceBus.AcceptanceTests
{
    using System;
    using AcceptanceTesting.Support;
    using ScenarioDescriptors;

    public static class RunDescriptorExtensions
    {
        public static Type GetTransportType(this RunDescriptor runDescriptor)
        {
            Type transportType;
            if (!runDescriptor.Settings.TryGet("Transport", out transportType))
            {
                return Transports.Default.Settings.Get<Type>("Transport");
            }

            return transportType;
        }
    }
}


text:
process.env.FRONTEND_URL = "dummy"
process.env.SESSION_SECRET = "dummy"
process.env.TWITTER_CONSUMER_KEY = "dummy"
process.env.TWITTER_CONSUMER_SECRET = "dummy"
process.env.TWITTER_CALLBACK_URL = "dummy"


text:
<?php

/**
 * @see Zend_Gdata_App_MediaData
 */
require_once 'Zend/Gdata/App/BaseMediaSource.php';

/**
 * Concrete class to use a file handle as an attachment within a MediaEntry.
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage App
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_App_MediaFileSource extends Zend_Gdata_App_BaseMediaSource
{
    /**
     * The filename which is represented
     *
     * @var string
     */
    protected $_filename = null;

    /**
     * The content type for the file attached (example image/png)
     *
     * @var string
     */
    protected $_contentType = null;

    /**
     * Create a new Zend_Gdata_App_MediaFileSource object.
     *
     * @param string $filename The name of the file to read from.
     */
    public function __construct($filename)
    {
        $this->setFilename($filename);
    }

    /**
     * Return the MIME multipart representation of this MediaEntry.
     *
     * @return string
     * @throws Zend_Gdata_App_IOException
     */
    public function encode()
    {
        if ($this->getFilename() !== null &&
            is_readable($this->getFilename())) {

            // Retrieves the file, using the include path
            $fileHandle = fopen($this->getFilename(), 'r', true);
            $result = fread($fileHandle, filesize($this->getFilename()));
            if ($result === false) {
                require_once 'Zend/Gdata/App/IOException.php';
                throw new Zend_Gdata_App_IOException("Error reading file - " .
                        $this->getFilename() . '. Read failed.');
            }
            fclose($fileHandle);
            return $result;
        } else {
            require_once 'Zend/Gdata/App/IOException.php';
            throw new Zend_Gdata_App_IOException("Error reading file - " .
                    $this->getFilename() . '. File is not readable.');
        }
    }

    /**
     * Get the filename associated with this reader.
     *
     * @return string
     */
    public function getFilename()
    {
        return $this->_filename;
    }

    /**
     * Set the filename which is to be read.
     *
     * @param string $value The desired file handle.
     * @return Zend_Gdata_App_MediaFileSource Provides a fluent interface.
     */
    public function setFilename($value)
    {
        $this->_filename = $value;
        return $this;
    }

    /**
     * The content type for the file attached (example image/png)
     *
     * @return string The content type
     */
    public function getContentType()
    {
        return $this->_contentType;
    }

    /**
     * Set the content type for the file attached (example image/png)
     *
     * @param string $value The content type
     * @return Zend_Gdata_App_MediaFileSource Provides a fluent interface
     */
    public function setContentType($value)
    {
        $this->_contentType = $value;
        return $this;
    }

    /**
     * Alias for getFilename().
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getFilename();
    }

}


text:
NSString *const KTP_API_TOKEN = @"5af9a24515589a73d0fa687e69cbaaa15918f833";

@implementation KTPNetworking

+ (NSString*)requestTypeToString:(KTPRequestType)type {
    switch (type) {
        case KTPRequestTypePOST:
            return @"POST";
        case KTPRequestTypeGET:
            return @"GET";
        case KTPRequestTypePUT:
            return @"PUT";
        case KTPRequestTypeDELETE:
            return @"DELETE";
    }
}

+ (NSString*)requestRouteToString:(KTPRequestRoute)route {
    switch (route) {
        case KTPRequestRouteAPIMembers:
            return @"/api/members/";
        case KTPRequestRouteAPILogin:
            return @"/api/login/";
        case KTPRequestRouteAPIChangePassword:
            return @"/api/changePassword/";
        case KTPRequestRouteAPIPitches:
            return @"/api/pitches/";
        case KTPRequestRouteAPIPledgeTasks:
            return @"/api/pledgeTasks/";
        case KTPRequestRouteAPIPledgeMeetings:
            return @"/api/pledgeMeetings/";
        case KTPRequestRouteAPICommittees:
            return @"/api/committees/";
    }
}

+ (NSString*)contentTypeToString:(KTPContentType)type {
    switch (type) {
        case KTPContentTypeJSON:
            return @"application/json";
        case KTPContentTypePNG:
            return @"image/png";
    }
}

+ (void)sendAsynchronousRequestType:(KTPRequestType)requestType
                            toRoute:(KTPRequestRoute)route
                          appending:(NSString*)append
                         parameters:(NSString*)parameters
                       withJSONBody:(NSDictionary *)body
                              block:(void (^)(NSURLResponse *, NSData *, NSError *))block
{
    NSData *data;
    NSError *error;
    if (body) {
        data = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    }

    if (!error) {
        [KTPNetworking sendAsynchronousRequestType:requestType toRoute:route appending:append parameters:parameters withData:data contentType:KTPContentTypeJSON block:block];
    } else {
        NSLog(@"JSON Serialization Failed");
        block(nil, nil, error);
    }
}

+ (void)sendAsynchronousRequestType:(KTPRequestType)requestType
                            toRoute:(KTPRequestRoute)route
                          appending:(NSString*)append
                         parameters:(NSString*)parameters
                           withData:(NSData *)data
                        contentType:(KTPContentType)contentType
                              block:(void (^)(NSURLResponse *, NSData *, NSError *))block
{
    NSMutableString *requestRouteString = [[KTPNetworking requestRouteToString:route] mutableCopy];
    if (append) {
        [requestRouteString appendString:append];
    }
    if (parameters) {
        [requestRouteString appendFormat:@"?%@", parameters];
    }

    [KTPNetworking sendAsynchronousRequestType:requestType
                                       toRoute:requestRouteString
                                      withData:data
                                   contentType:contentType
                                         block:block];
}

+ (void)sendAsynchronousRequestType:(KTPRequestType)requestType
                            toRoute:(NSString*)route
                           withData:(NSData*)data
                        contentType:(KTPContentType)contentType
                              block:(void (^)(NSURLResponse*, NSData*, NSError*))block
{
    NSString *requestTypeString = [KTPNetworking requestTypeToString:requestType];
    NSString *contentTypeString = [KTPNetworking contentTypeToString:contentType];

    NSString *requestURLString = [NSString stringWithFormat:@"http://kappathetapi.com%@", route];
    NSURL *requestURL = [NSURL URLWithString:requestURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
    request.allHTTPHeaderFields = @{@"x-access-token"   : KTP_API_TOKEN,
                                    @"Content-Type"     : contentTypeString};
    request.HTTPMethod = requestTypeString;
    request.HTTPBody = data;

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        !block ?: block(response, data, connectionError);
    }];
}

@end


text:
struct vec3
{
    float x, y, z;
};

mesh* load_mesh_ctm(char const* filepath) {
    CTMcontext context = ctmNewContext(CTM_IMPORT);
    ctmLoad(context, path_for_resource_and_type(filepath));
    assert(ctmGetError(context) == CTM_NONE);

    CTMuint tri_count = ctmGetInteger(context, CTM_TRIANGLE_COUNT);;
    CTMuint num_vertices = ctmGetInteger(context, CTM_VERTEX_COUNT);
    CTMuint num_indices = tri_count * 3;
    CTMuint num_normals = 0;
    CTMfloat const* vertices = ctmGetFloatArray(context, CTM_VERTICES);
    CTMuint const* indices = ctmGetIntegerArray(context, CTM_INDICES);
    CTMfloat const* normals = 0;
    if (ctmGetInteger(context, CTM_HAS_NORMALS) == CTM_TRUE) {
        num_normals = num_vertices;
        normals = ctmGetFloatArray(context, CTM_NORMALS);
    }

    mesh* new_mesh = new mesh;
    new_mesh->num_tris = tri_count;
    new_mesh->normals = num_normals > 0;

    // Create buffers
    glGenBuffers(1, &(new_mesh->vert_vbo));
    glBindBuffer(GL_ARRAY_BUFFER, new_mesh->vert_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vec3) * num_vertices, vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &(new_mesh->norm_vbo));
    glBindBuffer(GL_ARRAY_BUFFER, new_mesh->norm_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vec3) * num_vertices, normals, GL_STATIC_DRAW);

    assert(indices);
    glGenBuffers(1, &(new_mesh->ibo));
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, new_mesh->ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(CTMuint) * num_indices, indices, GL_STATIC_DRAW);

    ctmFreeContext(context);

    return new_mesh;
}

void draw_mesh(mesh const* mesh, GLuint pos_attrib, GLint normal_attrib) {
    glBindBuffer(GL_ARRAY_BUFFER, mesh->vert_vbo);
    glVertexAttribPointer(pos_attrib, 3, GL_FLOAT, GL_FALSE, sizeof(vec3), 0);
    glEnableVertexAttribArray(pos_attrib);

    if (mesh->normals && normal_attrib >= 0) {
        glBindBuffer(GL_ARRAY_BUFFER, mesh->norm_vbo);
        glVertexAttribPointer(normal_attrib, 3, GL_FLOAT, GL_FALSE, sizeof(vec3), 0);
        glEnableVertexAttribArray(normal_attrib);
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh->ibo);
    glDrawElements(GL_TRIANGLES, mesh->num_tris * 3, GL_UNSIGNED_INT, 0);

    glDisableVertexAttribArray(pos_attrib);
    glDisableVertexAttribArray(normal_attrib);
}


text:
package videostitcher

// [START videostitcher_list_cdn_keys]
import (
	"context"
	"fmt"
	"io"

	"google.golang.org/api/iterator"

	stitcher "cloud.google.com/go/video/stitcher/apiv1"
	"cloud.google.com/go/video/stitcher/apiv1/stitcherpb"
)

// listCdnKeys gets all of the CDN keys for a given location.
func listCdnKeys(w io.Writer, projectID string) error {
	// projectID := "my-project-id"
	location := "us-central1"
	ctx := context.Background()
	client, err := stitcher.NewVideoStitcherClient(ctx)
	if err != nil {
		return fmt.Errorf("stitcher.NewVideoStitcherClient: %v", err)
	}
	defer client.Close()

	req := &stitcherpb.ListCdnKeysRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListCdnKeys(ctx, req)
	fmt.Fprintln(w, "CDN keys:")
	for {
		response, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("it.Next(): %v", err)
		}
		fmt.Fprintln(w, response.GetName())
	}

	return nil
}

// [END videostitcher_list_cdn_keys]


text:
@interface OCLogObject ()

@property (nonatomic, strong) NSDate *logTime;

- (NSString *)logDescription;

@end


text:
// Portions copyright Hiroshi Ito. Licensed under Apache 2.0 license

package com.gs.fw.common.mithra.finder;

import com.gs.fw.common.mithra.attribute.Attribute;
import com.gs.fw.common.mithra.attribute.NonPrimitiveAttribute;
import com.gs.fw.common.mithra.attribute.StringAttribute;
import com.gs.fw.common.mithra.databasetype.DatabaseType;
import com.gs.fw.common.mithra.extractor.Extractor;
import com.gs.fw.common.mithra.finder.bytearray.ByteArraySet;
import com.gs.fw.common.mithra.finder.sqcache.ExactMatchSmr;
import com.gs.fw.common.mithra.finder.sqcache.NoMatchSmr;
import com.gs.fw.common.mithra.finder.sqcache.ShapeMatchResult;
import com.gs.fw.common.mithra.finder.sqcache.SuperMatchSmr;
import com.gs.fw.common.mithra.util.Time;
import org.eclipse.collections.impl.set.mutable.SetAdapter;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.TimeZone;

public class NonPrimitiveNotInOperation extends NotInOperation implements SqlParameterSetter, Externalizable
{
    private Set set;
    private transient volatile Object[] copiedArray;

    public NonPrimitiveNotInOperation(NonPrimitiveAttribute attribute, Set set)
    {
        super(attribute);
        this.set = set;
    }

    public NonPrimitiveNotInOperation()
    {
        // for Externalizable
    }

    @Override
    protected int getMaxLength()
    {
        if (this.getAttribute() instanceof StringAttribute)
        {
            Set<String> strings = (Set<String>) set;
            int max = 0;
            for(Iterator<String> it = strings.iterator(); it.hasNext();)
            {
                String next = it.next();
                if (next != null && next.length() > max)
                {
                    max = next.length();
                }
            }
            return max;
        }
        return 0;
    }

    protected int setSqlParameters(PreparedStatement pstmt, int startIndex, TimeZone timeZone, int setStart, int numberToSet, DatabaseType databaseType) throws SQLException
    {
        populateCopiedArray();
        for(int i=setStart;i<setStart+numberToSet;i++)
        {
            ((NonPrimitiveAttribute)this.getAttribute()).setSqlParameter(startIndex++, pstmt, copiedArray[i], timeZone, databaseType);
        }
        return numberToSet;
    }

    protected void populateCopiedArray()
    {
        if (this.copiedArray == null)
        {
            synchronized (this)
            {
                if (copiedArray == null)
                {
                    copiedArray = new Object[set.size()];
                    set.toArray(copiedArray);
                    if (copiedArray.length > 1 && !set.contains(null) && copiedArray[0] instanceof Comparable)
                    {
                        Arrays.sort(this.copiedArray);
                    }
                }
            }
        }
    }

    public int hashCode()
    {
        return ~(this.getAttribute().hashCode() ^ this.set.hashCode());
    }

    public boolean equals(Object obj)
    {
        if (obj == this) return true;
        if (obj instanceof NonPrimitiveNotInOperation)
        {
            NonPrimitiveNotInOperation other = (NonPrimitiveNotInOperation) obj;
            return this.getAttribute().equals(other.getAttribute()) && this.set.equals(other.set);
        }
        return false;
    }

    public int getSetSize()
    {
        return this.set.size();
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeObject(this.getAttribute());
        int size = this.getSetSize();
        out.writeInt(size);
        out.writeBoolean(set instanceof ByteArraySet);
        for (Iterator it = this.set.iterator(); size > 0; size--)
        {
            this.writeParameter(out, it.next());
        }
    }

    protected void writeParameter(ObjectOutput out, Object o) throws IOException
    {
        out.writeObject(o);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        this.setAttribute((Attribute) in.readObject());
        int size = in.readInt();
        boolean isByteArray = in.readBoolean();
        if (isByteArray)
        {
            this.set = new ByteArraySet(size);
        }
        else
        {
            this.set = new UnifiedSet(size);
        }
        for(int i=0;i<size;i++)
        {
            set.add(this.readParameter(in));
        }
    }

    protected Object readParameter(ObjectInput in) throws IOException, ClassNotFoundException
    {
        return in.readObject();
    }

    @Override
    public byte[] getSetValueAsByteArray(int index)
    {
        return (byte[]) copiedArray[index];
    }

    @Override
    public Date getSetValueAsDate(int index)
    {
        return (Date) copiedArray[index];
    }

    @Override
    public Time getSetValueAsTime(int index)
    {
        return (Time) copiedArray[index];
    }

    @Override
    public String getSetValueAsString(int index)
    {
        return (String) copiedArray[index];
    }

    @Override
    public Timestamp getSetValueAsTimestamp(int index)
    {
        return (Timestamp) copiedArray[index];
    }

    @Override
    protected void appendSetToString(ToStringContext toStringContext)
    {
        NonPrimitiveAttribute nonPrimitiveAttribute = (NonPrimitiveAttribute) this.getAttribute();
        String formattedStrings = SetAdapter.adapt(this.set)
                .asLazy()
                .collect(nonPrimitiveAttribute::formattedValue)
                .toString();
        toStringContext.append(formattedStrings);
    }

    @Override
    public BigDecimal getSetValueAsBigDecimal(int index)
    {
        return (BigDecimal) copiedArray[index];
    }

    @Override
    public boolean setContains(Object holder, Extractor extractor)
    {
        return this.set.contains(extractor.valueOf(holder));
    }

    @Override
    protected ShapeMatchResult shapeMatchSet(NotInOperation existingOperation)
    {
        if (existingOperation.getSetSize() < MAX_SHAPE_MATCH_SIZE)
        {
            NonPrimitiveNotInOperation loopOp = (NonPrimitiveNotInOperation) existingOperation;
            Iterator floatIterator = loopOp.set.iterator();
            while(floatIterator.hasNext())
            {
                if (!this.set.contains(floatIterator.next()))
                {
                    return NoMatchSmr.INSTANCE;
                }
            }
            return (this.getSetSize() == loopOp.getSetSize()) ? ExactMatchSmr.INSTANCE : new SuperMatchSmr(existingOperation, this);
        }
        return NoMatchSmr.INSTANCE;
    }
}


text:
body {
  padding-top: 50px;
}

.pager-lg {
    font-size: large;
}

.pager-control {
    font-size: x-large;
    padding: 4px 8px;
    cursor: pointer;
}

/* Use to collapse empty button columns */

.hideable {
    min-height: 0px;
}

label.label-switch {
    margin-top: 5px;
}

/* Styling for disabled, active buttons */
.btn.disabled.active{
    box-shadow: inset 0 3px 5px rgba(0,0,0,1);
}


text:
package org.wso2.carbon.bpmn.rest.api.internal.common;

import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.impl.AbstractQuery;
import org.activiti.engine.query.Query;
import org.activiti.engine.query.QueryProperty;
import org.activiti.rest.common.api.DataResponse;
import org.activiti.rest.common.api.PaginateRequest;
import org.activiti.rest.common.api.RequestUtil;

import javax.ws.rs.core.UriInfo;
import java.util.List;
import java.util.Map;

public abstract  class AbstractPaginateList {

    protected RestResponseFactory restResponseFactory;
    protected UriInfo uriInfo;

    public AbstractPaginateList(RestResponseFactory restResponseFactory, UriInfo uriInfo){
        this.restResponseFactory = restResponseFactory;
        this.uriInfo = uriInfo;
    }

    public DataResponse paginateList(Map<String, String> requestParams, PaginateRequest paginateRequest, Query query,
                                     String defaultSort, Map<String, QueryProperty> properties) {

        if (paginateRequest == null) {
            paginateRequest = new PaginateRequest();
        }

        // In case pagination request is incomplete, fill with values found in URL if possible
        if (paginateRequest.getStart() == null) {
            paginateRequest.setStart(RequestUtil.getInteger(requestParams, "start", 0));
        }

        if (paginateRequest.getSize() == null) {
            paginateRequest.setSize(RequestUtil.getInteger(requestParams, "size", 10));
        }

        if (paginateRequest.getOrder() == null) {
            paginateRequest.setOrder(requestParams.get("order"));
        }

        if (paginateRequest.getSort() == null) {
            paginateRequest.setSort(requestParams.get("sort"));
        }

        // Use defaults for paging, if not set in the PaginationRequest, nor in the URL
        Integer start = paginateRequest.getStart();
        if(start == null || start < 0) {
            start = 0;
        }

        Integer size = paginateRequest.getSize();
        if(size == null || size < 0) {
            size = 10;
        }

        String sort = paginateRequest.getSort();
        if(sort == null) {
            sort = defaultSort;
        }
        String order = paginateRequest.getOrder();
        if(order == null) {
            order = "asc";
        }

        // Sort order
        if (sort != null && !properties.isEmpty()) {
            QueryProperty qp = properties.get(sort);
            if (qp == null) {
                throw new ActivitiIllegalArgumentException("Value for param 'sort' is not valid, '" + sort + "' is not a valid property");
            }
            ((AbstractQuery) query).orderBy(qp);
            if (order.equals("asc")) {
                query.asc();
            }
            else if (order.equals("desc")) {
                query.desc();
            }
            else {
                throw new ActivitiIllegalArgumentException("Value for param 'order' is not valid : '" + order + "', must be 'asc' or 'desc'");
            }
        }

        // Get result and set pagination parameters
        List list = processList(query.listPage(start, size));
        DataResponse response = new DataResponse();
        response.setStart(start);
        response.setSize(list.size());
        response.setSort(sort);
        response.setOrder(order);
        response.setTotal(query.count());
        response.setData(list);
        return response;
    }

    /**
     * uses the pagination parameters from the request and makes sure to order the result and set all pagination
     * attributes for the response to render
     *
     * @param requestParams The request containing the pagination parameters
     * @param query The query to get the paged list from
     * @param properties The model to put the list and the pagination attributes in
     * @param defaultSort THe default sort column (the rest attribute) that later will be mapped to an internal engine name
     */
    @SuppressWarnings("rawtypes")
    public DataResponse paginateList(Map<String, String> requestParams, Query query,
                                     String defaultSort, Map<String, QueryProperty> properties) {
        return paginateList(requestParams, null, query, defaultSort, properties);
    }

    @SuppressWarnings("rawtypes")
    protected abstract List processList(List list);

}


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Migration_Install_project_permissions extends Migration {

	// permissions to migrate
	private $permission_values = array(
		array('name' => 'Project.Content.View', 'description' => '', 'status' => 'active',),
		array('name' => 'Project.Content.Create', 'description' => '', 'status' => 'active',),
		array('name' => 'Project.Content.Edit', 'description' => '', 'status' => 'active',),
		array('name' => 'Project.Content.Delete', 'description' => '', 'status' => 'active',),
	);

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

	public function up()
	{
		$prefix = $this->db->dbprefix;

		// permissions
		foreach ($this->permission_values as $permission_value)
		{
			$permissions_data = $permission_value;
			$this->db->insert("permissions", $permissions_data);
			$role_permissions_data = array('role_id' => '1', 'permission_id' => $this->db->insert_id(),);
			$this->db->insert("role_permissions", $role_permissions_data);
		}
	}

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

	public function down()
	{
		$prefix = $this->db->dbprefix;

        // permissions
		foreach ($this->permission_values as $permission_value)
		{
			$query = $this->db->select('permission_id')->get_where("permissions", array('name' => $permission_value['name'],));
			foreach ($query->result_array() as $row)
			{
				$permission_id = $row['permission_id'];
				$this->db->delete("role_permissions", array('permission_id' => $permission_id));
			}
			$this->db->delete("permissions", array('name' => $permission_value['name']));

		}
	}

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

}


text:
#ifndef DATE_TIME_LOCAL_TIME_CONVERSION_HPP__
#define DATE_TIME_LOCAL_TIME_CONVERSION_HPP__

#include "boost/date_time/posix_time/conversion.hpp"
#include "boost/date_time/c_time.hpp"
#include "boost/date_time/local_time/local_date_time.hpp"

namespace boost {
namespace local_time {

//! Function that creates a tm struct from a local_date_time
inline
tm to_tm(const local_date_time& lt) {
  tm lt_tm;
  lt_tm = posix_time::to_tm(lt.local_time());
  if(lt.is_dst()){
    lt_tm.tm_isdst = 1;
  }
  else{
    lt_tm.tm_isdst = 0;
  }
  return lt_tm;
}

}} // namespaces
#endif // DATE_TIME_LOCAL_TIME_CONVERSION_HPP__


text:
/*********************************************************************/
/* Copyright (c) 2014, EPFL/Blue Brain Project                       */
/*                     Raphael Dumusc <raphael.dumusc@epfl.ch>       */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/*   1. Redistributions of source code must retain the above         */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer.                                                  */
/*                                                                   */
/*   2. Redistributions in binary form must reproduce the above      */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer in the documentation and/or other materials       */
/*      provided with the distribution.                              */
/*                                                                   */
/*    THIS  SOFTWARE IS PROVIDED  BY THE  UNIVERSITY OF  TEXAS AT    */
/*    AUSTIN  ``AS IS''  AND ANY  EXPRESS OR  IMPLIED WARRANTIES,    */
/*    INCLUDING, BUT  NOT LIMITED  TO, THE IMPLIED  WARRANTIES OF    */
/*    MERCHANTABILITY  AND FITNESS FOR  A PARTICULAR  PURPOSE ARE    */
/*    DISCLAIMED.  IN  NO EVENT SHALL THE UNIVERSITY  OF TEXAS AT    */
/*    AUSTIN OR CONTRIBUTORS BE  LIABLE FOR ANY DIRECT, INDIRECT,    */
/*    INCIDENTAL,  SPECIAL, EXEMPLARY,  OR  CONSEQUENTIAL DAMAGES    */
/*    (INCLUDING, BUT  NOT LIMITED TO,  PROCUREMENT OF SUBSTITUTE    */
/*    GOODS  OR  SERVICES; LOSS  OF  USE,  DATA,  OR PROFITS;  OR    */
/*    BUSINESS INTERRUPTION) HOWEVER CAUSED  AND ON ANY THEORY OF    */
/*    LIABILITY, WHETHER  IN CONTRACT, STRICT  LIABILITY, OR TORT    */
/*    (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY WAY OUT    */
/*    OF  THE  USE OF  THIS  SOFTWARE,  EVEN  IF ADVISED  OF  THE    */
/*    POSSIBILITY OF SUCH DAMAGE.                                    */
/*                                                                   */
/* The views and conclusions contained in the software and           */
/* documentation are those of the authors and should not be          */
/* interpreted as representing official policies, either expressed   */
/* or implied, of The University of Texas at Austin.                 */
/*********************************************************************/

#ifndef TEXTINPUTHANDLER_H
#define TEXTINPUTHANDLER_H

#include <QObject>

#include "dcWebservice/Handler.h"

#include "types.h"

/**
 * Handle "/textinput" requests for the WebService.
 *
 * When a valid request is received, the receivedText() signal is emitted.
 * This class is typically used in the WebServiceServer thread and communicates
 * with the TextInputDispatcher in the main thread via signals/slots.
 */
class TextInputHandler : public QObject, public dcWebservice::Handler
{
    Q_OBJECT

public:
    /**
     * Handle TextInput requests.
     * @param displayGroupManagerAdapter An adapter over the displayGroupManager,
     * used for unit testing. If provided, the class takes ownership of it.
     */
    TextInputHandler(DisplayGroupManagerAdapterPtr displayGroupManagerAdapter);

    /** Destructor */
    virtual ~TextInputHandler();

    /**
     * Handle a request.
     * @param request A valid dcWebservice::Request object.
     * @return A valid Response object.
     */
    virtual dcWebservice::ConstResponsePtr handle(const dcWebservice::Request& request) const;

signals:
    /**
     * Emitted whenever a request is successfully handled.
     * @param key The key code received in the Request.
     */
    void receivedKeyInput(char key) const;

private:
    DisplayGroupManagerAdapterPtr displayGroupManagerAdapter_;
};

#endif // TEXTINPUTHANDLER_H


text:
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings

import stripe

class Subscriber(models.Model):
    user_rec = models.ForeignKey(User)
    address_one = models.CharField(max_length=100)
    address_two = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=50)
    state = models.CharField(max_length=2)
    stripe_id = models.CharField(max_length=30, blank=True)

    class Meta:
        verbose_name_plural = 'subscribers'

    def __unicode__(self):
        return u"%s's Subscription Info" % self.user_rec

    def charge(self, request, email, fee):
        stripe.api_key = settings.STRIPE_SECRET_KEY

        # Get the credit card details submitted by the form
        token = request.POST['stripeToken']

        # Create a Customer
        stripe_customer = stripe.Customer.create(
            card=token,
            description=email
        )

        # Save the Stripe ID to the customer
        self.stripe_id = stripe_customer.id
        self.save()

        # Charge the Customer instead of the card
        stripe.Charge.create(
            amount=fee,
            currency="usd",
            customer=stripe_customer.id
        )

        return stripe_customer


text:
id: bad87fee1348bd9aec908846
title: Create a Bootstrap Headline
challengeType: 0
forumTopicId: 16812
---

## Description

Now let's build something from scratch to practice our HTML, CSS and Bootstrap skills.
We'll build a jQuery playground, which we'll soon put to use in our jQuery challenges.
To start with, create an h3 element, with the text jQuery Playground.
Color your h3 element with the text-primary Bootstrap class, and center it with the text-center Bootstrap class.

## Instructions

## Tests

```yml
tests:
  - text: You should add an <code>h3</code> element to your page.
    testString: assert($("h3") && $("h3").length > 0);
  - text: Your <code>h3</code> element should have a closing tag.
    testString: assert(code.match(/<\/h3>/g) && code.match(/<h3/g) && code.match(/<\/h3>/g).length === code.match(/<h3/g).length);
  - text: Your <code>h3</code> element should be colored by applying the class <code>text-primary</code>
    testString: assert($("h3").hasClass("text-primary"));
  - text: Your <code>h3</code> element should be centered by applying the class <code>text-center</code>
    testString: assert($("h3").hasClass("text-center"));
  - text: Your <code>h3</code> element should have the text <code>jQuery Playground</code>.
    testString: assert.isTrue((/jquery(\s)+playground/gi).test($("h3").text()));

```

## Challenge Seed

```html

```

## Solution

```html
<h3 class="text-primary text-center">jQuery Playground</h3>
```


text:
<?php

/**
 *
 * This is the POST destination for most all locally posted
 * text stuff. This function handles status, wall-to-wall status,
 * local comments, and remote coments that are posted on this site
 * (as opposed to being delivered in a feed).
 * Also processed here are posts and comments coming through the
 * statusnet/twitter API.
 * All of these become an "item" which is our basic unit of
 * information.
 * Posts that originate externally or do not fall into the above
 * posting categories go through item_store() instead of this function.
 *
 */

require_once('include/crypto.php');
require_once('include/enotify.php');
require_once('include/items.php');
require_once('include/attach.php');

function item_post(&$a) {

	// This will change. Figure out who the observer is and whether or not
	// they have permission to post here. Else ignore the post.

	if((! local_user()) && (! remote_channel()) && (! x($_REQUEST,'commenter')))
		return;

	require_once('include/security.php');

	$uid = local_user();
	$channel = null;
	$observer = null;

	/**
	 * Is this a reply to something?
	 */

	$parent = ((x($_REQUEST,'parent')) ? intval($_REQUEST['parent']) : 0);
	$parent_mid = ((x($_REQUEST,'parent_mid')) ? trim($_REQUEST['parent_mid']) : '');

	$remote_xchan = ((x($_REQUEST,'remote_xchan')) ? trim($_REQUEST['remote_xchan']) : false);
	$r = q("select * from xchan where xchan_hash = '%s' limit 1",
		dbesc($remote_xchan)
	);
	if($r)
		$remote_observer = $r[0];
	else
		$remote_xchan = $remote_observer = false;

	$profile_uid = ((x($_REQUEST,'profile_uid')) ? intval($_REQUEST['profile_uid'])    : 0);
	require_once('include/identity.php');
	$sys = get_sys_channel();
	if($sys && $profile_uid && ($sys['channel_id'] == $profile_uid) && is_site_admin()) {
		$uid = intval($sys['channel_id']);
		$channel = $sys;
		$observer = $sys;
	}

	if(x($_REQUEST,'dropitems')) {
		require_once('include/items.php');
		$arr_drop = explode(',',$_REQUEST['dropitems']);
		drop_items($arr_drop);
		$json = array('success' => 1);
		echo json_encode($json);
		killme();
	}

	call_hooks('post_local_start', $_REQUEST);

//	 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);

	$api_source = ((x($_REQUEST,'api_source') && $_REQUEST['api_source']) ? true : false);

	$consensus = intval($_REQUEST['consensus']);

	// 'origin' (if non-zero) indicates that this network is where the message originated,
	// for the purpose of relaying comments to other conversation members.
	// If using the API from a device (leaf node) you must set origin to 1 (default) or leave unset.
	// If the API is used from another network with its own distribution
	// and deliveries, you may wish to set origin to 0 or false and allow the other
	// network to relay comments.

	// If you are unsure, it is prudent (and important) to leave it unset.

	$origin = (($api_source && array_key_exists('origin',$_REQUEST)) ? intval($_REQUEST['origin']) : 1);

	// To represent message-ids on other networks - this will create an item_id record

	$namespace = (($api_source && array_key_exists('namespace',$_REQUEST)) ? strip_tags($_REQUEST['namespace']) : '');
	$remote_id = (($api_source && array_key_exists('remote_id',$_REQUEST)) ? strip_tags($_REQUEST['remote_id']) : '');

	$owner_hash = null;

	$message_id  = ((x($_REQUEST,'message_id') && $api_source)  ? strip_tags($_REQUEST['message_id'])       : '');
	$created     = ((x($_REQUEST,'created'))     ? datetime_convert('UTC','UTC',$_REQUEST['created']) : datetime_convert());
	$post_id     = ((x($_REQUEST,'post_id'))     ? intval($_REQUEST['post_id'])        : 0);
	$app         = ((x($_REQUEST,'source'))      ? strip_tags($_REQUEST['source'])     : '');
	$return_path = ((x($_REQUEST,'return'))      ? $_REQUEST['return']                 : '');
	$preview     = ((x($_REQUEST,'preview'))     ? intval($_REQUEST['preview'])        : 0);
	$categories  = ((x($_REQUEST,'category'))    ? escape_tags($_REQUEST['category'])  : '');
	$webpage     = ((x($_REQUEST,'webpage'))     ? intval($_REQUEST['webpage'])        : 0);
	$pagetitle   = ((x($_REQUEST,'pagetitle'))   ? escape_tags(urlencode($_REQUEST['pagetitle'])) : '');
	$layout_mid  = ((x($_REQUEST,'layout_mid'))  ? escape_tags($_REQUEST['layout_mid']): '');
	$plink       = ((x($_REQUEST,'permalink'))   ? escape_tags($_REQUEST['permalink']) : '');
	$obj_type    = ((x($_REQUEST,'obj_type'))    ? escape_tags($_REQUEST['obj_type'])  : ACTIVITY_OBJ_NOTE);

	// allow API to bulk load a bunch of imported items with sending out a bunch of posts.
	$nopush      = ((x($_REQUEST,'nopush'))      ? intval($_REQUEST['nopush'])         : 0);

	/*
	 * Check service class limits
	 */
	if ($uid && !(x($_REQUEST,'parent')) && !(x($_REQUEST,'post_id'))) {
		$ret = item_check_service_class($uid,(($_REQUEST['webpage'] == ITEM_WEBPAGE) ? true : false));
		if (!$ret['success']) {
			notice( t($ret['message']) . EOL) ;
			if(x($_REQUEST,'return'))
				goaway($a->get_baseurl() . "/" . $return_path );
			killme();
		}
	}

	if($pagetitle) {
		require_once('library/urlify/URLify.php');
		$pagetitle = strtolower(URLify::transliterate($pagetitle));
	}

	$item_flags = $item_restrict = 0;

	$route = '';
	$parent_item = null;
	$parent_contact = null;
	$thr_parent = '';
	$parid = 0;
	$r = false;

	if($parent || $parent_mid) {

		if(! x($_REQUEST,'type'))
			$_REQUEST['type'] = 'net-comment';

		if($obj_type == ACTIVITY_OBJ_POST)
			$obj_type = ACTIVITY_OBJ_COMMENT;

		if($parent) {
			$r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
				intval($parent)
			);
		}
		elseif($parent_mid && $uid) {
			// This is coming from an API source, and we are logged in
			$r = q("SELECT * FROM `item` WHERE `mid` = '%s' AND `uid` = %d LIMIT 1",
				dbesc($parent_mid),
				intval($uid)
			);
		}
		// if this isn't the real parent of the conversation, find it
		if($r !== false && count($r)) {
			$parid = $r[0]['parent'];
			$parent_mid = $r[0]['mid'];
			if($r[0]['id'] != $r[0]['parent']) {
				$r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
					intval($parid)
				);
			}
		}

		if(($r === false) || (! count($r))) {
			notice( t('Unable to locate original post.') . EOL);
			if(x($_REQUEST,'return'))
				goaway($a->get_baseurl() . "/" . $return_path );
			killme();
		}

		// can_comment_on_post() needs info from the following xchan_query
		xchan_query($r);

		$parent_item = $r[0];
		$parent = $r[0]['id'];

		// multi-level threading - preserve the info but re-parent to our single level threading

		$thr_parent = $parent_mid;

		$route = $parent_item['route'];

	}

	if(! $observer)
		$observer = $a->get_observer();

	if($parent) {
		logger('mod_item: item_post parent=' . $parent);
		$can_comment = false;
		if((array_key_exists('owner',$parent_item)) && ($parent_item['owner']['abook_flags'] & ABOOK_FLAG_SELF))
			$can_comment = perm_is_allowed($profile_uid,$observer['xchan_hash'],'post_comments');
		else
			$can_comment = can_comment_on_post($observer['xchan_hash'],$parent_item);

		if(! $can_comment) {
			notice( t('Permission denied.') . EOL) ;
			if(x($_REQUEST,'return'))
				goaway($a->get_baseurl() . "/" . $return_path );
			killme();
		}
	}
	else {
		if(! perm_is_allowed($profile_uid,$observer['xchan_hash'],'post_wall')) {
			notice( t('Permission denied.') . EOL) ;
			if(x($_REQUEST,'return'))
				goaway($a->get_baseurl() . "/" . $return_path );
			killme();
		}
	}

	// is this an edited post?

	$orig_post = null;

	if($namespace && $remote_id) {
		// It wasn't an internally generated post - see if we've got an item matching this remote service id
		$i = q("select iid from item_id where service = '%s' and sid = '%s' limit 1",
			dbesc($namespace),
			dbesc($remote_id)
		);
		if($i)
			$post_id = $i[0]['iid'];
	}

	if($post_id) {
		$i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
			intval($profile_uid),
			intval($post_id)
		);
		if(! count($i))
			killme();
		$orig_post = $i[0];
	}

	if(! $channel) {
		if($uid && $uid == $profile_uid) {
			$channel = $a->get_channel();
		}
		else {
			// posting as yourself but not necessarily to a channel you control
			$r = q("select * from channel left join account on channel_account_id = account_id where channel_id = %d LIMIT 1",
				intval($profile_uid)
			);
			if($r)
				$channel = $r[0];
		}
	}

	if(! $channel) {
		logger("mod_item: no channel.");
		if(x($_REQUEST,'return'))
			goaway($a->get_baseurl() . "/" . $return_path );
		killme();
	}

	$owner_xchan = null;

	$r = q("select * from xchan where xchan_hash = '%s' limit 1",
		dbesc($channel['channel_hash'])
	);
	if($r && count($r)) {
		$owner_xchan = $r[0];
	}
	else {
		logger("mod_item: no owner.");
		if(x($_REQUEST,'return'))
			goaway($a->get_baseurl() . "/" . $return_path );
		killme();
	}

	$walltowall = false;
	$walltowall_comment = false;

	if($remote_xchan)
		$observer = $remote_observer;

	if($observer) {
		logger('mod_item: post accepted from ' . $observer['xchan_name'] . ' for ' . $owner_xchan['xchan_name'], LOGGER_DEBUG);

		// wall-to-wall detection.
		// For top-level posts, if the author and owner are different it's a wall-to-wall
		// For comments, We need to additionally look at the parent and see if it's a wall post that originated locally.

		if($observer['xchan_name'] != $owner_xchan['xchan_name'])  {
			if($parent_item && ($parent_item['item_flags'] & (ITEM_WALL|ITEM_ORIGIN)) == (ITEM_WALL|ITEM_ORIGIN)) {
				$walltowall_comment = true;
				$walltowall = true;
			}
			if(! $parent) {
				$walltowall = true;
			}
		}
	}

	$public_policy = ((x($_REQUEST,'public_policy')) ? escape_tags($_REQUEST['public_policy']) : map_scope($channel['channel_r_stream'],true));
	if($webpage)
		$public_policy = '';
	if($public_policy)
		$private = 1;

	if($orig_post) {
		$private = 0;
		// webpages are allowed to change ACLs after the fact. Normal conversation items aren't.
		if($webpage) {
			$str_group_allow   = perms2str($_REQUEST['group_allow']);
			$str_contact_allow = perms2str($_REQUEST['contact_allow']);
			$str_group_deny    = perms2str($_REQUEST['group_deny']);
			$str_contact_deny  = perms2str($_REQUEST['contact_deny']);
		}
		else {
			$str_group_allow   = $orig_post['allow_gid'];
			$str_contact_allow = $orig_post['allow_cid'];
			$str_group_deny    = $orig_post['deny_gid'];
			$str_contact_deny  = $orig_post['deny_cid'];
			$public_policy     = $orig_post['public_policy'];
			$private           = $orig_post['item_private'];
		}

		if((strlen($str_group_allow))
			|| strlen($str_contact_allow)
			|| strlen($str_group_deny)
			|| strlen($str_contact_deny)
			|| strlen($public_policy)
			|| $private) {
			$private = 1;
		}

		$location          = $orig_post['location'];
		$coord             = $orig_post['coord'];
		$verb              = $orig_post['verb'];
		$app               = $orig_post['app'];
		$title             = escape_tags(trim($_REQUEST['title']));
		$body              = trim($_REQUEST['body']);
		$item_flags        = $orig_post['item_flags'];

		// force us to recalculate if we need to obscure this post

		if($item_flags & ITEM_OBSCURED)
			$item_flags = ($item_flags ^ ITEM_OBSCURED);

		$item_restrict     = $orig_post['item_restrict'];
		$postopts          = $orig_post['postopts'];
		$created           = $orig_post['created'];
		$mid               = $orig_post['mid'];
		$parent_mid        = $orig_post['parent_mid'];
		$plink             = $orig_post['plink'];

	}
	else {

		// if coming from the API and no privacy settings are set,
		// use the user default permissions - as they won't have
		// been supplied via a form.

		if(($api_source)
			&& (! array_key_exists('contact_allow',$_REQUEST))
			&& (! array_key_exists('group_allow',$_REQUEST))
			&& (! array_key_exists('contact_deny',$_REQUEST))
			&& (! array_key_exists('group_deny',$_REQUEST))) {
			$str_group_allow   = $channel['channel_allow_gid'];
			$str_contact_allow = $channel['channel_allow_cid'];
			$str_group_deny    = $channel['channel_deny_gid'];
			$str_contact_deny  = $channel['channel_deny_cid'];
		}
		elseif($walltowall) {

			// use the channel owner's default permissions

			$str_group_allow   = $channel['channel_allow_gid'];
			$str_contact_allow = $channel['channel_allow_cid'];
			$str_group_deny    = $channel['channel_deny_gid'];
			$str_contact_deny  = $channel['channel_deny_cid'];
		}
		else {

			// use the posted permissions

			$str_group_allow   = perms2str($_REQUEST['group_allow']);
			$str_contact_allow = perms2str($_REQUEST['contact_allow']);
			$str_group_deny    = perms2str($_REQUEST['group_deny']);
			$str_contact_deny  = perms2str($_REQUEST['contact_deny']);
		}

		$location          = notags(trim($_REQUEST['location']));
		$coord             = notags(trim($_REQUEST['coord']));
		$verb              = notags(trim($_REQUEST['verb']));
		$title             = escape_tags(trim($_REQUEST['title']));
		$body              = trim($_REQUEST['body']);
		$body              .= trim($_REQUEST['attachment']);
		$postopts          = '';

		$private = (
				(  strlen($str_group_allow)
				|| strlen($str_contact_allow)
				|| strlen($str_group_deny)
				|| strlen($str_contact_deny)
				|| strlen($public_policy)
		) ? 1 : 0);

		// If this is a comment, set the permissions from the parent.

		if($parent_item) {
			$private = 0;

			if(($parent_item['item_private'])
				|| strlen($parent_item['allow_cid'])
				|| strlen($parent_item['allow_gid'])
				|| strlen($parent_item['deny_cid'])
				|| strlen($parent_item['deny_gid'])
				|| strlen($parent_item['public_policy'])) {
				$private = (($parent_item['item_private']) ? $parent_item['item_private'] : 1);
			}

			$public_policy     = $parent_item['public_policy'];
			$str_contact_allow = $parent_item['allow_cid'];
			$str_group_allow   = $parent_item['allow_gid'];
			$str_contact_deny  = $parent_item['deny_cid'];
			$str_group_deny    = $parent_item['deny_gid'];
			$owner_hash        = $parent_item['owner_xchan'];
		}

		if(! strlen($body)) {
			if($preview)
				killme();
			info( t('Empty post discarded.') . EOL );
			if(x($_REQUEST,'return'))
				goaway($a->get_baseurl() . "/" . $return_path );
			killme();
		}
	}

	$expires = NULL_DATE;

	if(feature_enabled($profile_uid,'content_expire')) {
		if(x($_REQUEST,'expire')) {
			$expires = datetime_convert(date_default_timezone_get(),'UTC', $_REQUEST['expire']);
			if($expires <= datetime_convert())
				$expires = NULL_DATE;
		}
	}

	$mimetype = notags(trim($_REQUEST['mimetype']));
	if(! $mimetype)
		$mimetype = 'text/bbcode';

	if($preview) {
		$body = z_input_filter($profile_uid,$body,$mimetype);
	}

	// Verify ability to use html or php!!!

	$execflag = false;

	if($mimetype === 'application/x-php') {
		$z = q("select account_id, account_roles, channel_pageflags from account left join channel on channel_account_id = account_id where channel_id = %d limit 1",
			intval($profile_uid)
		);
		if($z && (($z[0]['account_roles'] & ACCOUNT_ROLE_ALLOWCODE) || ($z[0]['channel_pageflags'] & PAGE_ALLOWCODE))) {
			if($uid && (get_account_id() == $z[0]['account_id'])) {
				$execflag = true;
			}
			else {
				notice( t('Executable content type not permitted to this channel.') . EOL);
				if(x($_REQUEST,'return'))
					goaway($a->get_baseurl() . "/" . $return_path );
				killme();
			}
		}
	}

	if($mimetype === 'text/bbcode') {

		require_once('include/text.php');
		if($uid && $uid == $profile_uid && feature_enabled($uid,'markdown')) {
			require_once('include/bb2diaspora.php');
			$body = escape_tags($body);
			$body = preg_replace_callback('/\[share(.*?)\]/ism','share_shield',$body);
			$body = diaspora2bb($body,true);
			$body = preg_replace_callback('/\[share(.*?)\]/ism','share_unshield',$body);
		}

		// BBCODE alert: the following functions assume bbcode input
		// and will require alternatives for alternative content-types (text/html, text/markdown, text/plain, etc.)
		// we may need virtual or template classes to implement the possible alternatives

		// Work around doubled linefeeds in Tinymce 3.5b2
		// First figure out if it's a status post that would've been
		// created using tinymce. Otherwise leave it alone.

		$plaintext = true;

//		$plaintext = ((feature_enabled($profile_uid,'richtext')) ? false : true);
//		if((! $parent) && (! $api_source) && (! $plaintext)) {
//			$body = fix_mce_lf($body);
//		}

		// If we're sending a private top-level message with a single @-taggable channel as a recipient, @-tag it, if our pconfig is set.

		if((! $parent) && (get_pconfig($profile_uid,'system','tagifonlyrecip')) && (substr_count($str_contact_allow,'<') == 1) && ($str_group_allow == '') && ($str_contact_deny == '') && ($str_group_deny == '')) {
			$x = q("select abook_id, abook_their_perms from abook where abook_xchan = '%s' and abook_channel = %d limit 1",
				dbesc(str_replace(array('<','>'),array('',''),$str_contact_allow)),
				intval($profile_uid)
			);
			if($x && ($x[0]['abook_their_perms'] & PERMS_W_TAGWALL))
				$body .= "\n\n@group+" . $x[0]['abook_id'] . "\n";
		}

		/**
		 * fix naked links by passing through a callback to see if this is a red site
		 * (already known to us) which will get a zrl, otherwise link with url, add bookmark tag to both.
		 * First protect any url inside certain bbcode tags so we don't double link it.
		 */

		$body = preg_replace_callback('/\[code(.*?)\[\/(code)\]/ism','red_escape_codeblock',$body);
		$body = preg_replace_callback('/\[url(.*?)\[\/(url)\]/ism','red_escape_codeblock',$body);
		$body = preg_replace_callback('/\[zrl(.*?)\[\/(zrl)\]/ism','red_escape_codeblock',$body);

		$body = preg_replace_callback("/([^\]\='".'"'."\/]|^|\#\^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\@\_\~\#\%\$\!\+\,]+)/ism", 'red_zrl_callback', $body);

		$body = preg_replace_callback('/\[\$b64zrl(.*?)\[\/(zrl)\]/ism','red_unescape_codeblock',$body);
		$body = preg_replace_callback('/\[\$b64url(.*?)\[\/(url)\]/ism','red_unescape_codeblock',$body);
		$body = preg_replace_callback('/\[\$b64code(.*?)\[\/(code)\]/ism','red_unescape_codeblock',$body);

		// fix any img tags that should be zmg

		$body = preg_replace_callback('/\[img(.*?)\](.*?)\[\/img\]/ism','red_zrlify_img_callback',$body);

		$body = bb_translate_video($body);

		/**
		 * Fold multi-line [code] sequences
		 */

		$body = preg_replace('/\[\/code\]\s*\[code\]/ism',"\n",$body);

		$body = scale_external_images($body,false);

		// Look for tags and linkify them
		$results = linkify_tags($a, $body, ($uid) ? $uid : $profile_uid);

		if($results) {

			// Set permissions based on tag replacements
			set_linkified_perms($results, $str_contact_allow, $str_group_allow, $profile_uid, $parent_item, $private);

			$post_tags = array();
			foreach($results as $result) {
				$success = $result['success'];
				if($success['replaced']) {
					$post_tags[] = array(
						'uid'   => $profile_uid,
						'type'  => $success['termtype'],
						'otype' => TERM_OBJ_POST,
						'term'  => $success['term'],
						'url'   => $success['url']
					);
				}
			}
		}

		/**
		 *
		 * When a photo was uploaded into the message using the (profile wall) ajax
		 * uploader, The permissions are initially set to disallow anybody but the
		 * owner from seeing it. This is because the permissions may not yet have been
		 * set for the post. If it's private, the photo permissions should be set
		 * appropriately. But we didn't know the final permissions on the post until
		 * now. So now we'll look for links of uploaded photos and attachments that are in the
		 * post and set them to the same permissions as the post itself.
		 *
		 * If the post was end-to-end encrypted we can't find images and attachments in the body,
		 * use our media_str input instead which only contains these elements - but only do this
		 * when encrypted content exists because the photo/attachment may have been removed from
		 * the post and we should keep it private. If it's encrypted we have no way of knowing
		 * so we'll set the permissions regardless and realise that the media may not be
		 * referenced in the post.
		 *
		 * What is preventing us from being able to upload photos into comments is dealing with
		 * the photo and attachment permissions, since we don't always know who was in the
		 * distribution for the top level post.
		 *
		 * We might be able to provide this functionality with a lot of fiddling:
		 * - if the top level post is public (make the photo public)
		 * - if the top level post was written by us or a wall post that belongs to us (match the top level post)
		 * - if the top level post has privacy mentions, add those to the permissions.
		 * - otherwise disallow the photo *or* make the photo public. This is the part that gets messy.
		 */

		if(! $preview) {
			fix_attached_photo_permissions($profile_uid,$owner_xchan['xchan_hash'],((strpos($body,'[/crypt]')) ? $_POST['media_str'] : $body),$str_contact_allow,$str_group_allow,$str_contact_deny,$str_group_deny);

			fix_attached_file_permissions($channel,$observer['xchan_hash'],((strpos($body,'[/crypt]')) ? $_POST['media_str'] : $body),$str_contact_allow,$str_group_allow,$str_contact_deny,$str_group_deny);

		}

		$attachments = '';
		$match = false;

		if(preg_match_all('/(\[attachment\](.*?)\[\/attachment\])/',$body,$match)) {
			$attachments = array();
			foreach($match[2] as $mtch) {
				$hash = substr($mtch,0,strpos($mtch,','));
				$rev = intval(substr($mtch,strpos($mtch,',')));
				$r = attach_by_hash_nodata($hash,$rev);
				if($r['success']) {
					$attachments[] = array(
						'href'     => $a->get_baseurl() . '/attach/' . $r['data']['hash'],
						'length'   => $r['data']['filesize'],
						'type'     => $r['data']['filetype'],
						'title'    => urlencode($r['data']['filename']),
						'revision' => $r['data']['revision']
					);
				}
				$body = str_replace($match[1],'',$body);
			}
		}

	}

// BBCODE end alert

	if(strlen($categories)) {
		$cats = explode(',',$categories);
		foreach($cats as $cat) {
			$post_tags[] = array(
				'uid'   => $profile_uid,
				'type'  => TERM_CATEGORY,
				'otype' => TERM_OBJ_POST,
				'term'  => trim($cat),
				'url'   => $owner_xchan['xchan_url'] . '?f=&cat=' . urlencode(trim($cat))
			);
		}
	}

	$item_unseen =  1;

	// determine if this is a wall post

	if($parent) {
		if($parent_item['item_flags'] & ITEM_WALL) {
			$item_flags = $item_flags | ITEM_WALL;
		}
	}
	else {
		if(! $webpage) {
			$item_flags = $item_flags | ITEM_WALL;
		}
	}

	if($origin)
		$item_flags = $item_flags | ITEM_ORIGIN;

	if($moderated)
		$item_restrict = $item_restrict | ITEM_MODERATED;

	if($webpage)
		$item_restrict = $item_restrict | $webpage;

	if(! strlen($verb))
		$verb = ACTIVITY_POST ;

	$notify_type = (($parent) ? 'comment-new' : 'wall-new' );

	if(! $mid) {
		$mid = (($message_id) ? $message_id : item_message_id());
	}
	if(! $parent_mid) {
		$parent_mid = $mid;
	}

	if($parent_item)
		$parent_mid = $parent_item['mid'];

	// Fallback so that we alway have a thr_parent

	if(!$thr_parent)
		$thr_parent = $mid;

	$datarray = array();

	if(! $parent) {
		$item_flags = $item_flags | ITEM_THREAD_TOP;
	}

	if($consensus)
		$item_flags |= ITEM_CONSENSUS;

	if ((! $plink) && ($item_flags & ITEM_THREAD_TOP)) {
		$plink = z_root() . '/channel/' . $channel['channel_address'] . '/?f=&mid=' . $mid;
	}

	$datarray['aid']            = $channel['channel_account_id'];
	$datarray['uid']            = $profile_uid;

	$datarray['owner_xchan']    = (($owner_hash) ? $owner_hash : $owner_xchan['xchan_hash']);
	$datarray['author_xchan']   = $observer['xchan_hash'];
	$datarray['created']        = $created;
	$datarray['edited']         = (($orig_post) ? datetime_convert() : $created);
	$datarray['expires']        = $expires;
	$datarray['commented']      = (($orig_post) ? datetime_convert() : $created);
	$datarray['received']       = (($orig_post) ? datetime_convert() : $created);
	$datarray['changed']        = (($orig_post) ? datetime_convert() : $created);
	$datarray['mid']            = $mid;
	$datarray['parent_mid']     = $parent_mid;
	$datarray['mimetype']       = $mimetype;
	$datarray['title']          = $title;
	$datarray['body']           = $body;
	$datarray['app']            = $app;
	$datarray['location']       = $location;
	$datarray['coord']          = $coord;
	$datarray['verb']           = $verb;
	$datarray['obj_type']       = $obj_type;
	$datarray['allow_cid']      = $str_contact_allow;
	$datarray['allow_gid']      = $str_group_allow;
	$datarray['deny_cid']       = $str_contact_deny;
	$datarray['deny_gid']       = $str_group_deny;
	$datarray['item_private']   = $private;
	$datarray['attach']         = $attachments;
	$datarray['thr_parent']     = $thr_parent;
	$datarray['postopts']       = $postopts;
	$datarray['item_restrict']  = $item_restrict;
	$datarray['item_flags']     = $item_flags;
	$datarray['layout_mid']     = $layout_mid;
	$datarray['public_policy']  = $public_policy;
	$datarray['comment_policy'] = map_scope($channel['channel_w_comment']);
	$datarray['term']           = $post_tags;
	$datarray['plink']          = $plink;
	$datarray['route']          = $route;
	$datarray['item_unseen']    = $item_unseen;

	// preview mode - prepare the body for display and send it via json

	if($preview) {
		require_once('include/conversation.php');

		$datarray['owner'] = $owner_xchan;
		$datarray['author'] = $observer;
		$datarray['attach'] = json_encode($datarray['attach']);
		$o = conversation($a,array($datarray),'search',false,'preview');
//		logger('preview: ' . $o, LOGGER_DEBUG);
		echo json_encode(array('preview' => $o));
		killme();
	}
	if($orig_post)
		$datarray['edit'] = true;

	call_hooks('post_local',$datarray);

	if(x($datarray,'cancel')) {
		logger('mod_item: post cancelled by plugin.');
		if($return_path) {
			goaway($a->get_baseurl() . "/" . $return_path);
		}

		$json = array('cancel' => 1);
		if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
			$json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];

		echo json_encode($json);
		killme();
	}

	if(mb_strlen($datarray['title']) > 255)
		$datarray['title'] = mb_substr($datarray['title'],0,255);

	if(array_key_exists('item_private',$datarray) && $datarray['item_private']) {

		$datarray['body'] = trim(z_input_filter($datarray['uid'],$datarray['body'],$datarray['mimetype']));

		if($uid) {
			if($channel['channel_hash'] === $datarray['author_xchan']) {
				$datarray['sig'] = base64url_encode(rsa_sign($datarray['body'],$channel['channel_prvkey']));
				$datarray['item_flags'] = $datarray['item_flags'] | ITEM_VERIFIED;
			}
		}

		logger('Encrypting local storage');
		$key = get_config('system','pubkey');
		$datarray['item_flags'] = $datarray['item_flags'] | ITEM_OBSCURED;
		if($datarray['title'])
			$datarray['title'] = json_encode(crypto_encapsulate($datarray['title'],$key));
		if($datarray['body'])
			$datarray['body']  = json_encode(crypto_encapsulate($datarray['body'],$key));
	}

	if($orig_post) {
		$datarray['id'] = $post_id;

		item_store_update($datarray,$execflag);

		update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remote_id,$mid);

		if(! $parent) {
			$r = q("select * from item where id = %d",
				intval($post_id)
			);
			if($r) {
				xchan_query($r);
				$sync_item = fetch_post_tags($r);
				$rid = q("select * from item_id where iid = %d",
					intval($post_id)
				);
				build_sync_packet($uid,array('item' => array(encode_item($sync_item[0],true)),'item_id' => $rid));
			}
		}
		if(! $nopush)
			proc_run('php', "include/notifier.php", 'edit_post', $post_id);

		if((x($_REQUEST,'return')) && strlen($return_path)) {
			logger('return: ' . $return_path);
			goaway($a->get_baseurl() . "/" . $return_path );
		}
		killme();
	}
	else
		$post_id = 0;

	$post = item_store($datarray,$execflag);

	$post_id = $post['item_id'];

	if($post_id) {
		logger('mod_item: saved item ' . $post_id);

		if($parent) {

			// only send comment notification if this is a wall-to-wall comment,
			// otherwise it will happen during delivery

			if(($datarray['owner_xchan'] != $datarray['author_xchan']) && ($parent_item['item_flags'] & ITEM_WALL)) {
				notification(array(
					'type'         => NOTIFY_COMMENT,
					'from_xchan'   => $datarray['author_xchan'],
					'to_xchan'     => $datarray['owner_xchan'],
					'item'         => $datarray,
					'link'		   => $a->get_baseurl() . '/display/' . $datarray['mid'],
					'verb'         => ACTIVITY_POST,
					'otype'        => 'item',
					'parent'       => $parent,
					'parent_mid'   => $parent_item['mid']
				));

			}
		}
		else {
			$parent = $post_id;

			if($datarray['owner_xchan'] != $datarray['author_xchan']) {
				notification(array(
					'type'         => NOTIFY_WALL,
					'from_xchan'   => $datarray['author_xchan'],
					'to_xchan'     => $datarray['owner_xchan'],
					'item'         => $datarray,
					'link'		   => $a->get_baseurl() . '/display/' . $datarray['mid'],
					'verb'         => ACTIVITY_POST,
					'otype'        => 'item'
				));
			}

			if($uid && $uid == $profile_uid && (! $datarray['item_restrict'])) {
				q("update channel set channel_lastpost = '%s' where channel_id = %d",
					dbesc(datetime_convert()),
					intval($uid)
				);
			}
		}

		// photo comments turn the corresponding item visible to the profile wall
		// This way we don't see every picture in your new photo album posted to your wall at once.
		// They will show up as people comment on them.

		if($parent_item['item_restrict'] & ITEM_HIDDEN) {
			$r = q("UPDATE `item` SET `item_restrict` = %d WHERE `id` = %d",
				intval($parent_item['item_restrict'] - ITEM_HIDDEN),
				intval($parent_item['id'])
			);
		}
	}
	else {
		logger('mod_item: unable to retrieve post that was just stored.');
		notice( t('System error. Post not saved.') . EOL);
		goaway($a->get_baseurl() . "/" . $return_path );
		// NOTREACHED
	}

	update_remote_id($channel,$post_id,$webpage,$pagetitle,$namespace,$remote_id,$mid);

	if(($parent) && ($parent != $post_id)) {
		// Store the comment signature information in case we need to relay to Diaspora
		$ditem = $datarray;
		$ditem['author'] = $observer;
		store_diaspora_comment_sig($ditem,$channel,$parent_item, $post_id, (($walltowall_comment) ? 1 : 0));
	}
	else {
		$r = q("select * from item where id = %d",
			intval($post_id)
		);
		if($r) {
			xchan_query($r);
			$sync_item = fetch_post_tags($r);
			$rid = q("select * from item_id where iid = %d",
				intval($post_id)
			);
			build_sync_packet($uid,array('item' => array(encode_item($sync_item[0],true)),'item_id' => $rid));
		}
	}

	$datarray['id']    = $post_id;
	$datarray['llink'] = $a->get_baseurl() . '/display/' . $channel['channel_address'] . '/' . $post_id;

	call_hooks('post_local_end', $datarray);

	if(! $nopush)
		proc_run('php', 'include/notifier.php', $notify_type, $post_id);

	logger('post_complete');

	// figure out how to return, depending on from whence we came

	if($api_source)
		return $post;

	if($return_path) {
		goaway($a->get_baseurl() . "/" . $return_path);
	}

	$json = array('success' => 1);
	if(x($_REQUEST,'jsreload') && strlen($_REQUEST['jsreload']))
		$json['reload'] = $a->get_baseurl() . '/' . $_REQUEST['jsreload'];

	logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);

	echo json_encode($json);
	killme();
	// NOTREACHED
}

function item_content(&$a) {

	if((! local_user()) && (! remote_channel()))
		return;

	require_once('include/security.php');

	if((argc() == 3) && (argv(1) === 'drop') && intval(argv(2))) {

		require_once('include/items.php');
		$i = q("select id, uid, author_xchan, owner_xchan, source_xchan, item_restrict from item where id = %d limit 1",
			intval(argv(2))
		);

		if($i) {
			$can_delete = false;
			$local_delete = false;
			if(local_user() && local_user() == $i[0]['uid'])
				$local_delete = true;

			$sys = get_sys_channel();
			if(is_site_admin() && $sys['channel_id'] == $i[0]['uid'])
				$can_delete = true;

			$ob_hash = get_observer_hash();
			if($ob_hash && ($ob_hash === $i[0]['author_xchan'] || $ob_hash === $i[0]['owner_xchan'] || $ob_hash === $i[0]['source_xchan']))
				$can_delete = true;

			if(! ($can_delete || $local_delete)) {
				notice( t('Permission denied.') . EOL);
				return;
			}

			// if this is a different page type or it's just a local delete
			// but not by the item author or owner, do a simple deletion

			if($i[0]['item_restrict'] || ($local_delete && (! $can_delete))) {
				drop_item($i[0]['id']);
			}
			else {
				// complex deletion that needs to propagate and be performed in phases
				drop_item($i[0]['id'],true,DROPITEM_PHASE1);
				tag_deliver($i[0]['uid'],$i[0]['id']);
			}
		}
	}
}

function fix_attached_photo_permissions($uid,$xchan_hash,$body,
		$str_contact_allow,$str_group_allow,$str_contact_deny,$str_group_deny) {

	if(get_pconfig($uid,'system','force_public_uploads')) {
		$str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
	}

	$match = null;
	// match img and zmg image links
	if(preg_match_all("/\[[zi]mg(.*?)\](.*?)\[\/[zi]mg\]/",$body,$match)) {
		$images = $match[2];
		if($images) {
			foreach($images as $image) {
				if(! stristr($image,get_app()->get_baseurl() . '/photo/'))
					continue;
				$image_uri = substr($image,strrpos($image,'/') + 1);
				if(strpos($image_uri,'-') !== false)
					$image_uri = substr($image_uri,0, strpos($image_uri,'-'));
				if(strpos($image_uri,'.') !== false)
					$image_uri = substr($image_uri,0, strpos($image_uri,'.'));
				if(! strlen($image_uri))
					continue;
				$srch = '<' . $xchan_hash . '>';

				$r = q("SELECT id FROM photo
					WHERE allow_cid = '%s' AND allow_gid = '' AND deny_cid = '' AND deny_gid = ''
					AND resource_id = '%s' AND uid = %d LIMIT 1",
					dbesc($srch),
					dbesc($image_uri),
					intval($uid)
				);

				if($r) {
					$r = q("UPDATE photo SET allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s'
						WHERE resource_id = '%s' AND uid = %d ",
						dbesc($str_contact_allow),
						dbesc($str_group_allow),
						dbesc($str_contact_deny),
						dbesc($str_group_deny),
						dbesc($image_uri),
						intval($uid)
					);

					// also update the linked item (which is probably invisible)

					$r = q("select id from item
						WHERE allow_cid = '%s' AND allow_gid = '' AND deny_cid = '' AND deny_gid = ''
						AND resource_id = '%s' and resource_type = 'photo' AND uid = %d LIMIT 1",
						dbesc($srch),
						dbesc($image_uri),
						intval($uid)
					);
					if($r) {
						$private = (($str_contact_allow || $str_group_allow || $str_contact_deny || $str_group_deny) ? true : false);

						$r = q("UPDATE item SET allow_cid = '%s', allow_gid = '%s', deny_cid = '%s', deny_gid = '%s', item_private = %d
							WHERE id = %d AND uid = %d",
							dbesc($str_contact_allow),
							dbesc($str_group_allow),
							dbesc($str_contact_deny),
							dbesc($str_group_deny),
							intval($private),
							intval($r[0]['id']),
							intval($uid)
						);
					}
				}
			}
		}
	}
}

function fix_attached_file_permissions($channel,$observer_hash,$body,
		$str_contact_allow,$str_group_allow,$str_contact_deny,$str_group_deny) {

	if(get_pconfig($channel['channel_id'],'system','force_public_uploads')) {
		$str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = '';
	}

	$match = false;

	if(preg_match_all("/\[attachment\](.*?)\[\/attachment\]/",$body,$match)) {
		$attaches = $match[1];
		if($attaches) {
			foreach($attaches as $attach) {
				$hash = substr($attach,0,strpos($attach,','));
				$rev = intval(substr($attach,strpos($attach,',')));
				attach_store($channel,$observer_hash,$options = 'update', array(
					'hash'      => $hash,
					'revision'  => $rev,
					'allow_cid' => $str_contact_allow,
					'allow_gid'  => $str_group_allow,
					'deny_cid'  => $str_contact_deny,
					'deny_gid'  => $str_group_deny
				));
			}
		}
	}
}

function item_check_service_class($channel_id,$iswebpage) {
	$ret = array('success' => false, 'message' => '');

	if ($iswebpage) {
		// note: we aren't counting comanche templates and blocks, only webpages
		$r = q("select count(id) as total from item where parent = id
			and ( item_restrict & %d ) > 0 and ( item_restrict & %d ) = 0 and uid = %d ",
			intval(ITEM_WEBPAGE),
			intval(ITEM_DELETED),
			intval($channel_id)
		);
	}
	else {
		$r = q("select count(id) as total from item where parent = id and item_restrict = 0 and (item_flags & %d) > 0 and uid = %d ",
			intval(ITEM_WALL),
			intval($channel_id)
		);
	}

	if(! $r) {
		$ret['message'] = t('Unable to obtain post information from database.');
		return $ret;
	}

	if (!$iswebpage) {
		$max = service_class_fetch($channel_id,'total_items');
		if(! service_class_allows($channel_id,'total_items',$r[0]['total'])) {
			$result['message'] .= upgrade_message() . sprintf( t('You have reached your limit of %1$.0f top level posts.'),$max);
			return $result;
		}
	}
	else {
		$max = service_class_fetch($channel_id,'total_pages');
		if(! service_class_allows($channel_id,'total_pages',$r[0]['total'])) {
			$result['message'] .= upgrade_message() . sprintf( t('You have reached your limit of %1$.0f webpages.'),$max);
			return $result;
		}
	}

	$ret['success'] = true;
	return $ret;
}