text:
package jetbrains.buildServer.clouds.kubernetes;

import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClientException;
import java.util.concurrent.ConcurrentMap;
import jetbrains.buildServer.clouds.CloudErrorInfo;
import jetbrains.buildServer.clouds.CloudInstance;
import jetbrains.buildServer.clouds.CloudInstanceUserData;
import jetbrains.buildServer.clouds.kubernetes.connector.ImagePullPolicy;
import jetbrains.buildServer.clouds.kubernetes.connector.KubeApiConnector;
import jetbrains.buildServer.clouds.kubernetes.podSpec.BuildAgentPodTemplateProvider;
import jetbrains.buildServer.clouds.kubernetes.podSpec.BuildAgentPodTemplateProviders;
import jetbrains.buildServer.clouds.kubernetes.podSpec.DeploymentBuildAgentPodTemplateProvider;
import jetbrains.buildServer.clouds.kubernetes.podSpec.SimpleRunContainerProvider;
import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ekoshkin (koshkinev@gmail.com) on 07.06.17.
 */
public class KubeCloudImageImpl implements KubeCloudImage {
    private final KubeApiConnector myApiConnector;
    private final KubeCloudImageData myImageData;
    private final KubeDataCache myCache;
    private final BuildAgentPodTemplateProviders myPodTemplateProviders;

    private final ConcurrentMap<String, KubeCloudInstance> myIdToInstanceMap = new ConcurrentHashMap<>();
    private CloudErrorInfo myCurrentError;

    KubeCloudImageImpl(@NotNull final KubeCloudImageData kubeCloudImageData,
                       @NotNull final KubeApiConnector apiConnector,
                       @NotNull final KubeDataCache cache,
                       @NotNull final BuildAgentPodTemplateProviders podTemplateProviders) {
        myImageData = kubeCloudImageData;
        myApiConnector = apiConnector;
        myCache = cache;
        myPodTemplateProviders = podTemplateProviders;
    }

    @NotNull
    @Override
    public String getPodSpecMode() {
        return myImageData.getPodSpecMode();
    }

    @Nullable
    @Override
    public String getCustomPodTemplateSpec() {
        return myImageData.getCustomPodTemplateContent();
    }

    @Nullable
    @Override
    public String getSourceDeploymentName() {
        return myImageData.getDeploymentName();
    }

    @Override
    public int getRunningInstanceCount() {
        return (int) myIdToInstanceMap.values().stream().filter(kubeCloudInstance -> kubeCloudInstance.getStatus().isStartingOrStarted()).count();
    }

    @Override
    public int getInstanceLimit() {
        return myImageData.getInstanceLimit();
    }

    @NotNull
    @Override
    public String getAgentName(@NotNull String instanceName) {
        final String agentNamePrefix = myImageData.getAgentNamePrefix();
        return StringUtil.isEmpty(agentNamePrefix) ? instanceName : agentNamePrefix + instanceName;
    }

    @Nullable
    @Override
    public String getAgentNamePrefix() {
        return myImageData.getAgentNamePrefix();
    }

    @NotNull
    @Override
    public CloudInstance startNewInstance(@NotNull CloudInstanceUserData instanceUserData, @NotNull KubeCloudClientParametersImpl clientParams) {
        final KubeCloudInstance newInstance;
        BuildAgentPodTemplateProvider podTemplateProvider = myPodTemplateProviders.get(getPodSpecMode());
        try {
            final Pod podTemplate = podTemplateProvider.getPodTemplate(instanceUserData, this, clientParams);
            final Pod newPod = myApiConnector.createPod(podTemplate);
            myCurrentError = null;
            newInstance = new CachingKubeCloudInstance(new KubeCloudInstanceImpl(this, newPod, myApiConnector), myCache);
        } catch (KubeCloudException | KubernetesClientException ex){
            myCurrentError = new CloudErrorInfo("Failed to start pod", ex.getMessage(), ex);
            throw ex;
        }
        populateInstances();
        return newInstance;
    }

    @Override
    public void setErrorInfo(@Nullable final CloudErrorInfo errorInfo) {
        myCurrentError = errorInfo;
    }

    @Nullable
    @Override
    public String getDockerImage() {
        return myImageData.getDockerImage();
    }

    @Nullable
    @Override
    public ImagePullPolicy getImagePullPolicy() {
        return myImageData.getImagePullPolicy();
    }

    @Nullable
    @Override
    public String getDockerArguments() {
        return myImageData.getDockerArguments();
    }

    @Nullable
    @Override
    public String getDockerCommand() {
        return myImageData.getDockerCommand();
    }

    @NotNull
    @Override
    public String getId() {
        return myImageData.getId();
    }

    @NotNull
    @Override
    public String getName() {
        switch (getPodSpecMode()){
            case SimpleRunContainerProvider.ID:
                return "Docker Image: " + getDockerImage();
            case DeploymentBuildAgentPodTemplateProvider.ID:
                return "Deployment: " + getSourceDeploymentName();
            default:
                return "Custom template: " + getAgentNamePrefix();
        }
    }

    @NotNull
    @Override
    public Collection<? extends CloudInstance> getInstances() {
        return myIdToInstanceMap.values();
    }

    @Nullable
    @Override
    public CloudInstance findInstanceById(@NotNull String id) {
        return myIdToInstanceMap.get(id);
    }

    @Nullable
    @Override
    public Integer getAgentPoolId() {
        return myImageData.getAgentPoolId();
    }

    @Nullable
    @Override
    public CloudErrorInfo getErrorInfo() {
        return myCurrentError;
    }

    //TODO: syncronize access to myIdToInstanceMap
    //TODO: filter pods more carefully using all setted labels
    public void populateInstances(){
        try{
            final Collection<Pod> pods = myApiConnector.listPods(CollectionsUtil.asMap(
              KubeTeamCityLabels.TEAMCITY_CLOUD_IMAGE, myImageData.getId(),
              KubeTeamCityLabels.TEAMCITY_CLOUD_PROFILE, myImageData.getProfileId()
                                                                 ));
            myIdToInstanceMap.clear();
            myCache.invalidate();
            for (Pod pod : pods){
                KubeCloudInstance cloudInstance = new CachingKubeCloudInstance(new KubeCloudInstanceImpl(this, pod, myApiConnector), myCache);
                String instanceId = cloudInstance.getInstanceId();
                myIdToInstanceMap.put(instanceId, cloudInstance);
            }
            myCurrentError = null;
        } catch (KubernetesClientException ex){
            myCurrentError = new CloudErrorInfo("Failed populate instances", ex.getMessage(), ex);
            throw ex;
        }
    }
}


text:
@class FLStackTrace;

@interface FLLogEntry : NSObject<NSCopying> {
@private
    NSString* _logString;
    NSString* _logType;
    NSString* _logName;
    uint32_t _logCount;
    NSTimeInterval _timestamp;
    FLStackTrace* _stackTrace;
    id _object;
}

+ (id) logEntry;

@property (readwrite, strong, nonatomic) id object;
@property (readwrite, strong, nonatomic) NSString* logString;
@property (readwrite, strong, nonatomic) NSString* logType;
@property (readonly, strong, nonatomic) NSString* logName;
@property (readwrite, strong, nonatomic) FLStackTrace* stackTrace;
@property (readonly, assign, nonatomic) uint32_t logCount;
@property (readonly, assign, nonatomic) NSTimeInterval timestamp;

- (void) releaseToCache;

@end

@interface NSObject (FLLogging)
- (NSString*) moreDescriptionForLogging;
- (FLLogEntry*) logEntryForSelf;
@end

@interface NSError (FLLogging)
@end

@interface NSException (FLLogging)
@end

redpajama_set_name: RedPajamaGithub


text:
<?php
declare(strict_types=1);

namespace Zelenin\HttpClient\Test;

use PHPUnit\Framework\TestCase;
use Zelenin\HttpClient\MiddlewareClient;
use Zelenin\HttpClient\RequestConfig;
use Zelenin\HttpClient\Transport\StreamTransport;
use Zend\Diactoros\Request;
use Zend\Diactoros\ResponseFactory;
use Zend\Diactoros\StreamFactory;
use Zend\Diactoros\Uri;

final class MiddlewareClientTest extends TestCase
{
    public function testResponse()
    {
        $streamFactory = new StreamFactory();
        $responseFactory = new ResponseFactory();

        $client = new MiddlewareClient([
            new StreamTransport($streamFactory, $responseFactory, new RequestConfig()),
        ], $responseFactory);

        $request = new Request(new Uri('https://example.com/'), 'GET');
        $response = $client->sendRequest($request);

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals(['text/html; charset=UTF-8'], $response->getHeader('Content-type'));
        $this->assertContains('Example Domain', $response->getBody()->getContents());
    }
}


text:
Meteor Autoform Materialize templates
=========================

Adds [materialize](http://materializecss.com/) templates for autoform.

**This is a work in progress: I'll update this package**

## Setup

1. `meteor add gildaspk:autoform-materialize`
2. In a client file (ex: `/client/config/autoform.js`)
  ```
  AutoForm.setDefaultTemplate('materialize');
  ```

You must add materialize CSS and JavaScript yourself. Some packages can help:

- [materialize:materialize](https://atmospherejs.com/materialize/materialize) `meteor add materialize:materialize`
- [d0minikk:materialize-meteor](https://atmospherejs.com/d0minikk/materialize-meteor) `meteor add d0minikk:materialize-meteor`
- [grigio:materialize-sass](https://atmospherejs.com/grigio/materialize-sass) `meteor add grigio:materialize-sass`
  Note this one doesn't add the scripts but allows you to customize the CSS with SASS
- [yang2007chun:materialize-scss](https://atmospherejs.com/yang2007chun/materialize-scss) `meteor add yang2007chun:materialize-scss`
  Note this one allows you to customize with SASS

## Additional type

### PickADate
Materialize uses [pickadate](https://github.com/amsul/pickadate.js) for date inputs.

You can apply it directly in your template:

```
{{> afFieldInput name='dateFieldName' type="pickadate"}}
```

You can also specify it at the schema level:
```
MySchema = new SimpleSchema({
  dateFieldName: {
    type: Date
    autoform: {
      type:"pickadate"
    }
  }
});
```
#### Choosing a Timezone

By default, the field's value will be a `Date` object representing the selected date and time in the browser's timezone (i.e., based on the user's computer time settings). In most cases, you probably want the `Date` object relative to some other timezone that you have previously stored. For example, if the form is setting the start date of an event, you want the date to be relative to the event venue's timezone. You can specify a different IANA timezone ID by adding a `timezoneId` attribute.

```js
{
  date: {
    type: Date,
    autoform: {
      type: "pickadate",
      timezoneId: "America/New_York"
    }
  }
}
```

Or:

```js
{{> afFieldInput name="typeTest" type="pickadate" timezoneId="America/New_York"}}
```

#### Automatic Type Conversions

This input type is intended to be used with `type: Date` schema keys, but it also works with other schema types. Here's a list:

* `Date`: Value is stored as a `Date` object representing the selected date and time in the timezone you specified with the `timezoneId` attribute. By default, the timezone is that of the browser (i.e., the user's computer time settings).
* `String`: Value is stored as a string representation of the selected date in ISO format, e.g., "2014-11-25T00:00:00".
* `Number`: Value is stored as the result of calling `getTime()` on the `Date` object (representing the selected date and time in the timezone you specified).
* `Array`: If the schema expects an array of `Date` or `String` or `Number`, the value is converted to a one-item array and stored.

To provide pickadate options, set a `pickadateOptions` attribute equal to a helper that returns the options object.

### Switch

You an also use [switches](http://materializecss.com/forms.html#switches)

At the template level:
```
{{> afFieldInput name='dateFieldName' type="switch"}}
```

At the schema level:
```
MySchema = new SimpleSchema({
  booleanFieldName: {
    type: Boolean
    autoform: {
      type:"switch"
    }
  }
});
```

You may specify the `trueLabel` or `falseLabel` options to customize the switch.

At the template level:
```
{{> afFieldInput name='dateFieldName' type="switch" trueLabel="Online" falseLabel="Offline"}}
```

At the schema level:
```
MySchema = new SimpleSchema({
  booleanFieldName: {
    type: Boolean
    autoform: {
      type:"switch"
      trueLabel:"Online"
      falseLabel:"Offline"
    }
  }
});
```
If you need other values than boolean, you may specify the `trueValue` or `falseValue` options to customize the switch.

At the template level:
```
{{> afFieldInput name='dateFieldName' type="switch" trueValue="online" falseValue="offline"}}
```

At the schema level:
```
MySchema = new SimpleSchema({
  booleanFieldName: {
    type: Boolean
    autoform: {
      type:"switch"
      trueValue:"online"
      falseValue:"offline"
    }
  }
});
```
## Contributors
- Gildas Garcia (@djhi)
- Razvan Teslaru (@rteslaru)

## License
autoform-materialize is licensed under the [MIT Licence](LICENSE), courtesy of [marmelab](http://marmelab.com).


text:
Primitives
==========

.. autoclass:: async_v20.AcceptDatetimeFormat
.. autoclass:: async_v20.AccountFinancingMode
.. autoclass:: async_v20.AccountID
.. autoclass:: async_v20.AccountUnits
.. autoclass:: async_v20.CancellableOrderType
.. autoclass:: async_v20.CandlestickGranularity
.. autoclass:: async_v20.ClientComment
.. autoclass:: async_v20.ClientID
.. autoclass:: async_v20.ClientTag
.. autoclass:: async_v20.Currency
.. autoclass:: async_v20.DateTime
.. autoclass:: async_v20.DecimalNumber
.. autoclass:: async_v20.Direction
.. autoclass:: async_v20.FundingReason
.. autoclass:: async_v20.InstrumentName
.. autoclass:: async_v20.InstrumentType
.. autoclass:: async_v20.LimitOrderReason
.. autoclass:: async_v20.MarketIfTouchedOrderReason
.. autoclass:: async_v20.MarketOrderMarginCloseoutReason
.. autoclass:: async_v20.MarketOrderReason
.. autoclass:: async_v20.OrderCancelReason
.. autoclass:: async_v20.OrderFillReason
.. autoclass:: async_v20.OrderID
.. autoclass:: async_v20.OrderPositionFill
.. autoclass:: async_v20.OrderSpecifier
.. autoclass:: async_v20.OrderState
.. autoclass:: async_v20.OrderStateFilter
.. autoclass:: async_v20.OrderTriggerCondition
.. autoclass:: async_v20.OrderType
.. autoclass:: async_v20.PositionAggregationMode
.. autoclass:: async_v20.PriceComponent
.. autoclass:: async_v20.PriceStatus
.. autoclass:: async_v20.PriceValue
.. autoclass:: async_v20.Reason
.. autoclass:: async_v20.RequestID
.. autoclass:: async_v20.StopLossOrderReason
.. autoclass:: async_v20.StopOrderReason
.. autoclass:: async_v20.TakeProfitOrderReason
.. autoclass:: async_v20.TimeInForce
.. autoclass:: async_v20.TradeID
.. autoclass:: async_v20.TradePL
.. autoclass:: async_v20.TradeSpecifier
.. autoclass:: async_v20.TradeState
.. autoclass:: async_v20.TradeStateFilter
.. autoclass:: async_v20.TrailingStopLossOrderReason
.. autoclass:: async_v20.TransactionFilter
.. autoclass:: async_v20.TransactionID
.. autoclass:: async_v20.TransactionRejectReason
.. autoclass:: async_v20.TransactionType
.. autoclass:: async_v20.WeeklyAlignment


text:
<?php

namespace Miny\Test\HTTP;

use Miny\HTTP\ResponseHeaders;

class ResponseHeadersTest extends \PHPUnit_Framework_TestCase
{

    public function testCookies()
    {
        $sender = $this->getMockForAbstractClass('\\Miny\\HTTP\\AbstractHeaderSender');

        $headers = new ResponseHeaders($sender);
        $headers->setCookie('name', 'value');
        $headers->setCookie('foo', 'bar');

        $this->assertContains('value', $headers->getCookies());
        $this->assertContains('bar', $headers->getCookies());

        $headers->removeCookie('foo');

        $this->assertContains('value', $headers->getCookies());
        $this->assertNotContains('bar', $headers->getCookies());
    }

    public function testSend()
    {
        $sender = $this->getMockForAbstractClass('\\Miny\\HTTP\\AbstractHeaderSender');

        $sender->expects($this->at(0))
            ->method('send')
            ->with($this->equalTo('expect: foo, bar'));

        $sender->expects($this->at(1))
            ->method('send')
            ->with($this->equalTo('Foobar'));

        $sender->expects($this->once())
            ->method('sendCookie')
            ->with($this->equalTo('name'), $this->equalTo('value'));

        $headers = new ResponseHeaders($sender);
        $headers->set('Expect', 'foo');
        $headers->set('Expect', 'bar');
        $headers->setCookie('name', 'value');
        $headers->setRaw('Foobar');
        $headers->send();
    }
}


text:
#pragma once

#include "gnss_messages_common.h"

namespace mrpt::obs::gnss
{
// Pragma to ensure we can safely serialize some of these structures
#pragma pack(push, 1)

/** Novatel OEM6 regular header structure \sa mrpt::obs::CObservationGPS  */
struct nv_oem6_header_t
{
	enum : uint8_t
	{
		SYNCH0 = 0xAA,
		SYNCH1 = 0X44,
		SYNCH2 = 0x12
	};

	uint8_t synch[3]{0, 0, 0};
	uint8_t hdr_len{0};
	uint16_t msg_id{0};
	uint8_t msg_type{0};
	uint8_t port_addr{0};
	uint16_t msg_len{0};
	uint16_t seq_number{0};
	uint8_t idle_percent{0};
	uint8_t time_status{0};
	uint16_t week{0};
	uint32_t ms_in_week{0};
	uint32_t receiver_status{0};
	uint16_t reserved{0};
	uint16_t receiver_sw_version{0};

	void fixEndianness()
	{
#if MRPT_IS_BIG_ENDIAN
		mrpt::reverseBytesInPlace(msg_id);
		mrpt::reverseBytesInPlace(msg_len);
		mrpt::reverseBytesInPlace(seq_number);
		mrpt::reverseBytesInPlace(week);
		mrpt::reverseBytesInPlace(ms_in_week);
		mrpt::reverseBytesInPlace(receiver_status);
		mrpt::reverseBytesInPlace(reserved);
		mrpt::reverseBytesInPlace(receiver_sw_version);
#endif
	}
};

/** Novatel OEM6 short header structure \sa mrpt::obs::CObservationGPS  */
struct nv_oem6_short_header_t
{
	enum : uint8_t
	{
		SYNCH0 = 0xAA,
		SYNCH1 = 0X44,
		SYNCH2 = 0x13
	};
	uint8_t synch[3]{0, 0, 0};
	uint8_t msg_len{0};
	uint16_t msg_id{0};
	uint16_t week{0};
	uint32_t ms_in_week{0};

	void fixEndianness()
	{
#if MRPT_IS_BIG_ENDIAN
		mrpt::reverseBytesInPlace(msg_id);
		mrpt::reverseBytesInPlace(msg_len);
		mrpt::reverseBytesInPlace(week);
		mrpt::reverseBytesInPlace(ms_in_week);
#endif
	}
};

namespace nv_oem6_position_type
{
/** Novatel OEM6 firmware reference, table 84; Novatel SPAN on OEM6 firmware
 * manual, table 26. */
enum nv_position_type_t : uint32_t
{
	NONE = 0,
	FIXEDPOS = 1,
	FIXEDHEIGHT = 2,
	Reserved = 3,
	FLOATCONV = 4,
	WIDELANE = 5,
	NARROWLANE = 6,
	DOPPLER_VELOCITY = 8,
	SINGLE = 16,
	PSRDIFF = 17,
	WAAS = 18,
	PROPAGATED = 19,
	OMNISTAR = 20,
	L1_FLOAT = 32,
	IONOFREE_FLOAT = 33,
	NARROW_FLOAT = 34,
	L1_INT = 48,
	WIDE_INT = 49,
	NARROW_INT = 50,
	RTK_DIRECT_INS = 51,
	INS = 52,
	INS_PSRSP = 53,
	INS_PSRDIFF = 54,
	INS_RTKFLOAT = 55,
	INS_RTKFIXED = 56,
	OMNISTAR_HP = 64,
	OMNISTAR_XP = 65,
	CDGPS = 66
};
/** for nv_position_type_t */
const std::string& enum2str(int val);
}  // namespace nv_oem6_position_type

namespace nv_oem6_solution_status
{
/** Novatel OEM6 firmware reference, table 85 */
enum nv_solution_status_t : uint32_t
{
	/** solution computed */
	SOL_COMPUTED = 0,
	/** insufficient observations */
	INSUFFICIENT_OBS,
	/** noconvergence */
	NO_CONVERGENCE,
	/** singularity at parameters matrix */
	SINGULARITY,
	/** covariance trace exceeds maximum (trace>1000m) */
	COV_TRACE,
	/** test distance exceeded (max of 3 rejections if distance > 10km) */
	TEST_DIST,
	/** not yet converged from cold start */
	COLD_START,
	/** height or velocity limits exceeded */
	V_H_LIMIT,
	/** variance exceeds limits */
	VARIANCE,
	/** residuals are too large */
	RESIDUALS,
	/** delta position is too large */
	DELTA_POS,
	/** negative variance */
	NEGATIVE_VAR,
	/** large residuals make position unreliable */
	INTEGRITY_WARNING = 13,
	/** ins has not started yet */
	INS_INACTIVE,
	/** ins doing its coarse alignment */
	INS_ALIGNING,
	/** ins position is bad */
	INS_BAD,
	/** no imu detected */
	IMU_UNPLUGGED,
	/** when a fix position command is entered, the receiver computes its own
	   position and determines if the fixed position is valid */
	PENDING = 18,
	/** the fixed position entered using the fix position command is not valid
	 */
	INVALID_FIX
};
/** for nv_solution_status_t */
const std::string& enum2str(int val);
}  // namespace nv_oem6_solution_status
namespace nv_oem6_ins_status_type
{
/** Novatel SPAN on OEM6 firmware reference, table 33 */
enum nv_ins_status_type_t : uint32_t
{
	INS_INACTIVE = 0,  // IMU logs are present, but the alignment routine has
	// not started; INS is inactive.
	INS_ALIGNING = 1,  // INS is in alignment mode.
	INS_HIGH_VARIANCE = 2,	// The INS solution is in navigation mode but the
	// azimuth solution uncertainty has exceeded the
	// threshold.
	INS_SOLUTION_GOOD = 3,	// The INS filter is in navigation mode and the INS
	// solution is good.
	INS_SOLUTION_FREE = 6,	// The INS filter is in navigation mode and the GNSS
	// solution is suspected to be in error.
	INS_ALIGNMENT_COMPLETE = 7,	 // The INS filter is in navigation mode, but
	// not enough vehicle dynamics have been
	// experienced for the system to be within
	// specifications.
	DETERMINING_ORIENTATION =
		8,	// INS is determining the IMU axis aligned with gravity.
	WAITING_INITIALPOS = 9	// The INS filter has determined the IMU orientation
	// and is awaiting an initial position estimate to
	// begin the alignment process.
};
/** for nv_ins_status_type_t */
const std::string& enum2str(int val);
}  // namespace nv_oem6_ins_status_type

/** Novatel generic frame (to store frames without a parser at the present
 * time). \sa mrpt::obs::CObservationGPS  */
struct Message_NV_OEM6_GENERIC_FRAME : public gnss_message
{
	Message_NV_OEM6_GENERIC_FRAME()
		: gnss_message((gnss_message_type_t)NV_OEM6_GENERIC_FRAME)
	{
	}
	/** Frame header */
	nv_oem6_header_t header;
	std::vector<uint8_t> msg_body;

	void fixEndianness() override { header.fixEndianness(); }

	void dumpToStream(std::ostream& out) const override;  // See docs in base
   protected:
	void internal_writeToStream(
		mrpt::serialization::CArchive& out) const override;
	void internal_readFromStream(mrpt::serialization::CArchive& in) override;
};

/** Novatel generic short-header frame (to store frames without a parser at the
 * present time). \sa mrpt::obs::CObservationGPS  */
struct Message_NV_OEM6_GENERIC_SHORT_FRAME : public gnss_message
{
	Message_NV_OEM6_GENERIC_SHORT_FRAME()
		: gnss_message((gnss_message_type_t)NV_OEM6_GENERIC_SHORT_FRAME)
	{
	}
	/** Frame header */
	nv_oem6_short_header_t header;
	std::vector<uint8_t> msg_body;

	void fixEndianness() override { header.fixEndianness(); }

	void dumpToStream(std::ostream& out) const override;  // See docs in base
   protected:
	void internal_writeToStream(
		mrpt::serialization::CArchive& out) const override;
	void internal_readFromStream(mrpt::serialization::CArchive& in) override;
};

/** Novatel frame: NV_OEM6_BESTPOS. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_BESTPOS)
/** Frame header */
nv_oem6_header_t header;
nv_oem6_solution_status::nv_solution_status_t solution_stat =
	nv_oem6_solution_status::INVALID_FIX;
nv_oem6_position_type::nv_position_type_t position_type =
	nv_oem6_position_type::NONE;
/** [deg], [deg], hgt over sea level[m] */
double lat = 0, lon = 0, hgt = 0;
float undulation = 0;
uint32_t datum_id = 0;
/** Uncertainties (all in [m]) */
float lat_sigma = 0, lon_sigma = 0, hgt_sigma = 0;
char base_station_id[4]{0, 0, 0, 0};
float diff_age = 0, sol_age = 0;
uint8_t num_sats_tracked = 0, num_sats_sol = 0, num_sats_sol_L1 = 0,
		num_sats_sol_multi = 0;
uint8_t reserved = 0;
uint8_t ext_sol_stat = 0;
uint8_t galileo_beidou_mask = 0;
uint8_t gps_glonass_mask = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
/**  Return the geodetic coords as a mrpt::topography::TGeodeticCoords structure
 * (requires linking against mrpt-topography)
 *   Call as: getAsStruct<TGeodeticCoords>(); */
template <class TGEODETICCOORDS>
inline TGEODETICCOORDS getAsStruct() const
{
	return TGEODETICCOORDS(fields.lat, fields.lon, fields.hgt);
}
bool getAllFieldDescriptions(std::ostream& o) const override;
bool getAllFieldValues(std::ostream& o) const override;
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace_enum(fields.solution_stat);
	mrpt::reverseBytesInPlace_enum(fields.position_type);
	mrpt::reverseBytesInPlace(fields.lat);
	mrpt::reverseBytesInPlace(fields.lon);
	mrpt::reverseBytesInPlace(fields.hgt);
	mrpt::reverseBytesInPlace(fields.undulation);
	mrpt::reverseBytesInPlace(fields.datum_id);
	mrpt::reverseBytesInPlace(fields.lat_sigma);
	mrpt::reverseBytesInPlace(fields.lon_sigma);
	mrpt::reverseBytesInPlace(fields.hgt_sigma);
	mrpt::reverseBytesInPlace(fields.diff_age);
	mrpt::reverseBytesInPlace(fields.sol_age);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_INSPVAS. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_INSPVAS)
/** Frame header */
nv_oem6_short_header_t header;
uint32_t week = 0;
double seconds_in_week = 0;
double lat = 0, lon = 0, hgt = 0;
double vel_north = 0, vel_east = 0, vel_up = 0;
double roll = 0, pitch = 0, azimuth = 0;
nv_oem6_ins_status_type::nv_ins_status_type_t ins_status =
	nv_oem6_ins_status_type::INS_INACTIVE;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
/**  Return the geodetic coords as a mrpt::topography::TGeodeticCoords structure
 * (requires linking against mrpt-topography)
 *   Call as: getAsStruct<TGeodeticCoords>(); */
template <class TGEODETICCOORDS>
inline TGEODETICCOORDS getAsStruct() const
{
	return TGEODETICCOORDS(fields.lat, fields.lon, fields.hgt);
}
bool getAllFieldDescriptions(std::ostream& o) const override;
bool getAllFieldValues(std::ostream& o) const override;
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.week);
	mrpt::reverseBytesInPlace(fields.seconds_in_week);
	mrpt::reverseBytesInPlace(fields.lat);
	mrpt::reverseBytesInPlace(fields.lon);
	mrpt::reverseBytesInPlace(fields.hgt);
	mrpt::reverseBytesInPlace(fields.vel_north);
	mrpt::reverseBytesInPlace(fields.vel_east);
	mrpt::reverseBytesInPlace(fields.vel_up);
	mrpt::reverseBytesInPlace(fields.roll);
	mrpt::reverseBytesInPlace(fields.pitch);
	mrpt::reverseBytesInPlace(fields.azimuth);
	mrpt::reverseBytesInPlace_enum(fields.ins_status);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_INSCOVS. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_INSCOVS)
/** Frame header */
nv_oem6_short_header_t header;
uint32_t week = 0;
double seconds_in_week = 0;
/** Position covariance matrix in local level frame (metres squared)
 * xx,xy,xz,yx,yy,yz,zx,zy,zz */
double pos_cov[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
/** Attitude covariance matrix of the SPAN frame to the local level frame.  (deg
 * sq) xx,xy,xz,yx,yy,yz,zx,zy,zz */
double att_cov[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
/** Velocity covariance matrix in local level frame. (metres/second squared)
 * xx,xy,xz,yx,yy,yz,zx,zy,zz */
double vel_cov[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
bool getAllFieldDescriptions(std::ostream& o) const override;
bool getAllFieldValues(std::ostream& o) const override;
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.week);
	mrpt::reverseBytesInPlace(fields.seconds_in_week);
	for (int i = 0; i < 9; i++)
	{
		mrpt::reverseBytesInPlace(fields.pos_cov[i]);
		mrpt::reverseBytesInPlace(fields.att_cov[i]);
		mrpt::reverseBytesInPlace(fields.vel_cov[i]);
	}
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_RANGECMP. \sa mrpt::obs::CObservationGPS  */
struct Message_NV_OEM6_RANGECMP : public gnss_message
{
	Message_NV_OEM6_RANGECMP()
		: gnss_message((gnss_message_type_t)NV_OEM6_RANGECMP)
	{
	}
	struct TCompressedRangeLog
	{
		uint8_t data[24];
	};

	/** Frame header */
	nv_oem6_header_t header;
	uint32_t num_obs{0};
	std::vector<TCompressedRangeLog> obs_data;
	uint32_t crc;

	void dumpToStream(std::ostream& out) const override;  // See docs in base
   protected:
	void internal_writeToStream(
		mrpt::serialization::CArchive& out) const override;
	void internal_readFromStream(mrpt::serialization::CArchive& in) override;
};

/** Novatel frame: NV_OEM6_RXSTATUS. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_RXSTATUS)
/** Frame header */
nv_oem6_header_t header;
uint32_t error = 0, num_stats = 0;
uint32_t rxstat = 0, rxstat_pri = 0, rxstat_set = 0, rxstat_clear = 0;
uint32_t aux1stat = 0, aux1stat_pri = 0, aux1stat_set = 0, aux1stat_clear = 0;
uint32_t aux2stat = 0, aux2stat_pri = 0, aux2stat_set = 0, aux2stat_clear = 0;
uint32_t aux3stat = 0, aux3stat_pri = 0, aux3stat_set = 0, aux3stat_clear = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.error);
	mrpt::reverseBytesInPlace(fields.num_stats);
	mrpt::reverseBytesInPlace(fields.rxstat);
	mrpt::reverseBytesInPlace(fields.rxstat_pri);
	mrpt::reverseBytesInPlace(fields.rxstat_set);
	mrpt::reverseBytesInPlace(fields.rxstat_clear);
	mrpt::reverseBytesInPlace(fields.aux1stat);
	mrpt::reverseBytesInPlace(fields.aux1stat_pri);
	mrpt::reverseBytesInPlace(fields.aux1stat_set);
	mrpt::reverseBytesInPlace(fields.aux1stat_clear);
	mrpt::reverseBytesInPlace(fields.aux2stat);
	mrpt::reverseBytesInPlace(fields.aux2stat_pri);
	mrpt::reverseBytesInPlace(fields.aux2stat_set);
	mrpt::reverseBytesInPlace(fields.aux2stat_clear);
	mrpt::reverseBytesInPlace(fields.aux3stat);
	mrpt::reverseBytesInPlace(fields.aux3stat_pri);
	mrpt::reverseBytesInPlace(fields.aux3stat_set);
	mrpt::reverseBytesInPlace(fields.aux3stat_clear);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_RAWEPHEM. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_RAWEPHEM)
/** Frame header */
nv_oem6_header_t header;
uint32_t sat_prn = 0, ref_week = 0, ref_secs = 0;
uint8_t subframe1[30], subframe2[30], subframe3[30];
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.sat_prn);
	mrpt::reverseBytesInPlace(fields.ref_week);
	mrpt::reverseBytesInPlace(fields.ref_secs);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_VERSION. \sa mrpt::obs::CObservationGPS  */
struct Message_NV_OEM6_VERSION : public gnss_message
{
	Message_NV_OEM6_VERSION()
		: gnss_message(static_cast<gnss_message_type_t>(NV_OEM6_VERSION))
	{
	}
	struct TComponentVersion
	{
		uint32_t type;
		char model[16], serial[16];
		char hwversion[16], swversion[16], bootversion[16];
		char compdate[12], comptime[12];
	};

	/** Frame header */
	nv_oem6_header_t header;
	uint32_t num_comps{0};
	std::vector<TComponentVersion> components;
	uint32_t crc;

	void dumpToStream(std::ostream& out) const override;  // See docs in base
	void fixEndianness() override
	{
#if MRPT_IS_BIG_ENDIAN
		header.fixEndianness();
		for (auto& c : components)
			mrpt::reverseBytesInPlace(c.type);
		mrpt::reverseBytesInPlace(crc);
#endif
	}

   protected:
	void internal_writeToStream(
		mrpt::serialization::CArchive& out) const override;
	void internal_readFromStream(mrpt::serialization::CArchive& in) override;
};

/** Novatel frame: NV_OEM6_RAWIMUS. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_RAWIMUS)
/** Frame header */
nv_oem6_short_header_t header;
uint32_t week = 0;
double week_seconds = 0;
uint32_t imu_status = 0;
int32_t accel_z = 0, accel_y_neg = 0, accel_x = 0;
int32_t gyro_z = 0, gyro_y_neg = 0, gyro_x = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
bool getAllFieldDescriptions(std::ostream& o) const override;
bool getAllFieldValues(std::ostream& o) const override;
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.week);
	mrpt::reverseBytesInPlace(fields.week_seconds);
	mrpt::reverseBytesInPlace(fields.imu_status);
	mrpt::reverseBytesInPlace(fields.accel_z);
	mrpt::reverseBytesInPlace(fields.accel_y_neg);
	mrpt::reverseBytesInPlace(fields.accel_x);
	mrpt::reverseBytesInPlace(fields.gyro_z);
	mrpt::reverseBytesInPlace(fields.gyro_y_neg);
	mrpt::reverseBytesInPlace(fields.gyro_x);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_MARKPOS. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_MARKPOS)
/** Frame header */
nv_oem6_header_t header;
nv_oem6_solution_status::nv_solution_status_t solution_stat =
	nv_oem6_solution_status::INVALID_FIX;
nv_oem6_position_type::nv_position_type_t position_type =
	nv_oem6_position_type::NONE;
/** [deg], [deg], hgt over sea level[m] */
double lat = 0, lon = 0, hgt = 0;
float undulation = 0;
uint32_t datum_id = 0;
float lat_sigma = 0, lon_sigma = 0, hgt_sigma = 0;
char base_station_id[4] = {0, 0, 0, 0};
float diff_age = 0, sol_age = 0;
uint8_t num_sats_tracked = 0, num_sats_sol = 0, num_sats_sol_L1 = 0,
		num_sats_sol_multi = 0;
uint8_t reserved = 0;
uint8_t ext_sol_stat = 0;
uint8_t galileo_beidou_mask = 0;
uint8_t gps_glonass_mask = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
/**  Return the geodetic coords as a mrpt::topography::TGeodeticCoords structure
 * (requires linking against mrpt-topography)
 *   Call as: getAsStruct<TGeodeticCoords>(); */
template <class TGEODETICCOORDS>
inline TGEODETICCOORDS getAsStruct() const
{
	return TGEODETICCOORDS(fields.lat, fields.lon, fields.hgt);
}
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace_enum(fields.solution_stat);
	mrpt::reverseBytesInPlace_enum(fields.position_type);
	mrpt::reverseBytesInPlace(fields.lat);
	mrpt::reverseBytesInPlace(fields.lon);
	mrpt::reverseBytesInPlace(fields.hgt);
	mrpt::reverseBytesInPlace(fields.undulation);
	mrpt::reverseBytesInPlace(fields.datum_id);
	mrpt::reverseBytesInPlace(fields.lat_sigma);
	mrpt::reverseBytesInPlace(fields.lon_sigma);
	mrpt::reverseBytesInPlace(fields.hgt_sigma);
	mrpt::reverseBytesInPlace(fields.diff_age);
	mrpt::reverseBytesInPlace(fields.sol_age);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_MARKTIME. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_MARKTIME)
/** Frame header */
nv_oem6_header_t header;
uint32_t week = 0;
double week_seconds = 0;
double clock_offset = 0, clock_offset_std = 0;
double utc_offset = 0;
uint32_t clock_status = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
bool getAllFieldDescriptions(std::ostream& o) const override;
bool getAllFieldValues(std::ostream& o) const override;
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.week);
	mrpt::reverseBytesInPlace(fields.week_seconds);
	mrpt::reverseBytesInPlace(fields.clock_offset);
	mrpt::reverseBytesInPlace(fields.clock_offset_std);
	mrpt::reverseBytesInPlace(fields.utc_offset);
	mrpt::reverseBytesInPlace(fields.clock_status);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_MARK2TIME. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_MARK2TIME)
/** Frame header */
nv_oem6_header_t header;
uint32_t week = 0;
double week_seconds = 0;
double clock_offset = 0, clock_offset_std = 0;
double utc_offset = 0;
uint32_t clock_status = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
bool getAllFieldDescriptions(std::ostream& o) const override;
bool getAllFieldValues(std::ostream& o) const override;
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.week);
	mrpt::reverseBytesInPlace(fields.week_seconds);
	mrpt::reverseBytesInPlace(fields.clock_offset);
	mrpt::reverseBytesInPlace(fields.clock_offset_std);
	mrpt::reverseBytesInPlace(fields.utc_offset);
	mrpt::reverseBytesInPlace(fields.clock_status);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

/** Novatel frame: NV_OEM6_IONUTC. \sa mrpt::obs::CObservationGPS  */
GNSS_BINARY_MSG_DEFINITION_START(NV_OEM6_IONUTC)
/** Frame header */
nv_oem6_header_t header;
/** Ionospheric alpha and beta constant terms parameters */
double a0 = 0, a1 = 0, a2 = 0, a3 = 0, b0 = 0, b1 = 0, b2 = 0, b3 = 0;
/** UTC reference week number */
uint32_t utc_wn = 0;
/** Reference time of UTC params */
uint32_t tot = 0;
/** UTC constant and 1st order terms */
double A0 = 0, A1 = 0;
/** Future week number */
uint32_t wn_lsf = 0;
/** Day number (1=sunday, 7=saturday) */
uint32_t dn = 0;
/** Delta time due to leap seconds */
uint32_t deltat_ls = 0;
/** Delta time due to leap seconds (future) */
uint32_t deltat_lsf = 0;
uint32_t reserved = 0;
uint32_t crc = 0;
GNSS_BINARY_MSG_DEFINITION_MID
void fixEndianness() override
{
#if MRPT_IS_BIG_ENDIAN
	fields.header.fixEndianness();
	mrpt::reverseBytesInPlace(fields.a0);
	mrpt::reverseBytesInPlace(fields.a1);
	mrpt::reverseBytesInPlace(fields.a2);
	mrpt::reverseBytesInPlace(fields.a3);
	mrpt::reverseBytesInPlace(fields.b0);
	mrpt::reverseBytesInPlace(fields.b1);
	mrpt::reverseBytesInPlace(fields.b2);
	mrpt::reverseBytesInPlace(fields.b3);
	mrpt::reverseBytesInPlace(fields.utc_wn);
	mrpt::reverseBytesInPlace(fields.tot);
	mrpt::reverseBytesInPlace(fields.A0);
	mrpt::reverseBytesInPlace(fields.A1);
	mrpt::reverseBytesInPlace(fields.wn_lsf);
	mrpt::reverseBytesInPlace(fields.dn);
	mrpt::reverseBytesInPlace(fields.deltat_ls);
	mrpt::reverseBytesInPlace(fields.deltat_lsf);
	mrpt::reverseBytesInPlace(fields.reserved);
	mrpt::reverseBytesInPlace(fields.crc);
#endif
}
GNSS_BINARY_MSG_DEFINITION_MID_END

#pragma pack(pop)  // End of pack = 1
}  // namespace mrpt::obs::gnss


text:
static NSColor *kValidationTextFieldBackgroundColour;
static NSColor *kValidationTextFieldValidBackgroundColour;
static NSColor *kValidationTextFieldInvalidBackgroundColour;
static NSColor *kValidationTextFieldPlaceholderValidateFontColour;
static NSColor *kValidationTextFieldPlaceholderFontColour;

static void *TextFieldValidationTypePropertyKey = &TextFieldValidationTypePropertyKey;
static void *PlaceholderStringPropertyKey = &PlaceholderStringPropertyKey;

@implementation NSTextField (Validation)

+ (void)initialize
{
	if (self == [NSTextField class]) {
		kValidationTextFieldBackgroundColour = [NSColor whiteColor];
		kValidationTextFieldValidBackgroundColour = [NSColor greenColor];
		kValidationTextFieldInvalidBackgroundColour = [NSColor redColor];
		kValidationTextFieldPlaceholderValidateFontColour = [NSColor whiteColor];
		kValidationTextFieldPlaceholderFontColour = [NSColor grayColor];
	}
}

#pragma mark - Properties

- (TextFieldValidationType)textFieldValidationType
{
	NSNumber *t = objc_getAssociatedObject(self, TextFieldValidationTypePropertyKey);
	return t.intValue;
}

- (void)setTextFieldValidationType:(TextFieldValidationType)textFieldValidationType
{
	objc_setAssociatedObject(self, TextFieldValidationTypePropertyKey, @(textFieldValidationType), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)placeholderString
{
	return objc_getAssociatedObject(self, PlaceholderStringPropertyKey);
}

- (void)setPlaceholderString:(NSString *)placeholderString
{
	objc_setAssociatedObject(self, PlaceholderStringPropertyKey, placeholderString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - Public

- (BOOL)validate
{
	NSColor *bgColour = kValidationTextFieldBackgroundColour;
	NSColor *placeholderColour = kValidationTextFieldPlaceholderValidateFontColour;

	BOOL valid = YES;
	switch (self.textFieldValidationType) {
		case TextFieldValidationTypeNone:
			// Do nothing, we just want white
			placeholderColour = kValidationTextFieldPlaceholderFontColour;
			break;

		case TextFieldValidationTypeEmailOptional:
			// IMPORTANT: make sure this is above the ValidationTypeEmail (which should be below)
			if (self.stringValue.length == 0) {
				// Do nothing, we just want white
				placeholderColour = kValidationTextFieldPlaceholderFontColour;
				break;
			}

		// Else: Do nothing, flow threw to ValidationTypeEmail

		case TextFieldValidationTypeEmail: {
			valid = [self.stringValue validEmail];
			bgColour = valid ? kValidationTextFieldValidBackgroundColour : kValidationTextFieldInvalidBackgroundColour;
			break;
		}

		case TextFieldValidationTypeOptional:
			placeholderColour = kValidationTextFieldPlaceholderFontColour;
			bgColour = kValidationTextFieldBackgroundColour;
			break;

		case TextFieldValidationTypeRequired:
		case TextFieldValidationTypePassword:
		default: {
			valid = self.stringValue.length > 0;
			bgColour = valid ? kValidationTextFieldValidBackgroundColour : kValidationTextFieldInvalidBackgroundColour;
			break;
		}
	}

	[self setPlaceholderFontColour:placeholderColour];

	self.backgroundColor = bgColour;
	// This will make sure the background updates
	[self setEditable:NO];
	[self setEditable:YES];

	return valid;
}

- (void)reset
{
	self.stringValue = @"";
	self.backgroundColor = kValidationTextFieldBackgroundColour;
	[self setPlaceholderFontColour:kValidationTextFieldPlaceholderFontColour];

	// This will make sure the background updates
	[self setEditable:NO];
	[self setEditable:YES];
}

#pragma mark - Private

- (void)setPlaceholderFontColour:(NSColor *)colour
{
	if (!self.placeholderString) {
		self.placeholderString = [self.cell placeholderString];
	}

	NSDictionary *d = @{
		NSFontAttributeName : self.font,
		NSForegroundColorAttributeName : colour
	};
	NSAttributedString *as = [[NSAttributedString alloc] initWithString:self.placeholderString
	                                                         attributes:d];
	[self.cell setPlaceholderAttributedString:as];
}

#pragma mark - Static Properties

+ (void)setBackgroundColour:(NSColor *)colour
{
	kValidationTextFieldBackgroundColour = colour;
}

+ (void)setValidBackgroundColour:(NSColor *)colour
{
	kValidationTextFieldValidBackgroundColour = colour;
}

+ (void)setInvalidBackgroundColour:(NSColor *)colour
{
	kValidationTextFieldInvalidBackgroundColour = colour;
}

+ (void)setPlaceholderValidateFontColour:(NSColor *)colour
{
	kValidationTextFieldPlaceholderValidateFontColour = colour;
}

+ (void)setPlaceholderFontColour:(NSColor *)colour
{
	kValidationTextFieldPlaceholderFontColour = colour;
}

@end


text:
<?php

use PHPUnit\Framework\TestCase;
use Laminas\ServiceManager\ServiceManager;
use Laminas\EventManager\EventManager;

class EventManagerFactoryTest extends TestCase
{
    public function setUp() : void
    {
        $this->container = new ServiceManager;
        $this->container->setFactory(EventManager::class, 'Obullo\Factory\EventManagerFactory');
    }

    public function testFactory()
    {
        $instance = $this->container->get(EventManager::class);

        $this->assertInstanceOf('Laminas\EventManager\EventManager', $instance);
    }
}


text:
package org.bzewdu.tools.perftrend.htmlgen;

import java.io.File;

public class TopLevelHtml extends Html {
    private static String FILENAME;
    private static String TITLE;
    private File _promoted;
    private File _nightly;
    private File _cte;
    private File _workspace;
    private File _other;

    public TopLevelHtml(final File htmldir) {
        super(new File(htmldir, TopLevelHtml.FILENAME), TopLevelHtml.TITLE);
    }

    public TopLevelHtml(final File htmldir, final File p, final File n, final File c, final File w, final File o) {
        super(new File(htmldir, TopLevelHtml.FILENAME), TopLevelHtml.TITLE);
        this._promoted = p;
        this._nightly = n;
        this._cte = c;
        this._workspace = w;
        this._other = o;
    }

    public TopLevelHtml(final File htmldir, final File p, final File n, final File c, final File w) {
        super(new File(htmldir, TopLevelHtml.FILENAME), TopLevelHtml.TITLE);
        this._promoted = p;
        this._nightly = n;
        this._cte = c;
        this._workspace = w;
    }

    protected String createHeader() {
        return "
Click on one of the following for a detailed summary.
\n";
    }

    protected String createBody() {
        String out = "";
        out += "
RE Promoted Summary
\n";
        out += "
RE Ergonomics Summary
\n";
        out += "
RE Nightly Summary
\n";
        out += "
Hotspot Summary
\n";
        out += "
Swing Nightly Summary
\n";
        out += "
Java2D Workspace Summary
\n";
        return out;
    }

    static {
        TopLevelHtml.FILENAME = "index.html";
        TopLevelHtml.TITLE = "Welcome to perftrend Trend Tool";
    }
}


text:
Symfony 2 config component extra loaders.

[![Latest Stable Version](https://poser.pugx.org/ebidtech/config-loader/v/stable.png)](https://packagist.org/packages/ebidtech/config-loader) [![Build Status](https://travis-ci.org/ebidtech/config-loader.png?branch=master)](https://travis-ci.org/ebidtech/config-loader) [![Coverage Status](https://coveralls.io/repos/ebidtech/config-loader/badge.png?branch=master)](https://coveralls.io/r/ebidtech/config-loader?branch=master) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/ebidtech/config-loader/badges/quality-score.png?s=19c113ae6cc28c94b2e7ba21a82513c0f7e93ea0)](https://scrutinizer-ci.com/g/ebidtech/config-loader/) [![Dependency Status](https://www.versioneye.com/user/projects/5299e146632bac33e8000014/badge.png)](https://www.versioneye.com/user/projects/5299e146632bac33e8000014)
## Requirements ##

* PHP >= 5.4

## Installation ##

The recommended way to install is through composer.

Just create a `composer.json` file for your project:

``` json
{
    "require": {
        "ebidtech/config-loader": "@stable"
    }
}
```

**Tip:** browse [`ebidtech/config-loader`](https://packagist.org/packages/ebidtech/config-loader) page to choose a stable version to use, avoid the `@stable` meta constraint.

And run these two commands to install it:

```bash
$ curl -sS https://getcomposer.org/installer | php
$ composer install
```

Now you can add the autoloader, and you will have access to the library:

```php
<?php

require 'vendor/autoload.php';
```

## Usage ##

You should read about [Symfony 2 config component](http://symfony.com/doc/2.3/components/config/introduction.html).

Example of simple use:
```php
use EBT\ConfigLoader\YamlFileLoader;

$yamlLoader = new YamlFileLoader();
// this will read the file and return it as array
$content = $yamlLoader->load(__DIR__ . '/test.yml');
```

## Contributing ##

See CONTRIBUTING file.

## Credits ##

* Ebidtech developer team, config loader Lead developer [Eduardo Oliveira](https://github.com/entering) (eduardo.oliveira@ebidtech.com).
* [All contributors](https://github.com/ebidtech/config-loader/contributors)

## License ##

Config loader library is released under the MIT License. See the bundled LICENSE file for details.


text:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using ThinMvvm.Tests.TestInfrastructure;
using Xunit;

namespace ThinMvvm.Tests
{
    public sealed class OptionalTests
    {
        [Fact]
        public void DefaultConstructorSetsHasValue()
        {
            var optional = new Optional<int>();

            Assert.False( optional.HasValue );
        }

        [Fact]
        public void CannotGetValueIfNotPresent()
        {
            var optional = new Optional<int>();

            Assert.Throws<InvalidOperationException>( () => optional.Value );
        }

        [Fact]
        public void ConstructorSetsHasValue()
        {
            var optional = new Optional<int>( 0 );

            Assert.True( optional.HasValue );
        }

        [Fact]
        public void ConstructorSetsValue()
        {
            var optional = new Optional<int>( 42 );

            Assert.Equal( 42, optional.Value );
        }

        [Fact]
        public void CanBeDataContractSerialized()
        {
            var optional = new Optional<int>( 42 );

            var serializer = new DataContractJsonSerializer( optional.GetType() );
            var stream = new MemoryStream();

            serializer.WriteObject( stream, optional );

            stream.Seek( 0, SeekOrigin.Begin );
            var roundtrippedOptional = (Optional<int>) serializer.ReadObject( stream );

            Assert.Equal( optional, roundtrippedOptional );
        }

        [Fact]
        public void Equality()
        {
            EqualityTests.For( default( Optional<string> ) )
                .WithUnequal( new Optional<string>( null ) )
                .WithUnequal( new Optional<string>( "" ) )
                .WithUnequal( new Optional<string>( "abc" ) )
                .Test();

            EqualityTests.For( new Optional<string>( null ) )
                .WithUnequal( new Optional<string>( "" ) )
                .WithUnequal( new Optional<string>( "abc" ) )
                .Test();

            EqualityTests.For( new Optional<string>( "" ) )
                .WithUnequal( new Optional<string>( "abc" ) )
                .Test();

            EqualityTests.For( new Optional<string>( "abc" ) )
                .Test();
        }

        [Fact]
        public void ToStringReturnsWrappedValueWhenPresent()
        {
            var optional = new Optional<int>( 42 );

            Assert.Equal( "(value: 42)", optional.ToString() );
        }

        [Fact]
        public void ToStringReturnsSpecialValueWhenNoValueIsPresent()
        {
            var optional = new Optional<int>();

            Assert.Equal( "(no value)", optional.ToString() );
        }

        [Fact]
        public void ToStringReturnsSpecialValueOnNullValue()
        {
            var optional = new Optional<string>( null );

            Assert.Equal( "(null)", optional.ToString() );
        }
    }
}


text:
/*
 * @file
 * @brief Lego NXT direct command manager
 *
 * @date 13.03.11
 * @author Anton Kozlov
 */

#include <stdint.h>
#include <string.h>

#include <drivers/nxt/direct_comm.h>
#include <drivers/bluetooth/bluetooth.h>

#include <pnet/core.h>
#include <pnet/repo.h>
#include <pnet/node.h>
#include <pnet/pack/pack_alone.h>

#include <pnet/node/direct_comm.h>

#include <embox/unit.h>

EMBOX_UNIT_INIT(dc_pnet_init);

#define DC_BUFF_SIZE 0x20 /* lego_nxt direct command maximum length */

static int ctrl_rx(struct pnet_pack *pack);
static int data_rx(struct pnet_pack *pack);

PNET_NODE_DEF_NAME(PNET_NODE_DIRECT_COMM_FORMATION_DATA, this_data, {
	.rx_hnd = data_rx
});

PNET_NODE_DEF_NAME(PNET_NODE_DIRECT_COMM_FORMATION_CTRL, this_ctrl, {
	.rx_hnd = ctrl_rx
});

static int handle_size(uint8_t *buff) {
	return buff[0] + (buff[1] << 8);
}

static int (*data_hnd)(void *);
static int get_body(void *msg);
static int get_header(void *msg);

static int get_header(void *msg) {
	int size = handle_size((uint8_t *) msg);

	if (size > DC_BUFF_SIZE - MSG_SIZE_BYTE_CNT) {
		//TODO error length
	}
	data_hnd = get_body;
	bluetooth_read(size);
	return NET_HND_STOP_FREE;
}

static int get_body(void *msg) {
	data_hnd = get_header;
	bluetooth_read(MSG_SIZE_BYTE_CNT);
	return NET_HND_FORWARD_DEFAULT;
}

static int data_rx(struct pnet_pack *pack) {
	return data_hnd(pnet_pack_get_data(pack));
}

static int ctrl_rx(struct pnet_pack *pack) {
	int status = *((uint8_t *) pnet_pack_get_data(pack));
	if (0 != status) { /* if connected */
		data_hnd = get_header;
		bluetooth_read(MSG_SIZE_BYTE_CNT);
	}

	return NET_HND_STOP_FREE;
}

static int dc_pnet_init(void) {
	return 0;
}


text:
package main

import (
	"fmt"
	"github.com/mattbaird/turnpike"
	"log"
	"net/http"
)

func main() {
	s := turnpike.NewServer(false)
	http.Handle("/ws", s.Handler)
	http.Handle("/", http.FileServer(http.Dir("web")))

	fmt.Println("Listening on port 8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}


text:
package syslog

import (
	"errors"
	"math"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/influxdata/go-syslog/v2/rfc5424"
	"github.com/influxdata/telegraf"
)

type SyslogMapper struct {
	DefaultSdid         string
	DefaultSeverityCode uint8
	DefaultFacilityCode uint8
	DefaultAppname      string
	Sdids               []string
	Separator           string
	reservedKeys        map[string]bool
}

// MapMetricToSyslogMessage maps metrics tags/fields to syslog messages
func (sm *SyslogMapper) MapMetricToSyslogMessage(metric telegraf.Metric) (*rfc5424.SyslogMessage, error) {
	msg := &rfc5424.SyslogMessage{}

	sm.mapPriority(metric, msg)
	sm.mapStructuredData(metric, msg)
	sm.mapAppname(metric, msg)
	mapHostname(metric, msg)
	mapTimestamp(metric, msg)
	mapMsgID(metric, msg)
	mapVersion(metric, msg)
	mapProcID(metric, msg)
	mapMsg(metric, msg)

	if !msg.Valid() {
		return nil, errors.New("metric could not produce valid syslog message")
	}
	return msg, nil
}

func (sm *SyslogMapper) mapStructuredData(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	for _, tag := range metric.TagList() {
		sm.mapStructuredDataItem(tag.Key, tag.Value, msg)
	}
	for _, field := range metric.FieldList() {
		sm.mapStructuredDataItem(field.Key, formatValue(field.Value), msg)
	}
}

func (sm *SyslogMapper) mapStructuredDataItem(key string, value string, msg *rfc5424.SyslogMessage) {
	if sm.reservedKeys[key] {
		return
	}
	isExplicitSdid := false
	for _, sdid := range sm.Sdids {
		k := strings.TrimLeft(key, sdid+sm.Separator)
		if len(key) > len(k) {
			isExplicitSdid = true
			msg.SetParameter(sdid, k, value)
			break
		}
	}
	if !isExplicitSdid && len(sm.DefaultSdid) > 0 {
		k := strings.TrimPrefix(key, sm.DefaultSdid+sm.Separator)
		msg.SetParameter(sm.DefaultSdid, k, value)
	}
}

func (sm *SyslogMapper) mapAppname(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	if value, ok := metric.GetTag("appname"); ok {
		msg.SetAppname(formatValue(value))
	} else {
		//Use default appname
		msg.SetAppname(sm.DefaultAppname)
	}
}

func mapMsgID(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	if value, ok := metric.GetField("msgid"); ok {
		msg.SetMsgID(formatValue(value))
	} else {
		// We default to metric name
		msg.SetMsgID(metric.Name())
	}
}

func mapVersion(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	if value, ok := metric.GetField("version"); ok {
		switch v := value.(type) {
		case uint64:
			msg.SetVersion(uint16(v))
			return
		}
	}
	msg.SetVersion(1)
}

func mapMsg(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	if value, ok := metric.GetField("msg"); ok {
		msg.SetMessage(formatValue(value))
	}
}

func mapProcID(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	if value, ok := metric.GetField("procid"); ok {
		msg.SetProcID(formatValue(value))
	}
}

func (sm *SyslogMapper) mapPriority(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	severityCode := sm.DefaultSeverityCode
	facilityCode := sm.DefaultFacilityCode

	if value, ok := getFieldCode(metric, "severity_code"); ok {
		severityCode = *value
	}

	if value, ok := getFieldCode(metric, "facility_code"); ok {
		facilityCode = *value
	}

	priority := (8 * facilityCode) + severityCode
	msg.SetPriority(priority)
}

func mapHostname(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	// Try with hostname, then with source, then with host tags, then take OS Hostname
	if value, ok := metric.GetTag("hostname"); ok {
		msg.SetHostname(formatValue(value))
	} else if value, ok := metric.GetTag("source"); ok {
		msg.SetHostname(formatValue(value))
	} else if value, ok := metric.GetTag("host"); ok {
		msg.SetHostname(formatValue(value))
	} else if value, err := os.Hostname(); err == nil {
		msg.SetHostname(value)
	}
}

func mapTimestamp(metric telegraf.Metric, msg *rfc5424.SyslogMessage) {
	timestamp := metric.Time()
	if value, ok := metric.GetField("timestamp"); ok {
		switch v := value.(type) {
		case int64:
			timestamp = time.Unix(0, v).UTC()
		}
	}
	msg.SetTimestamp(timestamp.Format(time.RFC3339))
}

func formatValue(value interface{}) string {
	switch v := value.(type) {
	case string:
		return v
	case bool:
		if v {
			return "1"
		}
		return "0"
	case uint64:
		return strconv.FormatUint(v, 10)
	case int64:
		return strconv.FormatInt(v, 10)
	case float64:
		if math.IsNaN(v) {
			return ""
		}

		if math.IsInf(v, 0) {
			return ""
		}
		return strconv.FormatFloat(v, 'f', -1, 64)
	}

	return ""
}

func getFieldCode(metric telegraf.Metric, fieldKey string) (*uint8, bool) {
	if value, ok := metric.GetField(fieldKey); ok {
		if v, err := strconv.ParseUint(formatValue(value), 10, 8); err == nil {
			r := uint8(v)
			return &r, true
		}
	}
	return nil, false
}

func newSyslogMapper() *SyslogMapper {
	return &SyslogMapper{
		reservedKeys: map[string]bool{
			"version": true, "severity_code": true, "facility_code": true,
			"procid": true, "msgid": true, "msg": true, "timestamp": true, "sdid": true,
			"hostname": true, "source": true, "host": true, "severity": true,
			"facility": true, "appname": true},
	}
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="assets/stylesheets/example.css">

    <title>Map</title>

        <ui-gmap-google-map center="map.center" zoom="map.zoom" draggable="true" options="options">
            <ui-gmap-marker icon="marker.icon" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id" >
            </ui-gmap-marker>
            <ui-gmap-markers models='markers' coords="'coords'" options="'options'" events="'events'" idkey="'id'" >
              <ui-gmap-windows show="'show'">

                    id: {{id}}, lat: {{coords.latitude}}, lon: {{coords.latitude}}

              </ui-gmap-windows>
            </ui-gmap-markers>
        </ui-gmap-google-map>

coords  update ctr: {{coordsUpdates}}

dynamic move ctr: {{dynamicMoveCtr}}


text:
namespace blink {
class WebFrameWidget;
class WebLocalFrame;
}

namespace content {

class PepperPluginInstanceImpl;
class RenderWidget;

// This is the renderer-side message filter that generates the replies for the
// messages sent by the TextInputClientMac. See
// content/browser/renderer_host/text_input_client_mac.h for more information.
class TextInputClientObserver : public IPC::Listener, public IPC::Sender {
 public:
  explicit TextInputClientObserver(RenderWidget* render_widget);
  ~TextInputClientObserver() override;

  // IPC::Listener override.
  bool OnMessageReceived(const IPC::Message& message) override;

  // IPC::Sender override.
  bool Send(IPC::Message* message) override;

 private:
  // The render widget corresponding to this TextInputClientObserver.
  blink::WebFrameWidget* GetWebFrameWidget() const;

  blink::WebLocalFrame* GetFocusedFrame() const;

#if BUILDFLAG(ENABLE_PLUGINS)
  // Returns the currently focused pepper plugin on the page. The expectation is
  // that the focused pepper plugin is inside a frame whose local root is equal
  // to GetWebFrameWidget()->localRoot().
  PepperPluginInstanceImpl* GetFocusedPepperPlugin() const;
#endif

  // IPC Message handlers:
  void OnStringAtPoint(gfx::Point point);
  void OnCharacterIndexForPoint(gfx::Point point);
  void OnFirstRectForCharacterRange(gfx::Range range);
  void OnStringForRange(gfx::Range range);

  // The RenderWidget owning this instance of the observer.
  RenderWidget* render_widget_;

  DISALLOW_COPY_AND_ASSIGN(TextInputClientObserver);
};

}  // namespace content

#endif  // CONTENT_RENDERER_TEXT_INPUT_CLIENT_OBSERVER_H_


text:
using System;

namespace hpack
{
	/// <summary>
	/// The DynamicTable class.
	/// </summary>
	public class DynamicTable
	{
		// a circular queue of header fields
		HeaderField[] headerFields;
		int head;
		int tail;
		private int size;
		private int capacity = -1;
		// ensure setCapacity creates the array

		/// <summary>
		/// The Capacity
		/// </summary>
		/// <value></value>
		public int Capacity { get { return this.capacity; } }

		/// <summary>
		/// The Size
		/// </summary>
		/// <value></value>
		public int Size { get { return this.size; } }

		/// <summary>
		/// Creates a new dynamic table with the specified initial capacity.
		/// </summary>
		/// <param name="initialCapacity">Initial capacity.</param>
		public DynamicTable(int initialCapacity)
		{
			this.SetCapacity(initialCapacity);
		}

		/// <summary>
		/// Return the number of header fields in the dynamic table.
		/// </summary>
		public int Length()
		{
			var length = 0;
			if (this.head < this.tail) {
				length = this.headerFields.Length - this.tail + this.head;
			} else {
				length = this.head - this.tail;
			}
			return length;
		}

		/// <summary>
		/// Return the current size of the dynamic table.
		/// This is the sum of the size of the entries.
		/// </summary>
		/// <returns>The size.</returns>
		public int GetSize()
		{
			return this.size;
		}

		/// <summary>
		/// Return the maximum allowable size of the dynamic table.
		/// </summary>
		/// <returns>The capacity.</returns>
		public int GetCapacity()
		{
			return capacity;
		}

		/// <summary>
		/// Return the header field at the given index.
		/// The first and newest entry is always at index 1,
		/// and the oldest entry is at the index length().
		/// </summary>
		/// <returns>The entry.</returns>
		/// <param name="index">Index.</param>
		public HeaderField GetEntry(int index)
		{
			if (index <= 0 || index > this.Length()) {
				throw new IndexOutOfRangeException();
			}
			var i = this.head - index;
			if (i < 0) {
				return this.headerFields[i + this.headerFields.Length];
			} else {
				return this.headerFields[i];
			}
		}

		/// <summary>
		/// Add the header field to the dynamic table.
		/// Entries are evicted from the dynamic table until the size of the table
		/// and the new header field is less than or equal to the table's capacity.
		/// If the size of the new entry is larger than the table's capacity,
		/// the dynamic table will be cleared.
		/// </summary>
		/// <param name="header">Header.</param>
		public void Add(HeaderField header)
		{
			var headerSize = header.Size;
			if (headerSize > this.capacity) {
				this.Clear();
				return;
			}
			while(this.size + headerSize > this.capacity) {
				this.Remove();
			}
			this.headerFields[this.head++] = header;
			this.size += header.Size;
			if (this.head == this.headerFields.Length) {
				this.head = 0;
			}
		}

		/// <summary>
		/// Remove and return the oldest header field from the dynamic table.
		/// </summary>
		public HeaderField Remove()
		{
			var removed = this.headerFields[this.tail];
			if (removed == null) {
				return null;
			}
			this.size -= removed.Size;
			this.headerFields[this.tail++] = null;
			if (this.tail == this.headerFields.Length) {
				this.tail = 0;
			}
			return removed;
		}

		/// <summary>
		/// Remove all entries from the dynamic table.
		/// </summary>
		public void Clear()
		{
			while(this.tail != this.head) {
				this.headerFields[this.tail++] = null;
				if (this.tail == this.headerFields.Length) {
					this.tail = 0;
				}
			}
			this.head = 0;
			this.tail = 0;
			this.size = 0;
		}

		/// <summary>
		/// Set the maximum size of the dynamic table.
		/// Entries are evicted from the dynamic table until the size of the table
		/// is less than or equal to the maximum size.
		/// </summary>
		/// <param name="capacity">Capacity.</param>
		public void SetCapacity(int capacity)
		{
			if (capacity < 0) {
				throw new ArgumentException("Illegal Capacity: " + capacity);
			}

			// initially capacity will be -1 so init won't return here
			if (this.capacity == capacity) {
				return;
			}
			this.capacity = capacity;

			if (capacity == 0) {
				this.Clear();
			} else {
				// initially size will be 0 so remove won't be called
				while(this.size > capacity) {
					this.Remove();
				}
			}

			var maxEntries = capacity / HeaderField.HEADER_ENTRY_OVERHEAD;
			if (capacity % HeaderField.HEADER_ENTRY_OVERHEAD != 0) {
				maxEntries++;
			}

			// check if capacity change requires us to reallocate the array
			if (this.headerFields != null && this.headerFields.Length == maxEntries) {
				return;
			}

			var tmp = new HeaderField[maxEntries];

			// initially length will be 0 so there will be no copy
			var len = this.Length();
			var cursor = this.tail;
			for(var i = 0; i < len; i++) {
				var entry = this.headerFields[cursor++];
				tmp[i] = entry;
				if (cursor == this.headerFields.Length) {
					cursor = 0;
				}
			}

			this.tail = 0;
			this.head = this.tail + len;
			this.headerFields = tmp;
		}
	}
}


text:
using System.Web.Optimization;

namespace Cake.Web
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/Content/js/jquery").Include(
                        "~/Content/js/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/Content/js/jqueryval").Include(
                        "~/Content/js/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/Content/js/modernizr").Include(
                        "~/Content/js/modernizr-*"));

            bundles.Add(new ScriptBundle("~/Content/js/bootstrap").Include(
                      "~/Content/js/bootstrap.js",
                      "~/Content/js/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css/files").Include(
                      "~/Content/css/bootstrap.css",
                      "~/Content/css/cake-theme.css",
                      "~/Content/css/global.css"));
        }
    }
}


text:
layout: default
href: "#modal-02"
modalID: "modal-02"
projectTitle: Cupcake Physics Blog
imageAlt: Cupcake Physics
src: assets/images/cupcake-physics.png
projectLocation: Online Blog
projectDates: 2015-2016
projectTags: Education, Data Visualization, Web Development
projectLink: http://blog.cupcakephysics.com
clients:
description: I love teaching. I love physics. I love programming. Why not combine all three of these passions into a blog? Not only do I use my blog to teach the world about physics, but I also use it as a test bed for new ideas. Many of the data-driven and interactive pieces of code that I implement in my research are first tested here on my blog.
---


text:
import Feature from '../../../src/ol/Feature.js';
import Map from '../../../src/ol/Map.js';
import Point from '../../../src/ol/geom/Point.js';
import View from '../../../src/ol/View.js';
import {
  Tile as TileLayer,
  Vector as VectorLayer,
} from '../../../src/ol/layer.js';
import {Vector as VectorSource, XYZ} from '../../../src/ol/source.js';
import {fromLonLat} from '../../../src/ol/proj.js';

const center = fromLonLat([-111, 45.7]);

new Map({
  layers: [
    new TileLayer({
      source: new XYZ({
        url: '/data/tiles/satellite/{z}/{x}/{y}.jpg',
      }),
    }),
    new VectorLayer({
      source: new VectorSource({
        features: [new Feature(new Point(center))],
      }),
    }),
  ],
  target: 'map',
  view: new View({
    center: center,
    zoom: 3,
    rotation: Math.PI / 4,
  }),
});

render();


text:
package com.amazonaws.services.elasticloadbalancing.model;

import java.io.Serializable;

import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing#modifyLoadBalancerAttributes(ModifyLoadBalancerAttributesRequest) ModifyLoadBalancerAttributes operation}.
 *

 * Modifies the attributes of the specified load balancer.
 *

 *

 * You can modify the load balancer attributes, such as
 * AccessLogs ,
 * ConnectionDraining , and
 * CrossZoneLoadBalancing by either enabling or disabling
 * them. Or, you can modify the load balancer attribute
 * ConnectionSettings by specifying an idle connection
 * timeout value for your load balancer.
 *

 *

 * For more information, see the following in the Elastic Load
 * Balancing Developer Guide :
 *

 *
 *

 *

 *  Cross-Zone Load Balancing
 *

 *

 *  Connection Draining
 *

 *

 *  Access Logs
 *

 *

 *  Idle Connection Timeout
 *

 *
 *

 *
 * @see com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing#modifyLoadBalancerAttributes(ModifyLoadBalancerAttributesRequest)
 */
public class ModifyLoadBalancerAttributesRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     * The name of the load balancer.
     */
    private String loadBalancerName;

    /**
     * The attributes of the load balancer.
     */
    private LoadBalancerAttributes loadBalancerAttributes;

    /**
     * The name of the load balancer.
     *
     * @return The name of the load balancer.
     */
    public String getLoadBalancerName() {
        return loadBalancerName;
    }

    /**
     * The name of the load balancer.
     *
     * @param loadBalancerName The name of the load balancer.
     */
    public void setLoadBalancerName(String loadBalancerName) {
        this.loadBalancerName = loadBalancerName;
    }

    /**
     * The name of the load balancer.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param loadBalancerName The name of the load balancer.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ModifyLoadBalancerAttributesRequest withLoadBalancerName(String loadBalancerName) {
        this.loadBalancerName = loadBalancerName;
        return this;
    }

    /**
     * The attributes of the load balancer.
     *
     * @return The attributes of the load balancer.
     */
    public LoadBalancerAttributes getLoadBalancerAttributes() {
        return loadBalancerAttributes;
    }

    /**
     * The attributes of the load balancer.
     *
     * @param loadBalancerAttributes The attributes of the load balancer.
     */
    public void setLoadBalancerAttributes(LoadBalancerAttributes loadBalancerAttributes) {
        this.loadBalancerAttributes = loadBalancerAttributes;
    }

    /**
     * The attributes of the load balancer.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param loadBalancerAttributes The attributes of the load balancer.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public ModifyLoadBalancerAttributesRequest withLoadBalancerAttributes(LoadBalancerAttributes loadBalancerAttributes) {
        this.loadBalancerAttributes = loadBalancerAttributes;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getLoadBalancerName() != null) sb.append("LoadBalancerName: " + getLoadBalancerName() + ",");
        if (getLoadBalancerAttributes() != null) sb.append("LoadBalancerAttributes: " + getLoadBalancerAttributes() );
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getLoadBalancerName() == null) ? 0 : getLoadBalancerName().hashCode());
        hashCode = prime * hashCode + ((getLoadBalancerAttributes() == null) ? 0 : getLoadBalancerAttributes().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof ModifyLoadBalancerAttributesRequest == false) return false;
        ModifyLoadBalancerAttributesRequest other = (ModifyLoadBalancerAttributesRequest)obj;

        if (other.getLoadBalancerName() == null ^ this.getLoadBalancerName() == null) return false;
        if (other.getLoadBalancerName() != null && other.getLoadBalancerName().equals(this.getLoadBalancerName()) == false) return false;
        if (other.getLoadBalancerAttributes() == null ^ this.getLoadBalancerAttributes() == null) return false;
        if (other.getLoadBalancerAttributes() != null && other.getLoadBalancerAttributes().equals(this.getLoadBalancerAttributes()) == false) return false;
        return true;
    }

    @Override
    public ModifyLoadBalancerAttributesRequest clone() {

            return (ModifyLoadBalancerAttributesRequest) super.clone();
    }

}


text:
import React from 'react'
import type {Node} from 'react'
import type {ObservableI, Subscription} from '../typedefs/observable'

type Props = {
  documentId: string,
  materialize: string => ObservableI<Object>,
  children: Object => null | Node
}

type State = {
  materialized: ?Object
}

export default class WithMaterializedDocument extends React.Component<
  Props,
  State
> {
  state = {
    materialized: null
  }

  subscription: ?Subscription

  componentDidMount() {
    this.setDocId(this.props.documentId)
  }

  componentWillReceiveProps(nextProps: Props) {
    if (this.props.documentId !== nextProps.documentId) {
      this.setDocId(nextProps.documentId)
    }
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  unsubscribe() {
    if (this.subscription) {
      this.subscription.unsubscribe()
    }
  }

  setDocId(docId: string) {
    this.unsubscribe()
    if (!docId) {
      this.setState({materialized: null})
      return
    }
    this.subscription = this.props
      .materialize(docId)
      .subscribe(materialized => this.setState({materialized}))
  }

  render() {
    const {materialized} = this.state
    const {children} = this.props
    return materialized ? children(materialized) : null
  }
}


text:
package com.reactnativenavigation;

import android.app.Application;
import android.support.annotation.Nullable;
import android.support.annotation.NonNull;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.reactnativenavigation.react.NavigationReactNativeHost;
import com.reactnativenavigation.react.ReactGateway;
import com.reactnativenavigation.viewcontrollers.externalcomponent.ExternalComponentCreator;

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

public abstract class NavigationApplication extends Application implements ReactApplication {

	private ReactGateway reactGateway;
	public static NavigationApplication instance;
	final Map<String, ExternalComponentCreator> externalComponents = new HashMap<>();

	@Override
	public void onCreate() {
		super.onCreate();
        instance = this;
        reactGateway = createReactGateway();
	}

    /**
     * Subclasses of NavigationApplication may override this method to create the singleton instance
     * of {@link ReactGateway}. For example, subclasses may wish to provide a custom {@link ReactNativeHost}
     * with the ReactGateway. This method will be called exactly once, in the application's {@link #onCreate()} method.
     *
     * Custom {@link ReactNativeHost}s must be sure to include {@link com.reactnativenavigation.react.NavigationPackage}
     *
     * @return a singleton {@link ReactGateway}
     */
	protected ReactGateway createReactGateway() {
	    return new ReactGateway(this, isDebug(), createReactNativeHost());
    }

    protected ReactNativeHost createReactNativeHost() {
        return new NavigationReactNativeHost(this);
    }

	public ReactGateway getReactGateway() {
		return reactGateway;
	}

	@Override
	public ReactNativeHost getReactNativeHost() {
		return getReactGateway().getReactNativeHost();
	}

    /**
     * Generally no need to override this; override for custom permission handling.
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    }

	public abstract boolean isDebug();

    /**
     * Create a list of additional {@link ReactPackage}s to include. This method will only be called by
     * the default implementation of {@link #createReactGateway()}
     */
	@Nullable
	public abstract List<ReactPackage> createAdditionalReactPackages();

    /**
     * Register a native View which can be displayed using the given {@code name}
     * @param name Unique name used to register the native view
     * @param creator Used to create the view at runtime
     */
    @SuppressWarnings("unused")
    public void registerExternalComponent(String name, ExternalComponentCreator creator) {
        if (externalComponents.containsKey(name)) {
            throw new RuntimeException("A component has already been registered with this name: " + name);
        }
        externalComponents.put(name, creator);
    }

    public final Map<String, ExternalComponentCreator> getExternalComponents() {
        return externalComponents;
    }
}


text:
/* eslint-disable prefer-destructuring */
/* eslint-disable no-mixed-operators */
/* eslint-disable import/first */
const url = require('url')
const request = require('request')
const helper = require('apis-helpers')
const cheerio = require('cheerio')
const _ = require('lodash')
const app = require('../../server')

const baseUrl = url.parse('http://dev.phpbin.ja.is/ajax_leit.php')

// return permutation of a given word
function getDeclensions(callback, providedParams) {
  const params = Object.assign({}, providedParams)
  request.get(params, (err, res, body) => {
    if (err || res.statusCode !== 200) {
      return res.status(500).json({
        error: 'A request to dev.phpbin.ja.is resulted in a error',
      })
    }

    let $
    const sanitisedBody = body.replace(/<!--[\s\S]*?-->/g, '')

    try {
      $ = cheerio.load(sanitisedBody)
    } catch (error) {
      return res.status(500).json({
        error: 'Parsing the data from dev.phpbin.ja.is resulted in a error',
        moreinfo: error,
      })
    }

    // Links mean results!
    const result = $('a')

    // more than 1 result from request (ex: 'hús')
    if (result.length > 1) {
      // call recursively again with new url
      const id = result[0].attribs.on_click.match(/\d+/)[0]
      baseUrl.query = { id }
      params.url = url.format(baseUrl)
      return getDeclensions(callback, params)
    }

    // else just call func to return data
    return callback($)
  })
}

// Creates a sequence of integers, each iteration creates a value and increments that value by 1
// step: specify how often to run the iteration
// increment: how much to increment after each iteration
function generateSequence(start, step, increment) {
  // ex:
  // input: start: 0, step: 4, increment: 3
  // output: [ 0, 1, 4, 5, 8, 9, 12, 13 ]
  const results = []

  _.each(_.range(start, step), (i) => {
    const value = (i + increment * i)

    results.push(value, value + 1)
  })

  return results
}

function parseTable($) {
  const type = $('small').contents().text().trim()

  // create a sequence which is the same as the index of 'Eintala' of the td's
  // in the HTML table.
  const singular = generateSequence(0, 4, 3)
  const results = []

  $('table tr td span').each((i, element) => {
    const predicate = (
      element
        .parent
        .parent
        .children
        .filter(node => node.name === 'td')[0]
        .children[0]
        .data
    )

    results.push({
      predicate,
      value: element.children[0].data,
      category: i in singular ? 'Eintala' : 'Fleirtala',
    })
  })

  return { results, type }
}

app.get('/declension/:word', (req, res) => {
  const word = req.params.word
  baseUrl.query = { q: word }

  const params = {
    url: url.format(baseUrl),
    headers: {
      'User-Agent': helper.browser(),
    },
  }

  getDeclensions((body) => {
    return res.cache(86400).json(parseTable(body))
  }, params)
})


text:
//---------------------------------------------------------------------------
// RandomUtils.h
//---------------------------------------------------------------------------

/**
@file RandomUtils.h

@see BaseSubsystems::RandomUtils

@author Alberto Martínez Villarán
@date Abril, 2015
*/

#ifndef __BaseSubsystems_RandomUtils_H
#define __BaseSubsystems_RandomUtils_H

#include <random>
#include <time.h>

namespace BaseSubsystems {

	class RandomUtils
	{

	public:

		/*
		Setea la semilla aleatoria
		*/
		static void setRandomSeed(int seed);

		/*
		Random clásico entre 0 y 1
		*/
		static float Random();

		/*
		Random clásico de rango
		*/
		static int RandomRange(int min, int max);

	protected:

		static std::default_random_engine _generator;

		static int _id;

		static int _seed;

	};

};///BaseSubsystems

#endif


text:
title: "A Plain Markdown Post"
date: "2016-12-30T21:49:57-07:00"
---

This is a post written in plain Markdown (`*.md`) instead of R Markdown (`*.Rmd`). The major differences are:

1. You cannot run any R code in a plain Markdown document, whereas in an R Markdown document, you can embed R code chunks (```` ```{r} ````);
2. A plain Markdown post is rendered through [Blackfriday](https://gohugo.io/overview/configuration/), and an R Markdown document is compiled by [**rmarkdown**](http://rmarkdown.rstudio.com) and [Pandoc](http://pandoc.org).

There are many differences in syntax between Blackfriday's Markdown and Pandoc's Markdown. For example, you can write a task list with Blackfriday but not with Pandoc:

- [x] Write an R package.
- [ ] Write a book.
- [ ] ...
- [ ] Profit!

Similarly, Blackfriday does not support LaTeX math and Pandoc does. I have added the MathJax support to this theme ([hugo-lithium](https://github.com/yihui/hugo-lithium)) but there is a caveat for plain Markdown posts: you have to include math expressions in a pair of backticks (inline: `` `$ $` ``; display style: `` `$$ $$` ``), e.g., `$S_n = \sum_{i=1}^n X_i$`.^[This is because we have to protect the math expressions from being interpreted as Markdown. You may not need the backticks if your math expression does not contain any special Markdown syntax such as underscores or asterisks, but it is always a safer choice to use backticks. When you happen to have a pair of literal dollar signs inside the same element, you can escape one dollar sign, e.g., `\$50 and $100` renders "\$50 and $100".] For R Markdown posts, you do not need the backticks, because Pandoc can identify and process math expressions.

When creating a new post, you have to decide whether the post format is Markdown or R Markdown, and this can be done via the `ext` argument of the function `blogdown::new_post()`, e.g.

```r
blogdown::new_post("Post Title", ext = '.Rmd')
```


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Milesina coniogrammes Hirats.

### Remarks
null


text:
import os
import socket
import struct
import sys
import threading
import time
import urllib

try:
    from SimpleHTTPServer import SimpleHTTPRequestHandler
    from SocketServer import TCPServer
    from urllib import quote
    input = raw_input
except ImportError:
    from http.server import SimpleHTTPRequestHandler
    from socketserver import TCPServer
    from urllib.parse import quote

interactive = False

if len(sys.argv) <= 2:
    # If there aren't enough variables, use interactive mode
    if len(sys.argv) == 2:
        if sys.argv[1].lower() in ('--help', '-help', 'help', 'h', '-h', '--h'):
            print('Usage: ' + sys.argv[0] + ' <target ip> <file / directory> [host ip] [host port]')
            sys.exit(1)

    interactive = True

elif len(sys.argv) < 3 or len(sys.argv) > 6:
    print('Usage: ' + sys.argv[0] + ' <target ip> <file / directory> [host ip] [host port]')
    sys.exit(1)

accepted_extension = ('.cia', '.tik', '.cetk', '.3dsx')
hostPort = 8080 # Default value

if interactive:
    target_ip = input("The IP of your 3DS: ")
    target_path = input("The file you want to send (.cia, .tik, .cetk, or .3dsx): ")

    hostIp = input("Host IP (or press Enter to have the script detect host IP):")
    if hostIp == '':
        print('Detecting host IP...')
        hostIp = [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
    else:
        hostPort = input("Host port (or press Enter to keep default, 8080):")
        if hostPort == '':
            hostPort = 8080 # Default

else:
    # (if the script is being run using a full python path; ex: "path/to/python script_name.py foo foo..")
    if sys.argv[1] == os.path.basename(__file__):
        target_ip = sys.argv[2]
        target_path = sys.argv[3]

        if len(sys.argv) >= 5:
            hostIp = sys.argv[4]
            if len(sys.argv) == 6:
                hostPort = int(sys.argv[5])
        else:
            print('Detecting host IP...')
            hostIp = [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]

    # (if the script is being run using just the script name and default executable for python scripts; ex: "script_name.py foo foo..")
    else:
        target_ip = sys.argv[1]
        target_path = sys.argv[2]

        if len(sys.argv) >= 4:
            hostIp = sys.argv[3]
            if len(sys.argv) == 5:
                hostPort = int(sys.argv[4])
        else:
            print('Detecting host IP...')
            hostIp = [(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]

target_path = target_path.strip()
if not os.path.exists(target_path):
    print(target_path + ': No such file or directory.')
    sys.exit(1)

print('Preparing data...')
baseUrl = hostIp + ':' + str(hostPort) + '/'

if os.path.isfile(target_path):
    if target_path.endswith(accepted_extension):
        file_list_payload = baseUrl + quote(os.path.basename(target_path))
        directory = os.path.dirname(target_path)  # get file directory
    else:
        print('Unsupported file extension. Supported extensions are: ' + accepted_extension)
        sys.exit(1)

else:
    directory = target_path  # it's a directory
    file_list_payload = ''  # init the payload before adding lines
    for file in [file for file in next(os.walk(target_path))[2] if file.endswith(accepted_extension)]:
        file_list_payload += baseUrl + quote(file) + '\n'

if len(file_list_payload) == 0:
    print('No files to serve.')
    sys.exit(1)

file_list_payloadBytes = file_list_payload.encode('ascii')

if directory and directory != '.':  # doesn't need to move if it's already the current working directory
    os.chdir(directory)  # set working directory to the right folder to be able to serve files

print('\nURLs:')
print(file_list_payload + '\n')

class MyServer(TCPServer):
    def server_bind(self):
        import socket
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)

print('Opening HTTP server on port ' + str(hostPort))
server = MyServer(('', hostPort), SimpleHTTPRequestHandler)
thread = threading.Thread(target=server.serve_forever)
thread.start()

try:
    print('Sending URL(s) to ' + target_ip + ' on port 5000...')
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((target_ip, 5000))
    sock.sendall(struct.pack('!L', len(file_list_payloadBytes)) + file_list_payloadBytes)
    while len(sock.recv(1)) < 1:
        time.sleep(0.05)
    sock.close()
except Exception as e:
    print('An error occurred: ' + str(e))
    server.shutdown()
    sys.exit(1)

print('Shutting down HTTP server...')
server.shutdown()


text:
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 1/10/2017
 * Time: 2:38 PM
 */

class Upload_library {

    var $CI = '';

    public function __construct(){
        // khoi tao cho bien sieu doi tuong.
        $this->CI =&get_instance();
    }

    /*
     * ham upload 1 file.
     * @param : duong dan upload file,ten truong file.
     */

    public function upload_file($upload_path,$file){

        // neu khong chuyen vao duong dan upload file hoac ten truong file.
        // return false.

        if(!$upload_path || !$file){
            return false;
        }

        // laod ra thu vien upload cua CI.
        $this->CI->load->library("upload",$this->config($upload_path));
        // thuc hien uplaod file.
        if($this->CI->upload->do_upload($file)){
            // neu upload thanh cong thi tra ve ten cua file upload.
            $data = $this->CI->upload->data();
        }else{
            // tra ve loi neu khong up load  thanh cong.
            $data = $this->CI->upload->display_errors();
        }

        return $data;
    }

    /*
     *  Ham upload nhieu file.
     *  @param : duong dan upload file,ten truong file.
     */

    public function upload_multiple_file($upload_path,$file){

        // neu khong chuyen vao duong dan upload file hoac ten truong file.
        // return false.

        if(!$upload_path || !$file){
            return false;
        }
        // laod ra thu vien upload cua CI.
        $this->CI->load->library("upload",$this->config($upload_path));

        // lay ra  mag chua cac file can upload.
        $list = $_FILES[$file];

        // lay ra kich thuoc mang file.
        $size = count($list['tmp_name']);

        $result_name = array();

        // lap mang file va upload.

        for($i = 0; $i < $size; $i++){

            $_FILES['userfile']['name']    = $list['name'][$i]; // ten file thu i
            $_FILES['userfile']['type']    = $list['type'][$i]; // kieu cua file thu i
            $_FILES['userfile']['tmp_name']    = $list['tmp_name'][$i]; // duong dan tam cua file thu i.
            $_FILES['userfile']['size']    = $list['size'][$i]; // kich thuoc cua file thu i.
            $_FILES['userfile']['error']    = $list['error'][$i];   //khai bao loi cua file thu i

            // thuc hien upload ttung file.
            if($this->CI->upload->do_upload()){
                $data = $this->CI->upload->data();
                $result_name[] = $data['file_name'];
            }else{
                return $this->CI->upload->display_errors();
            }
        }

        return $result_name;
    }

    /*
     *  ham cau hinh cac thong so chung.
     */
    public function config($upload_path){

        $config = array(
            'upload_path' => $upload_path,
            'max_size' => 1024,
            'max_height' => 1024,
            'max_length' => 1024,
            'allowed_types' => "jpg|jpeg|png|gif"
        );
        return $config;
    }
}


text:
package com.zimbra.soap.admin.message;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.zimbra.common.soap.AdminConstants;

/**
 * @zm-api-command-auth-required true
 * @zm-api-command-admin-auth-required true
 * @zm-api-command-description Remove Account Alias
 *

 * Access: domain admin sufficient
 *

 * note: this request is by default proxied to the account's home server
 */
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name=AdminConstants.E_REMOVE_ACCOUNT_ALIAS_REQUEST)
@XmlType(propOrder = {})
public class RemoveAccountAliasRequest {

    /**
     * @zm-api-field-tag value-of-zimbra-id
     * @zm-api-field-description Zimbra ID
     */
    @XmlAttribute(name=AdminConstants.E_ID, required=false)
    private final String id;

    /**
     * @zm-api-field-description Alias
     */
    @XmlAttribute(name=AdminConstants.E_ALIAS, required=true)
    private final String alias;

    /**
     * no-argument constructor wanted by JAXB
     */
     @SuppressWarnings("unused")
    private RemoveAccountAliasRequest() {
        this(null, null);
    }

    public RemoveAccountAliasRequest(String id, String alias) {
        this.id = id;
        this.alias = alias;
    }

    public String getId() { return id; }
    public String getAlias() { return alias; }
}


text:
package com.walkertribe.ian.protocol.core.eng;

import com.walkertribe.ian.enums.Origin;
import com.walkertribe.ian.iface.PacketReader;
import com.walkertribe.ian.iface.PacketWriter;
import com.walkertribe.ian.protocol.BaseArtemisPacket;
import com.walkertribe.ian.protocol.Packet;
import com.walkertribe.ian.protocol.core.CorePacketType;
import com.walkertribe.ian.util.GridCoord;

/**
 * Send a DAMCON team to a grid location.
 * @author dhleong
 */
@Packet(origin = Origin.CLIENT, type = CorePacketType.VALUE_FOUR_INTS, subtype = 0x04)
public class EngSendDamconPacket extends BaseArtemisPacket {
    private int mTeamNumber;
    private GridCoord mCoord;

    /**
     * Send the team to grid node at x,y,z.
     * @param teamNumber int [0, TEAMS) where TEAMS is probably 3
     * @param x Destination X-coordinate in the system grid
     * @param y Destination Y-coordinate in the system grid
     * @param z Destination Z-coordinate in the system grid
     */
    public EngSendDamconPacket(int teamNumber, int x, int y, int z) {
    	this(teamNumber, GridCoord.get(x, y, z));
    }

    /**
     * @param teamNumber int [0, TEAMS) where TEAMS is probably 3
     * @param coord Destination coordinates in the system grid
     */
    public EngSendDamconPacket(int teamNumber, GridCoord coord) {
        if (teamNumber < 0) {
        	throw new IllegalArgumentException(
        			"DAMCON team number can't be less than 0"
        	);
        }

        mTeamNumber = teamNumber;
        mCoord = coord;
    }

    public EngSendDamconPacket(PacketReader reader) {
        reader.skip(4); // subtype
        mTeamNumber = reader.readInt();
        mCoord = GridCoord.get(reader.readInt(), reader.readInt(), reader.readInt());
    }

    /**
     * The number identifying this DAMCON team.
     */
    public int getTeamNumber() {
    	return mTeamNumber;
    }

    /**
     * The grid coordinates to which this DAMCON team is travelling.
     */
    public GridCoord getDestination() {
    	return mCoord;
    }

	@Override
	protected void writePayload(PacketWriter writer) {
		writer	.writeInt(0x04) // subtype
				.writeInt(mTeamNumber)
				.writeInt(mCoord.x())
				.writeInt(mCoord.y())
				.writeInt(mCoord.z());
	}

	@Override
	protected void appendPacketDetail(StringBuilder b) {
		b.append("Team #").append(mTeamNumber).append(" to ").append(mCoord);
	}
}