text:
package com.playtika.test.keycloak.util;

import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED;

public final class KeycloakClient {

    private final Environment environment;
    private final RestTemplate restTemplate;

    private KeycloakClient(Environment environment) {
        this.environment = environment;
        this.restTemplate = new RestTemplate();
    }

    public static KeycloakClient newKeycloakClient(Environment environment) {
        return new KeycloakClient(requireNonNull(environment));
    }

    public KeyCloakToken keycloakToken() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", fromEnv("testing.keycloak.client"));
        map.add("client_secret", fromEnv("testing.keycloak.client-secret"));
        map.add("grant_type", "password");
        map.add("username", fromEnv("testing.keycloak.username"));
        map.add("password", fromEnv("testing.keycloak.password"));

        String url = format("%s/realms/%s/protocol/openid-connect/token", baseUrl(), realm());
        return restTemplate.postForObject(url, new HttpEntity<>(map, headers), KeyCloakToken.class);
    }

    public String baseUrl() {
        return fromEnv("embedded.keycloak.auth-server-url");
    }

    public String realm() {
        return fromEnv("testing.keycloak.realm");
    }

    public RealmInfo getRealmInfo(String realm) {
        return restTemplate.getForObject(
            format("%s/realms/%s", baseUrl(), requireNonNull(realm)),
            RealmInfo.class);
    }

    private String fromEnv(String key) {
        return environment.getProperty(requireNonNull(key));
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- $Id: block_basic_1.xml 627324 2008-02-13 09:35:01Z maxberger $ -->
<testcase>
  <info>
    <p>
      This test checks the visibility trait.
    </p>
  </info>
  <fo>
    <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:svg="http://www.w3.org/2000/svg">
      <fo:layout-master-set>
        <fo:simple-page-master master-name="normal" page-width="5in" page-height="5in">
          <fo:region-body/>
        </fo:simple-page-master>
      </fo:layout-master-set>
      <fo:page-sequence master-reference="normal" white-space-collapse="true">
        <fo:flow flow-name="xsl-region-body">
          <fo:block>test1</fo:block>
          <fo:block visibility="hidden">hidden</fo:block>
        </fo:flow>
      </fo:page-sequence>
    </fo:root>
  </fo>
  <checks>
    <!-- Check for first paragraph -->
    <eval expected="360000" xpath="/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[1]/@ipd"/>
    <eval expected="14400" xpath="/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[1]/@bpd"/>
	<eval expected="visible" xpath="/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[1]/@visibility"/>
    <!-- Check for second paragraph -->
    <eval expected="360000" xpath="/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[2]/@ipd"/>
    <eval expected="14400" xpath="/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[2]/@bpd"/>
	<eval expected="hidden" xpath="/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[2]/@visibility"/>
	<eval expected="0" xpath="count(/areaTree/pageSequence/pageViewport/page[1]/regionViewport/regionBody/mainReference/span/flow/block[2]/*)"/>
  </checks>
</testcase>


text:
@implementation CBUUID (UUIDString)

- (NSString*) UUIDStringFromData
{
    NSData *data = [self data];

    NSUInteger bytesToConvert = [data length];
    const unsigned char *uuidBytes = [data bytes];
    NSMutableString *outputString = [NSMutableString stringWithCapacity:16];

    for (NSUInteger currentByteIndex = 0; currentByteIndex < bytesToConvert; currentByteIndex++) {
        switch (currentByteIndex) {
            case 3:
            case 5:
            case 7:
            case 9:[outputString appendFormat:@"%02x-", uuidBytes[currentByteIndex]]; break;
            default:[outputString appendFormat:@"%02x", uuidBytes[currentByteIndex]];
        }
    }

    return outputString;
}

// Generate the 128 bit UUIDString. If the UUID is 16 bit, it will be prefilled to 128 bit.
- (NSString *)fullUUIDString;
{
    NSString* outputString;
    if ([self respondsToSelector:@selector(UUIDString)]) {
        outputString = [self UUIDString];
    } else {
        outputString = [self UUIDStringFromData];
    }

    if ([outputString length] == 4) {
        // Convert 16 bits UUID to 128 bits UUID. Reference: http://en.wikipedia.org/wiki/Bluetooth_low_energy#Identifiers
        outputString = [NSString stringWithFormat:@"0000%@-0000-1000-8000-00805F9B34FB", outputString];
    }

    return [outputString lowercaseString];
}

@end
#pragma mark ChromeBluetooth interface

@interface ChromeBluetooth() <CBCentralManagerDelegate> {
    CBCentralManager* _centralManager;
    NSMutableDictionary* _peripherals;
    NSMutableSet* _activePeripherals;

    NSString* _bluetoothCallbackId;
    NSString* _bluetoothLowEnergyCallbackId;

    BOOL _isScanning;
    NSTimer* _removedDeviceTimer;
}
#pragma mark chrome.bluetooth interface

- (void)getAdapterState:(CDVInvokedUrlCommand*)command;
- (void)getDevice:(CDVInvokedUrlCommand*)command;
- (void)getDevices:(CDVInvokedUrlCommand*)command;
- (void)startDiscovery:(CDVInvokedUrlCommand*)command;
- (void)stopDiscovery:(CDVInvokedUrlCommand*)command;
- (void)registerBluetoothEvents:(CDVInvokedUrlCommand*)command;

- (void)sendDeviceChangedEvent:(NSDictionary*)deviceInfo;
- (void)sendServiceAddedEvent:(NSDictionary*)serviceInfo;
- (void)sendServiceChangedEvent:(NSDictionary*)serviceInfo;
- (void)sendServiceRemovedEvent:(NSDictionary*)serviceInfo;
- (void)sendCharacteristicValueChangedEvent:(NSArray*)characteristicInfo;
- (void)sendDescriptorValueChangedEvent:(NSArray*)descriptroInfo;
- (void)disconnectPeripheral:(CBPeripheral*)peripheral;

@end

#pragma mark ChromeBluetoothPeripheral interface

@interface ChromeBluetoothPeripheral : NSObject<CBPeripheralDelegate> {
    @public
    __weak ChromeBluetooth* _plugin;
    CBPeripheral* _peripheral;
    NSDictionary* _adData;
    NSNumber* _RSSI;

    // <InstanceId, CBService>
    NSMutableDictionary* _knownServices;
    // <InstanceId, CBCharacteristic>
    NSMutableDictionary* _knownCharacteristics;
    // <InstanceId, CBDescriptor>
    NSMutableDictionary* _knownDescriptors;

    id _connectCallback;
    id _disconnectCallback;

    NSMutableDictionary* _getIncludedServicesCallbacks;
    NSMutableDictionary* _getCharacteristicsCallbacks;
    NSMutableDictionary* _getDescriptorsCallbacks;
    NSMutableDictionary* _readCharacteristicValueCallbacks;
    NSMutableDictionary* _writeCharacteristicValueCallbacks;
    NSMutableDictionary* _startCharacteristicNotificationCallbacks;
    NSMutableDictionary* _stopCharacteristicNotificationCallbacks;
    NSMutableDictionary* _readDescriptorValueCallbacks;
    NSMutableDictionary* _writeDescriptorValueCallbacks;
}

@end

@implementation ChromeBluetoothPeripheral

- (ChromeBluetoothPeripheral*)initWithPeripheral:(CBPeripheral*)thePeripheral adData:(NSDictionary*)theAdData RSSI:(NSNumber*)RSSI plugin:(ChromeBluetooth*)thePlugin
{
    self = [super init];
    if (self) {
        _peripheral = thePeripheral;
        [_peripheral setDelegate:self];
        _plugin = thePlugin;
        _adData = theAdData;
        _RSSI = RSSI;

        _knownServices = [NSMutableDictionary dictionary];
        _knownCharacteristics = [NSMutableDictionary dictionary];
        _knownDescriptors = [NSMutableDictionary dictionary];

        _getIncludedServicesCallbacks = [NSMutableDictionary dictionary];
        _getCharacteristicsCallbacks = [NSMutableDictionary dictionary];
        _getDescriptorsCallbacks = [NSMutableDictionary dictionary];
        _readCharacteristicValueCallbacks = [NSMutableDictionary dictionary];
        _writeCharacteristicValueCallbacks = [NSMutableDictionary dictionary];
        _startCharacteristicNotificationCallbacks = [NSMutableDictionary dictionary];
        _stopCharacteristicNotificationCallbacks = [NSMutableDictionary dictionary];
        _readDescriptorValueCallbacks = [NSMutableDictionary dictionary];
        _writeDescriptorValueCallbacks = [NSMutableDictionary dictionary];
    }
    return self;
}

+ (NSString*)peripheralAddressFromUUID:(NSUUID*)identifier
{
    // TODO: find a way function to hash an UUIDString to a bluetooth address.
    // Device address should be a MAC address in format of "xx:xx:xx:xx:xx:xx",
    // and we can not get this information from iOS. We want to fake this by map
    // each UUID to a unique fake MAC address.
    return identifier.UUIDString;
}

- (NSString*)peripheralAddress
{
    return [ChromeBluetoothPeripheral peripheralAddressFromUUID:_peripheral.identifier];
}

- (NSString*)serviceIdFromService:(CBService*)service
{
    return [NSString stringWithFormat:@"%@/%@", [self peripheralAddress], [service.UUID fullUUIDString]];
}

- (NSString*)characteristicIdFromCharacteristic:(CBCharacteristic*)characteristic
{
    return [NSString stringWithFormat:@"%@/%@/%@", [self peripheralAddress], [characteristic.service.UUID fullUUIDString], [characteristic.UUID fullUUIDString]];
}

- (NSString*)descriptorIdFromDescriptor:(CBDescriptor*)descriptor
{
    return [NSString stringWithFormat:@"%@/%@/%@/%@", [self peripheralAddress], [descriptor.characteristic.service.UUID fullUUIDString], [descriptor.characteristic.UUID fullUUIDString], [descriptor.UUID fullUUIDString]];
}

- (BOOL)isConnected
{
    return _peripheral.state == CBPeripheralStateConnected;
}

- (NSDictionary*)getDeviceInfo
{
    NSMutableDictionary* deviceInfo = [@{
        @"address": [self peripheralAddress],
        @"connected": [NSNumber numberWithBool:[_peripheral state] == CBPeripheralStateConnected],
    } mutableCopy];

    NSString* name = [_peripheral name];
    if (name) {
        deviceInfo[@"name"] = name;
    }

    NSMutableSet* serviceUuids = [NSMutableSet set];

    NSArray* adServices = _adData[CBAdvertisementDataServiceUUIDsKey];
    if (adServices && [adServices count] > 0) {
        for (CBUUID* serviceUuid in adServices) {
            [serviceUuids addObject:[serviceUuid fullUUIDString]];
        }
    }

    NSArray* services = [_peripheral services];
    if (services && [services count] > 0) {
        for (CBService* service in services) {
            [serviceUuids addObject:[service.UUID fullUUIDString]];
        }
    }

    deviceInfo[@"uuids"] = [serviceUuids allObjects];
    deviceInfo[@"rssi"] = _RSSI;

    if (_adData[CBAdvertisementDataTxPowerLevelKey]) {
        deviceInfo[@"tx_power"] = _adData[CBAdvertisementDataTxPowerLevelKey];
    }

    NSDictionary* serviceDataInfo = _adData[CBAdvertisementDataServiceDataKey];
    if (serviceDataInfo) {
        for (CBUUID* serviceDataUuid in serviceDataInfo) {
            deviceInfo[@"serviceDataUuid"] = [serviceDataUuid fullUUIDString];
            deviceInfo[@"serviceData"] = [serviceDataInfo[serviceDataUuid] base64EncodedString];
        }
    }

    return deviceInfo;
}

- (NSDictionary*)buildServiceInfo:(CBService*)service
{
    NSString* serviceId = [self serviceIdFromService:service];

    if (!_knownServices[serviceId]) {
        _knownServices[serviceId] = service;
    }

    return @{
        @"uuid": [service.UUID fullUUIDString],
        @"deviceAddress": [self peripheralAddress],
        @"instanceId": serviceId,
        @"isPrimary": [NSNumber numberWithBool:service.isPrimary],
    };
}

- (NSDictionary*)getServiceInfoByServiceId:(NSString*)serviceId
{
    CBService* service = _knownServices[serviceId];
    if (service) {
        return [self buildServiceInfo:service];
    }
    return nil;
}

- (NSArray*)getServicesInfo
{
    NSMutableArray* servicesInfo = [NSMutableArray array];

    for (CBService* service in _peripheral.services) {
        [servicesInfo addObject:[self buildServiceInfo:service]];
    }
    return servicesInfo;
}

- (BOOL)discoveryIncludedServicesByServiceId:(NSString*)serviceId
{
    CBService* service = _knownServices[serviceId];
    if (service) {
        [_peripheral discoverIncludedServices:nil forService:service];
        return YES;
    }
    return NO;
}

- (NSDictionary*)buildCharacteristicInfo:(CBCharacteristic*)characteristic
{
    NSString* characteristicId = [self characteristicIdFromCharacteristic:characteristic];

    if (!_knownCharacteristics[characteristicId]) {
        _knownCharacteristics[characteristicId] = characteristic;
        if (characteristic.service) {
            [_plugin sendServiceChangedEvent:[self buildServiceInfo:characteristic.service]];
        }
    }

    NSMutableArray* properties = [NSMutableArray array];

    if (characteristic.properties & CBCharacteristicPropertyBroadcast) {
        [properties addObject:@"broadcast"];
    }

    if (characteristic.properties & CBCharacteristicPropertyRead) {
        [properties addObject:@"read"];
    }

    if (characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) {
        [properties addObject:@"writeWithoutResponse"];
    }

    if (characteristic.properties & CBCharacteristicPropertyWrite) {
        [properties addObject:@"write"];
    }

    if (characteristic.properties & CBCharacteristicPropertyNotify) {
        [properties addObject:@"notify"];
    }

    if (characteristic.properties & CBCharacteristicPropertyIndicate) {
        [properties addObject:@"indicate"];
    }

    if (characteristic.properties & CBCharacteristicPropertyAuthenticatedSignedWrites) {
        [properties addObject:@"authenticatedSignedWrites"];
    }

    if (characteristic.properties & CBCharacteristicPropertyExtendedProperties) {
        [properties addObject:@"extendedProperties"];
    }

    return @{
        @"uuid": [characteristic.UUID fullUUIDString],
        @"service": [self buildServiceInfo:characteristic.service],
        @"properties": properties,
        @"instanceId": characteristicId,
    };
}

- (NSData*)getCharacteristicValueByCharacteristicId:(NSString*)characteristicId
{
    CBCharacteristic* characteristic = _knownCharacteristics[characteristicId];

    if (characteristic) {
        return characteristic.value;
    }

    return nil;
}

- (NSDictionary*)getCharacteristicInfoByCharacteristicId:(NSString*)characteristicId
{
    CBCharacteristic* characteristic = _knownCharacteristics[characteristicId];

    if (characteristic) {
        return [self buildCharacteristicInfo:characteristic];
    }
    return nil;
}

- (BOOL)discoveryCharacteristicsByServiceId:(NSString*)serviceId
{
    CBService* service = _knownServices[serviceId];
    if (service) {
        [_peripheral discoverCharacteristics:nil forService:service];
        return YES;
    }
    return NO;
}

- (BOOL)readCharacteristicValueByCharacteristicId:(NSString*)characteristicId
{
    CBCharacteristic* characteristic = _knownCharacteristics[characteristicId];
    if (characteristic) {
        [_peripheral readValueForCharacteristic:characteristic];
        return YES;
    }
    return NO;
}

- (BOOL)writeCharacteristicValueByCharacteristicId:(NSString*)characteristicId value:(NSData*)value
{
    CBCharacteristic* characteristic = _knownCharacteristics[characteristicId];
    if (characteristic) {
        CBCharacteristicWriteType type = CBCharacteristicWriteWithResponse;
        if (characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse)
            type = CBCharacteristicWriteWithoutResponse;

        [_peripheral writeValue:value forCharacteristic:characteristic type:type];
        return YES;
    }
    return NO;
}

- (BOOL)setCharacteristicNotificationValue:(BOOL)enabled CharacteristicId:(NSString*)characteristicId
{
    CBCharacteristic* characteristic = _knownCharacteristics[characteristicId];
    if (characteristic) {
        [_peripheral setNotifyValue:enabled forCharacteristic:characteristic];
        return YES;
    }
    return NO;
}

- (NSDictionary*)buildDescriptorInfo:(CBDescriptor*)descriptor
{
    NSString* descriptorId = [self descriptorIdFromDescriptor:descriptor];

    if (!_knownDescriptors[descriptorId]) {
        _knownDescriptors[descriptorId] = descriptor;
    }

    return @{
        @"uuid": [descriptor.UUID fullUUIDString],
        @"characteristic": [self buildCharacteristicInfo:descriptor.characteristic],
        @"instanceId": descriptorId,
    };
}

- (NSData*)getDescriptorValueByDescriptorId:(NSString*)descriptorId
{
    CBDescriptor* descriptor = _knownDescriptors[descriptorId];

    if (descriptor) {
        return descriptor.value;
    }

    return nil;
}

- (NSDictionary*)getDescriptorInfoByDescriptorId:(NSString*)descriptorId
{
    CBDescriptor* descriptor = _knownDescriptors[descriptorId];

    if (descriptor) {
        return [self buildDescriptorInfo:descriptor];
    }

    return nil;
}

- (BOOL)discoveryDescriptorByCharacteristicId:(NSString*)characteristicId
{
    CBCharacteristic* characteristic = _knownCharacteristics[characteristicId];
    if (characteristic) {
        [_peripheral discoverDescriptorsForCharacteristic:characteristic];
        return YES;
    }
    return NO;
}

- (BOOL)readDescriptorValueByDescriptorId:(NSString*)descriptorId
{
    CBDescriptor* descriptor = _knownDescriptors[descriptorId];
    if (descriptor) {
        [_peripheral readValueForDescriptor:descriptor];
        return YES;
    }
    return NO;
}

- (BOOL)writeDescriptorValueByDescriptorId:(NSString*)descriptorId value:(NSData*)value
{
    CBDescriptor* descriptor = _knownDescriptors[descriptorId];
    if (descriptor) {
        [_peripheral writeValue:value forDescriptor:descriptor];
        return YES;
    }
    return NO;
}

- (void)cleanup
{
    if (!_peripheral.isConnected) {
        return;
    }

    for (CBService* service in _peripheral.services) {
        for (CBCharacteristic* characteristic in service.characteristics) {
            if (characteristic.isNotifying) {
                [_peripheral setNotifyValue:NO forCharacteristic:characteristic];
            }
        }
        [_plugin sendServiceRemovedEvent:[self buildServiceInfo:service]];
    }

    [_plugin disconnectPeripheral:_peripheral];
    return;
}

- (void)callAndClear:(NSMutableDictionary*)blocks withInstanceId:(NSString*)instanceId array:(NSArray*)array error:(NSError*)error
{
    void (^callback)(NSArray*, NSError*) = blocks[instanceId];
    if (callback != nil) {
        [blocks removeObjectForKey:instanceId];
        callback(array, error);
    }
}

- (void)callAndClear:(NSMutableDictionary*)blocks withInstanceId:(NSString *)instanceId error:(NSError *)error
{
    void (^callback)(NSError*) = blocks[instanceId];
    if (callback != nil) {
        [blocks removeObjectForKey:instanceId];
        callback(error);
    }
}

# pragma mark CBPeripheralDelegate methods

// Note: this delegate does not work correctly for cached device.
// See: http://stackoverflow.com/questions/13180134/corebluetooth-refreshing-local-name-of-an-already-discovered-peripheral
- (void)peripheralDidUpdateName:(CBPeripheral *)peripheral
{
    [_plugin sendDeviceChangedEvent:[self getDeviceInfo]];
}

- (void)peripheral:(CBPeripheral *)peripheral didModifyServices:(NSArray *)invalidatedServices
{
    for (CBService* service in invalidatedServices) {
        [_plugin sendServiceRemovedEvent:[self buildServiceInfo:service]];
        [_knownServices removeObjectForKey:[self serviceIdFromService:service]];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    for (CBService* service in peripheral.services) {
        [_plugin sendServiceAddedEvent:[self buildServiceInfo:service]];
    }

    [_plugin sendDeviceChangedEvent:[self getDeviceInfo]];
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverIncludedServicesForService:(CBService *)service error:(NSError *)error
{
    NSMutableArray* includedServicesInfo = [NSMutableArray array];
    for (CBService* includedService in service.includedServices) {
        NSDictionary* serviceInfo = [self buildServiceInfo:includedService];
        [includedServicesInfo addObject:serviceInfo];
    }

    NSString* serviceId = [self serviceIdFromService:service];
    [self callAndClear:_getIncludedServicesCallbacks withInstanceId:serviceId array:includedServicesInfo error:error];
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSMutableArray* characteristicsInfo = [NSMutableArray array];
    for (CBCharacteristic* characteristic in service.characteristics) {
        NSDictionary* characteristicInfo = [self buildCharacteristicInfo:characteristic];
        [characteristicsInfo addObject:characteristicInfo];
    }

    NSString* serviceId = [self serviceIdFromService:service];
    [self callAndClear:_getCharacteristicsCallbacks withInstanceId:serviceId array:characteristicsInfo error:error];
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSDictionary* characteristicInfo = [self buildCharacteristicInfo:characteristic];
    NSMutableArray* multipartMessage = [@[
        characteristicInfo[@"uuid"],
        characteristicInfo[@"service"],
        characteristicInfo[@"properties"],
        characteristicInfo[@"instanceId"],
    ] mutableCopy];

    if (characteristic.value) {
        [multipartMessage addObject:characteristic.value];
    }

    NSString* characteristicId = [self characteristicIdFromCharacteristic:characteristic];
    [self callAndClear:_readCharacteristicValueCallbacks withInstanceId:characteristicId array:multipartMessage error:error];

    if (characteristic.isNotifying) {
        [_plugin sendCharacteristicValueChangedEvent:multipartMessage];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSString* characteristicId = [self characteristicIdFromCharacteristic:characteristic];
    [self callAndClear:_writeCharacteristicValueCallbacks withInstanceId:characteristicId error:error];
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSString* characteristicId = [self characteristicIdFromCharacteristic:characteristic];
    if (characteristic.isNotifying) { // start notification
        [self callAndClear:_startCharacteristicNotificationCallbacks withInstanceId:characteristicId error:error];
    } else { // stop notification
        [self callAndClear:_stopCharacteristicNotificationCallbacks withInstanceId:characteristicId error:error];
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSMutableArray* descriptorsInfo = [NSMutableArray array];
    for (CBDescriptor* descriptor in characteristic.descriptors) {
        [descriptorsInfo addObject:[self buildDescriptorInfo:descriptor]];
    }

    NSString* characteristicId = [self characteristicIdFromCharacteristic:characteristic];
    [self callAndClear:_getDescriptorsCallbacks withInstanceId:characteristicId array:descriptorsInfo error:error];
}

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
    NSDictionary* descriptorInfo = [self buildDescriptorInfo:descriptor];

    NSMutableArray* multipartMessage = [@[
        descriptorInfo[@"uuid"],
        descriptorInfo[@"characteristic"],
        descriptorInfo[@"instanceId"],
    ] mutableCopy];

    if (descriptor.value) {
        [multipartMessage addObject:descriptor.value];
    }

    NSString* descriptorId = [self descriptorIdFromDescriptor:descriptor];
    [self callAndClear:_readDescriptorValueCallbacks withInstanceId:descriptorId array:multipartMessage error:error];

    [_plugin sendDescriptorValueChangedEvent:multipartMessage];
}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
    NSString* descriptorId = [self descriptorIdFromDescriptor:descriptor];

    [self callAndClear:_writeCharacteristicValueCallbacks withInstanceId:descriptorId error:error];
}

@end

@implementation ChromeBluetooth

- (void)pluginInitialize
{
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
    _peripherals = [NSMutableDictionary dictionary];
    _activePeripherals = [NSMutableSet set];
    _isScanning = NO;
}

#pragma mark chrome.bluetooth implementations
- (NSDictionary*)getAdapterStateInfo
{
    BOOL isPoweredOn = NO;

    if (_centralManager.state == CBCentralManagerStatePoweredOn) {
        isPoweredOn = YES;
    }

    return @{
        @"name": [[UIDevice currentDevice] name],
        // getifaddrs() returns 02:00:00:00:00:00 since iOS7
        @"address": @"02:00:00:00:00:00",
        @"discovering": [NSNumber numberWithBool:_isScanning],
        @"available": [NSNumber numberWithBool:isPoweredOn],
        @"powered": [NSNumber numberWithBool:isPoweredOn],
    };
}

- (void)getAdapterState:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[self getAdapterStateInfo]] callbackId:command.callbackId];

}

- (void)getDevice:(CDVInvokedUrlCommand*)command
{
    NSString* deviceAddress = [command argumentAtIndex:0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:[chromePeripheral getDeviceInfo]] callbackId:command.callbackId];
    } else {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)getDevices:(CDVInvokedUrlCommand*)command
{
    NSArray *allPeripherals = [_peripherals allValues];
    NSMutableArray *allDeviceInfo = [NSMutableArray array];

    for (ChromeBluetoothPeripheral* peripheral in allPeripherals) {
        [allDeviceInfo addObject:[peripheral getDeviceInfo]];
    }

    [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:allDeviceInfo] callbackId:command.callbackId];
}

- (void)startDiscovery:(CDVInvokedUrlCommand *)command
{
    if (!_isScanning) {
        [_centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO}];
        [_removedDeviceTimer invalidate];
        _removedDeviceTimer = [NSTimer scheduledTimerWithTimeInterval:REMOVED_DEVICE_CHECKING_INTERVAL target:self selector:@selector(checkRemovedDevice:) userInfo:nil repeats:YES];
        _isScanning = YES;
        [self sendAdapterStateChangedEvent:[self getAdapterStateInfo]];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
    } else {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Bluetooth adapter is scanning"] callbackId:command.callbackId];
    }
}

- (void)stopDiscovery:(CDVInvokedUrlCommand *)command
{
    if (_isScanning) {
        [_removedDeviceTimer invalidate];
        [_centralManager stopScan];
        [_activePeripherals removeAllObjects];
        _isScanning = NO;
        [self sendAdapterStateChangedEvent:[self getAdapterStateInfo]];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
    } else {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Bluetooth adapter is not scanning"] callbackId:command.callbackId];
    }
}

- (void)restartScanner
{
    if (_isScanning) {
        [_centralManager stopScan];
        [_centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO}];
    }
}

- (void)registerBluetoothEvents:(CDVInvokedUrlCommand *)command
{
    _bluetoothCallbackId = command.callbackId;
}

- (void)sendAdapterStateChangedEvent:(NSDictionary*)adapterStateInfo
{
    NSArray* eventResult = @[@"onAdapterStateChanged", adapterStateInfo];
    CDVPluginResult* adapterStateChangedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [adapterStateChangedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:adapterStateChangedResult callbackId:_bluetoothCallbackId];
}

- (void)sendDeviceAddedEvent:(NSDictionary*)deviceInfo
{
    NSArray* eventResult = @[@"onDeviceAdded", deviceInfo];
    CDVPluginResult* deviceAddedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [deviceAddedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:deviceAddedResult callbackId:_bluetoothCallbackId];
}

- (void)sendDeviceChangedEvent:(NSDictionary*)deviceInfo
{
    NSArray* eventResult = @[@"onDeviceChanged", deviceInfo];
    CDVPluginResult* deviceChangedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [deviceChangedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:deviceChangedResult callbackId:_bluetoothCallbackId];
}

- (void)sendDeviceRemovedEvent:(NSDictionary*)deviceInfo
{
    NSArray* eventResult = @[@"onDeviceRemoved", deviceInfo];
    CDVPluginResult* deviceRemovedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [deviceRemovedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:deviceRemovedResult callbackId:_bluetoothCallbackId];
}

// There is no remove device events on iOS. This method checks whether some devices did not advertise
// in a fixed period of time, and declare the device is removed.
// We are polling the bluetooth advertisement data and schedule this method at a fixed rate; therefore,
// it will be more efficient if we don't send remove event.
- (void)checkRemovedDevice:(id)sender
{
    NSArray* activeDeviceAddrs = [_activePeripherals allObjects];
    NSMutableArray* removedDeviceAddrs = [[_peripherals allKeys] mutableCopy];
    [removedDeviceAddrs removeObjectsInArray:activeDeviceAddrs];
    [_activePeripherals removeAllObjects];

    for (NSString* deviceAddr in removedDeviceAddrs) {
        ChromeBluetoothPeripheral* peripheral = _peripherals[deviceAddr];
        [self sendDeviceRemovedEvent:[peripheral getDeviceInfo]];
        [peripheral cleanup];
        [_peripherals removeObjectForKey:deviceAddr];
    }
    [self restartScanner];
}

- (void)callAndClear:(__strong id*)block withError:(NSError*)error
{
    void (^callback)(NSError*) = *block;
    if (callback != nil) {
        *block = nil;
        callback(error);
    }
}

#pragma mark CBCentralManagerDelegate methods

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    [self sendAdapterStateChangedEvent:[self getAdapterStateInfo]];

    if (_centralManager.state != CBCentralManagerStatePoweredOn) {
        for (NSString* address in _peripherals) {
            [_peripherals[address] cleanup];
        }
        [_peripherals removeAllObjects];
    }
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSString* address = [ChromeBluetoothPeripheral peripheralAddressFromUUID:peripheral.identifier];
    [_activePeripherals addObject:address];

    ChromeBluetoothPeripheral* foundPeripheral = _peripherals[address];
    if (foundPeripheral) {
        foundPeripheral->_adData = advertisementData;
        foundPeripheral->_RSSI = RSSI;
        return;
    }

    ChromeBluetoothPeripheral* chromePeripheral = [[ChromeBluetoothPeripheral alloc] initWithPeripheral:peripheral adData:advertisementData RSSI:RSSI plugin:self];

    _peripherals[address] = chromePeripheral;

    [self sendDeviceAddedEvent:[chromePeripheral getDeviceInfo]];
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[[ChromeBluetoothPeripheral peripheralAddressFromUUID:peripheral.identifier]];
    if (!chromePeripheral)
        return;

    VERBOSE_LOG(@"Device %@ connected", [chromePeripheral peripheralAddress]);

    [self sendDeviceChangedEvent:[chromePeripheral getDeviceInfo]];

    [peripheral discoverServices:nil];

    [self callAndClear:&(chromePeripheral->_connectCallback) withError:nil];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[[ChromeBluetoothPeripheral peripheralAddressFromUUID:peripheral.identifier]];
    if (!chromePeripheral)
        return;

    [self callAndClear:&(chromePeripheral->_connectCallback) withError:error];
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[[ChromeBluetoothPeripheral peripheralAddressFromUUID:peripheral.identifier]];
    if (!chromePeripheral)
        return;

    VERBOSE_LOG(@"Device %@ disconnected", [chromePeripheral peripheralAddress]);

    [self sendDeviceChangedEvent:[chromePeripheral getDeviceInfo]];

    [self callAndClear:&(chromePeripheral->_disconnectCallback) withError:error];
}

#pragma mark chrome.bluetoothLowEnergy implementations

- (void)connect:(CDVInvokedUrlCommand*)command
{
    NSString* deviceAddress = [command argumentAtIndex:0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];
    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    NSNumber* isConnectable = chromePeripheral->_adData[CBAdvertisementDataIsConnectable];
    if (isConnectable && ![isConnectable boolValue]) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Device is not connectable"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_connectCallback = [^(NSError* error) {
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
        }
    } copy];

    [_centralManager connectPeripheral:chromePeripheral->_peripheral options:nil];
}

- (void)disconnectPeripheral:(CBPeripheral *)peripheral
{
    [_centralManager cancelPeripheralConnection:peripheral];
}

- (void)disconnect:(CDVInvokedUrlCommand*)command
{
    NSString* deviceAddress = [command argumentAtIndex:0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];
    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_disconnectCallback = [^(NSError* error) {
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
        }
    } copy];

    [chromePeripheral cleanup];
    [self disconnectPeripheral:chromePeripheral->_peripheral];
}

- (void)getService:(CDVInvokedUrlCommand*)command
{
    NSString* serviceId = [command argumentAtIndex:0];
    NSString* deviceAddress = [serviceId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral.isConnected) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Bluetooth is not connected"] callbackId:command.callbackId];
        return;
    }

    NSDictionary *serviceInfo = [chromePeripheral getServiceInfoByServiceId:serviceId];

    if (serviceInfo) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:serviceInfo] callbackId:command.callbackId];
    } else {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)getServices:(CDVInvokedUrlCommand*)command
{
    NSString* deviceAddress = [command argumentAtIndex:0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];
    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[chromePeripheral getServicesInfo]] callbackId:command.callbackId];
}

- (void)getCharacteristic:(CDVInvokedUrlCommand*)command
{
    NSString* characteristicId = [command argumentAtIndex:0];
    NSString* deviceAddress = [characteristicId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    NSDictionary* characteristicInfo = [chromePeripheral getCharacteristicInfoByCharacteristicId:characteristicId];
    NSData* characteristicValue = [chromePeripheral getCharacteristicValueByCharacteristicId:characteristicId];

    if (!characteristicInfo) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    NSMutableArray* multipartMessage = [@[
        characteristicInfo[@"uuid"],
        characteristicInfo[@"service"],
        characteristicInfo[@"properties"],
        characteristicInfo[@"instanceId"],
    ] mutableCopy];

    if (characteristicValue) {
        [multipartMessage addObject:multipartMessage];
    }

    [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:multipartMessage] callbackId:command.callbackId];
}

- (void)getCharacteristics:(CDVInvokedUrlCommand*)command
{
    NSString* serviceId = [command argumentAtIndex:0];
    NSString* deviceAddress = [serviceId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_getCharacteristicsCallbacks[serviceId] = [^(NSArray* characteristicsInfo, NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:characteristicsInfo] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral discoveryCharacteristicsByServiceId:serviceId]) {
        [chromePeripheral->_getCharacteristicsCallbacks removeObjectForKey:serviceId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)getIncludedServices:(CDVInvokedUrlCommand*)command
{
    NSString* serviceId = [command argumentAtIndex:0];
    NSString* deviceAddress = [serviceId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_getIncludedServicesCallbacks[serviceId] = [^(NSArray* includedServicesInfo, NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:includedServicesInfo] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral discoveryIncludedServicesByServiceId:serviceId]) {
        [chromePeripheral->_getIncludedServicesCallbacks removeObjectForKey:serviceId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }

}

- (void)getDescriptor:(CDVInvokedUrlCommand*)command
{
    NSString* descriptorId = [command argumentAtIndex:0];
    NSString* deviceAddress = [descriptorId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    NSDictionary* descriptorInfo = [chromePeripheral getDescriptorInfoByDescriptorId:descriptorId];
    NSData* descriptorValue = [chromePeripheral getDescriptorValueByDescriptorId:descriptorId];

    if (!descriptorInfo) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    NSMutableArray* multipartMessage = [@[
        descriptorInfo[@"uuid"],
        descriptorInfo[@"characteristic"],
        descriptorInfo[@"instanceId"],
    ] mutableCopy];

    if (descriptorValue) {
        [multipartMessage addObject:descriptorValue];
    }

    [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:multipartMessage] callbackId:command.callbackId];
}

- (void)getDescriptors:(CDVInvokedUrlCommand*)command
{
    NSString* characteristicId = [command argumentAtIndex:0];
    NSString* deviceAddress = [characteristicId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_getDescriptorsCallbacks[characteristicId] = [^(NSArray* descriptorsInfo, NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:descriptorsInfo] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral discoveryDescriptorByCharacteristicId:characteristicId]) {
        [chromePeripheral->_getDescriptorsCallbacks removeObjectForKey:characteristicId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)readCharacteristicValue:(CDVInvokedUrlCommand*)command
{
    NSString* characteristicId = [command argumentAtIndex:0];
    NSString* deviceAddress = [characteristicId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_readCharacteristicValueCallbacks[characteristicId] = [^(NSArray* characteristicMultipartInfo, NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:characteristicMultipartInfo] callbackId:command.callbackId];
        }
    } copy];

    if(![chromePeripheral readCharacteristicValueByCharacteristicId:characteristicId]) {
        [chromePeripheral->_readCharacteristicValueCallbacks removeObjectForKey:characteristicId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)writeCharacteristicValue:(CDVInvokedUrlCommand*)command
{
    NSString* characteristicId = [command argumentAtIndex:0];
    NSData* value = [command argumentAtIndex:1];
    NSString* deviceAddress = [characteristicId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_writeCharacteristicValueCallbacks[characteristicId] = [^(NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral writeCharacteristicValueByCharacteristicId:characteristicId value:value]) {
        [chromePeripheral->_readCharacteristicValueCallbacks removeObjectForKey:characteristicId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)startCharacteristicNotifications:(CDVInvokedUrlCommand*)command
{
    NSString* characteristicId = [command argumentAtIndex:0];
    NSString* deviceAddress = [characteristicId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_startCharacteristicNotificationCallbacks[characteristicId] = [^(NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral setCharacteristicNotificationValue:YES CharacteristicId:characteristicId]) {
        [chromePeripheral->_startCharacteristicNotificationCallbacks removeObjectForKey:characteristicId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)stopCharacteristicNotifications:(CDVInvokedUrlCommand*)command
{
    NSString* characteristicId = [command argumentAtIndex:0];
    NSString* deviceAddress = [characteristicId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_stopCharacteristicNotificationCallbacks[characteristicId] = [^(NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral setCharacteristicNotificationValue:NO CharacteristicId:characteristicId]) {
        [chromePeripheral->_stopCharacteristicNotificationCallbacks removeObjectForKey:characteristicId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)readDescriptorValue:(CDVInvokedUrlCommand*)command
{
    NSString* descriptorId = [command argumentAtIndex:0];
    NSString* deviceAddress = [descriptorId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_readDescriptorValueCallbacks[descriptorId] = [^(NSArray* multipartMessage, NSError* error) {
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:multipartMessage] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral readDescriptorValueByDescriptorId:descriptorId]) {
        [chromePeripheral->_readDescriptorValueCallbacks removeObjectForKey:descriptorId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)writeDescriptorValue:(CDVInvokedUrlCommand*)command
{
    NSString* descriptorId = [command argumentAtIndex:0];
    NSData* value = [command argumentAtIndex:1];
    NSString* deviceAddress = [descriptorId componentsSeparatedByString:@"/"][0];

    ChromeBluetoothPeripheral* chromePeripheral = _peripherals[deviceAddress];

    if (!chromePeripheral) {
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
        return;
    }

    id<CDVCommandDelegate> commandDelegate = self.commandDelegate;
    chromePeripheral->_writeDescriptorValueCallbacks[descriptorId] = [^(NSError* error){
        if (error) {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[error localizedDescription]] callbackId:command.callbackId];
        } else {
            [commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK] callbackId:command.callbackId];
        }
    } copy];

    if (![chromePeripheral writeDescriptorValueByDescriptorId:descriptorId value:value]) {
        [chromePeripheral->_writeDescriptorValueCallbacks removeObjectForKey:descriptorId];
        [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid Argument"] callbackId:command.callbackId];
    }
}

- (void)registerBluetoothLowEnergyEvents:(CDVInvokedUrlCommand *)command
{
    _bluetoothLowEnergyCallbackId = command.callbackId;
}

- (void)sendServiceAddedEvent:(NSDictionary*)serviceInfo
{
    NSArray* eventResult = @[@"onServiceAdded", serviceInfo];
    CDVPluginResult* serviceAddedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [serviceAddedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:serviceAddedResult callbackId:_bluetoothLowEnergyCallbackId];
}

- (void)sendServiceChangedEvent:(NSDictionary*)serviceInfo
{
    NSArray* eventResult = @[@"onServiceChanged", serviceInfo];
    CDVPluginResult* serviceChangedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [serviceChangedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:serviceChangedResult callbackId:_bluetoothLowEnergyCallbackId];
}

- (void)sendServiceRemovedEvent:(NSDictionary*)serviceInfo
{
    NSArray* eventResult = @[@"onServiceRemoved", serviceInfo];
    CDVPluginResult* serviceRemovedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [serviceRemovedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:serviceRemovedResult callbackId:_bluetoothLowEnergyCallbackId];
}

- (void)sendCharacteristicValueChangedEvent:(NSArray*)characteristicInfo
{
    NSArray* eventResult = [@[@"onCharacteristicValueChanged"] arrayByAddingObjectsFromArray:characteristicInfo];
    CDVPluginResult* characteristicValueChangedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:eventResult];
    [characteristicValueChangedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:characteristicValueChangedResult callbackId:_bluetoothLowEnergyCallbackId];
}

- (void)sendDescriptorValueChangedEvent:(NSArray*)descriptorInfo
{
    NSArray* evnetResult = [@[@"onDescriptorValueChanged"] arrayByAddingObjectsFromArray:descriptorInfo];
    CDVPluginResult* descriptorValueChangedResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsMultipart:evnetResult];
    [descriptorValueChangedResult setKeepCallbackAsBool:YES];
    [self.commandDelegate sendPluginResult:descriptorValueChangedResult callbackId:_bluetoothLowEnergyCallbackId];
}

@end


text:
package com.PRIME.main.operations.main;

import com.PRIME.main.operations.menubars.analysisMenu.analysismenulist;
import com.PRIME.main.operations.menubars.editMenu.editmenulist;
import com.PRIME.main.operations.menubars.fileMenu.filemenulist;
import com.PRIME.main.operations.menubars.dataMenu.*;
import com.PRIME.main.operations.menubars.helpMenu.*;
import com.PRIME.main.operations.menubars.displayMenu.*;
import com.PRIME.main.operations.menubars.programmerMenu.*;

import com.PRIME.main.operations.menubars.projectMenu.projectmenulist;
import com.PRIME.main.operations.toolbars.analysisMenu.crossplot;
import com.PRIME.main.operations.toolbars.toolBarFontAwesome;
import com.PRIME.main.operations.toolbars.dataMenu.lasload;
import com.PRIME.main.operations.toolbars.displayMenu.display;
import com.PRIME.main.operations.toolbars.editMenu.edit;
import com.PRIME.main.operations.toolbars.fileMenu.file;
import com.PRIME.main.operations.toolbars.helpMenu.help;
import com.PRIME.main.operations.toolbars.programmerMenu.calculator;
import com.PRIME.main.operations.toolbars.projectMenu.recent;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

class menubar {

    VBox vbox = new VBox();
    public VBox displayMenuBar(){

        home ob = new home();
        Stage mainstage = ob.getstage();
        MenuBar menuBar= new MenuBar();
        vbox.getChildren().addAll(menuBar, toolBarFontAwesome.method());

        //File Menu
        Menu fileMenu = filemenulist.filemenulist();
        fileMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, file.fileToolbar());
        });

        //Edit Menu
        Menu editMenu = editmenulist.editmenulist();
        editMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, edit.editToolbar());
        });

        //Project Menu
        Menu projectMenu = projectmenulist.projectmenulist();
        projectMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, recent.recentToolbar() );
        });

        //Data Menu
        Menu dataMenu = datamenulist.datamenulist(mainstage);
        dataMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, lasload.lasloadToolbar());
        });

        //Analysis Menu
        Menu analysisMenu = analysismenulist.analysismenulist(mainstage);
        analysisMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, crossplot.crossplotToolbar());
        });

        //Display Menu
        Menu displayMenu = displaymenulist.displaymenulist();
        displayMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, display.displayToolbar());
        });

        //Programmer Menu
        Menu programmerMenu = programmermenulist.programmermenulist();
        programmerMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, calculator.calculatorToolbar() );
        });

        //Help Menu
        Menu helpMenu = helpmenulist.helpmenulist();
        helpMenu.setOnShown(e->{
            vbox.getChildren().clear();
            vbox.getChildren().addAll(menuBar, help.helpToolbar());
        });

        //Menu Bar

        menuBar.getStyleClass().add("topmenu");
        menuBar.getMenus().addAll(fileMenu,projectMenu,dataMenu,editMenu,analysisMenu,displayMenu, programmerMenu,helpMenu);

        return vbox;
    }
}


text:
@class NSMutableDictionary;

@interface XCApplicationMonitor_iOS : XCApplicationMonitor
{
    NSMutableDictionary *_applicationsForBundleIDs;
    NSMutableDictionary *_AXActiveForPID;
}

- (id)allMonitoredApplications;
- (id)monitoredApplicationWithProcessIdentifier:(int)arg1;
- (void)beginMonitoringApplication:(id)arg1;
- (void)applicationWithBundleID:(id)arg1 didUpdatePID:(int)arg2 andState:(unsigned long long)arg3;
- (void)setAccessibilityActive:(BOOL)arg1 forApplicationWithPID:(int)arg2;
- (id)init;

@end


text:
By [Emily Kowal](https://github.com/emottk/) and [Gabi O'Connor](https://github.com/GabiOC/)

This is a small app built to turn gifs from Giphy (as well as your own gifs) into ASCII art that runs in your terminal.
Video demo [here](https://youtu.be/pZ4QysBQkUs).

Thank you to @stefania11, @stevennunez and @drewprice for their help and Stefania for her idea to loop gif frames in the terminal!


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.rockson</groupId>
	<artifactId>validator</artifactId>
	<version>0.0.2</version>
	<packaging>jar</packaging>

	<name>validator</name>
	<url>http://maven.apache.org</url>

	<properties>
		<github.global.server>github</github.global.server>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18.1</version>
			</plugin>

			<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-project-info-reports-plugin</artifactId> <version>2.7</version>
				<configuration> <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
				</configuration> </plugin> -->

		</plugins>
	</reporting>
	<build>
		<plugins>
			<plugin>
				<groupId>org.eluder.coveralls</groupId>
				<artifactId>coveralls-maven-plugin</artifactId>
				<version>3.1.0</version>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.7</version>
				<configuration>
					<check>
						<branchRate>85</branchRate>
						<lineRate>85</lineRate>
						<haltOnFailure>false</haltOnFailure>
						<totalBranchRate>85</totalBranchRate>
						<totalLineRate>85</totalLineRate>
						<packageLineRate>85</packageLineRate>
						<packageBranchRate>85</packageBranchRate>
					</check>
					<formats>
						<format>html</format>
						<format>xml</format>
					</formats>
					<aggregate>true</aggregate>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>clean</goal>
							<goal>check</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>2.8.1</version>
				<configuration>
					<altDeploymentRepository>internal.repo::default::file://${project.build.directory}/${project.name}</altDeploymentRepository>
				</configuration>
			</plugin>
			<plugin>
				<groupId>com.github.github</groupId>
				<artifactId>site-maven-plugin</artifactId>
				<version>0.11</version>
				<configuration>
					<merge>true</merge>
					<noJekyll>false</noJekyll>                                  <!-- disable webpage processing -->
					<message>Maven artifacts for ${project.version}</message>  <!-- git commit message -->
					<outputDirectory>${project.build.directory}/${project.name}</outputDirectory> <!-- matches distribution management repository url above -->
					<branch>refs/heads/master</branch>                       <!-- remote branch name -->
					<includes>
						<include>**/*</include>
					</includes>
					<repositoryName>mvn-repo</repositoryName>      <!-- github repo name -->
					<repositoryOwner>rock-java</repositoryOwner>    <!-- github username -->
				</configuration>
				<executions>
					<!-- run site-maven-plugin's 'site' target as part of the build's normal
						'deploy' phase -->
					<execution>
						<goals>
							<goal>site</goal>
						</goals>
						<phase>deploy</phase>
					</execution>
				</executions>
			</plugin>
		</plugins>

	</build>
</project>


text:
package org.iidp.ostmap.batch_processing.tweetPerUserAnalysis;

import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Value;
import org.apache.flink.api.common.operators.Order;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.tuple.Tuple2;
import org.iidp.ostmap.commons.accumulo.FlinkEnvManager;
import org.iidp.ostmap.commons.enums.TableIdentifier;

/**
 * writes csv containg a count of tweets per user in a given timeframe
 *
 */
public class TPUAnalysis {

    /**
     *
     * @param configPath
     * @param outputPath path for csv export
     * @param timeMin
     * @param timeMax
     * @param limit first n element only, if 0 don't filter
     * @throws Exception
     */
    public void run(String configPath, String outputPath, long timeMin, long timeMax, int limit)throws Exception {

        FlinkEnvManager fem = new FlinkEnvManager(configPath, "converterJob",
                TableIdentifier.RAW_TWITTER_DATA.get(),null);

        DataSet<Tuple2<Key,Value>> rawTwitterDataRows = fem.getDataFromAccumulo();;

        DataSet<Tuple2<String,Integer>> tweetCount = rawTwitterDataRows
                .filter(new TimeFilter(timeMin, timeMax))
                .map(new UserTweetMap())
                .groupBy(0)
                .sum(1);

        tweetCount =tweetCount.sortPartition(1, Order.DESCENDING)
                .setParallelism(1);

        if(limit >0){
            tweetCount = tweetCount.first(limit).setParallelism(1);
        }

        tweetCount.writeAsCsv(outputPath).setParallelism(1);
        //tweetCount.writeAsCsv(outputPath);

        fem.getExecutionEnvironment().execute("TPUAnalysis");

    }

    /**
     * entry point
     *
     * @param args pathToConfig, pathCSV, longTimeMin, longTimeMax (,limitFirstN)
     */
    public static void main(String[] args) throws Exception {

        TPUAnalysis d = new TPUAnalysis();
        if(args.length >4){
            d.run(args[0], args[1], Integer.parseInt(args[2]),
                    Integer.parseInt(args[3]), Integer.parseInt(args[4]));

        }else{
            d.run(args[0], args[1], Integer.parseInt(args[2]),
                    Integer.parseInt(args[3]), 0);
        }

    }

}


text:
package re.fallenempi.tfe_core.database;

import re.fallenempi.tfe_core.Core;

public class Insert {

	Core TFE;
	MySQL DB;

	public Insert(Core TFE, MySQL DB) {
		this.TFE = TFE;
		this.DB = DB;
	}

}


text:
#include "config.h"
#include "Pattern.h"

#include "AffineTransform.h"
#include "GraphicsContext.h"
#include <cairo.h>

namespace WebCore {

cairo_pattern_t* Pattern::createPlatformPattern(const AffineTransform&) const
{
    NativeImageCairo* image = tileImage()->nativeImageForCurrentFrame();
    if (!image)
        return 0;

    cairo_pattern_t* pattern = cairo_pattern_create_for_surface(image->surface());

    // cairo merges patter space and user space itself
    cairo_matrix_t matrix = m_patternSpaceTransformation;
    cairo_matrix_invert(&matrix);
    cairo_pattern_set_matrix(pattern, &matrix);

    if (m_repeatX || m_repeatY)
        cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
    return pattern;
}

}


text:
			   <?php $this->load->view('admin/common/menu_master.tpl.php');	?>

						<?=$table_title?>

                            <form id="frm_admin_price_range" name="frm_admin_price_range" method="post" action="<?=base_url().'admin/price_range/insert_price_range'?>">

                              * Price From  :

							  <input id="price_from" name="price_from" type="text" class="textfield" style="width:200px;" value=""  onKeyPress="return isNumberKey(event)"/>

                              * Price To  :
                              <input id="price_to" name="price_to" type="text" class="textfield" style="width:200px;" value="" onKeyPress="return isNumberKey(event)"/>

                              * Country  :

							  <select name="country_id" id="country_id">
							  <?=$country?>
							  </select>

							    Status :

								<input type="radio" name="status" id="status" value="1" checked="checked" />Active
								<input type="radio" name="status" id="status" value="0" />Inactive

                                    <input name="change_id" type="button" class="button" value="Submit" onclick="ck_page()" />
                                <input name="reset1" type="reset" class="button" value="Back" onclick="window.location.href='<?=base_url().'admin/price_range'?>';" />

						  </form>


text:
const backslashSoup = pattern => new RegExp(pattern.replace(/\\/g, '\\\\'));

module.exports = (plugins = []) => ({
    extensions: ['js'],
    include: dirPath => plugins.some(plugin => backslashSoup(`(\\|/)(katulong-plugin-${plugin})+(\\|/)src(\\|/)index.js$`).test(dirPath)),
    recurse: true
});


text:
charcam
=======
About:
	This project is a basic character and camera movement system built on OGRE.

Licensing and Credits:
	The OGRE license is in: ogre_license.txt
	Much of this project relies and builds upon the OGRE tutorial framework.
	See for more information:
		http://www.ogre3d.org/tikiwiki/

	I do not take credit for any files except:
	CharCam.h
	CharCam.cpp

	All other files should be assumed to have come from the OGRE tutorial framework.
	It should also be known that these files may also be altered, and not assumed to be the originals from OGRE.

	The following files have been taken from either OGRE's distribution or Tutorial framework, and may have been altered:
	./src:
		BaseApplication.cpp
		BaseApplication.h

	./src/dist/bin:
		plugins.cfg
		resources.cfg

	./src/dist/media/materials/programs:
		Example_Basic.cg
		Grass.cg
		hdr.cg

	./src/dist/media/materials/scripts:
		Examples.material

	./src/dist/media/materials/textures:
		clouds.jpg
		grass_1024.jpg
		r2skin.jpg

	./src/dist/media/models:
		robot.mesh
		robot.skeleton

Building:
	This project has only been built on linux, building on windows has not been attempted.
	Dependencies: OGRE-1.9, OIS, libboost
	To build simply run the command 'make' in the root project directory.
	All executable files should be available in the bin folder.

How to use(keybindings):
	Key		Function
	-----	-----------------------
	W		Move character forward
	A		Move character left
	S		Move character backward
	D		Move character right
	I		Zoom camera in
	O		Zoom camera out
	UP		Move camera up
	DOWN	Move camera down
	LEFT	Move camera left
	RIGHT	Move camera right


text:
#import <AppKit/NSControl.h>
#import <AppKit/NSDatePickerCell.h>

@class NSCalendar;

@interface NSDatePicker : NSControl

-(BOOL)isBezeled;
-(BOOL)isBordered;

-delegate;

-(NSDatePickerElementFlags)datePickerElements;
-(NSDatePickerMode)datePickerMode;
-(NSDatePickerStyle)datePickerStyle;

-(NSCalendar *)calendar;
-(NSLocale *)locale;
-(NSDate *)minDate;
-(NSDate *)maxDate;

-(NSDate *)dateValue;
-(NSTimeInterval)timeInterval;
-(NSTimeZone *)timeZone;

-(BOOL)drawsBackground;
-(NSColor *)backgroundColor;
-(NSColor *)textColor;

-(void)setBezeled:(BOOL)flag;
-(void)setBordered:(BOOL)flag;

-(void)setDelegate:delegate;

-(void)setDatePickerElements:(NSDatePickerElementFlags)elements;
-(void)setDatePickerMode:(NSDatePickerMode)mode;
-(void)setDatePickerStyle:(NSDatePickerStyle)style;

-(void)setCalendar:(NSCalendar *)calendar;
-(void)setLocale:(NSLocale *)locale;
-(void)setMinDate:(NSDate *)date;
-(void)setMaxDate:(NSDate *)date;

-(void)setDateValue:(NSDate *)date;
-(void)setTimeInterval:(NSTimeInterval)interval;
-(void)setTimeZone:(NSTimeZone *)timeZone;

-(void)setDrawsBackground:(BOOL)flag;
-(void)setBackgroundColor:(NSColor *)color;
-(void)setTextColor:(NSColor *)color;

@end


text:
This is a fork of [reqlite](https://github.com/neumino/reqlite).

The project was not totally complete, and this fork includes hacks to:
- simulate network/query latency in a predicatable way
- simulate new/removed servers in `servers_status`.


text:
package com.ricex.cartracker.data.validation;

import java.text.MessageFormat;

import com.ricex.cartracker.common.entity.AbstractEntity;
import com.ricex.cartracker.data.mapper.EntityMapper;
import com.ricex.cartracker.data.query.properties.EntityType;

public abstract class AbstractEntityValidator<T extends AbstractEntity> implements EntityValidator<T> {

	private final EntityMapper<T> mapper;
	private final EntityType entityType;

	public AbstractEntityValidator(EntityMapper<T> mapper, EntityType entityType) {
		this.mapper = mapper;
		this.entityType = entityType;
	}

	/** Checks that an entity with the given ID exists. Throws an exception if the entity doesn't exist
	 *
	 * @param id The ID of the entity to check for existence
	 * @throws EntityValidationException If the entity does not exist
	 */
	public void exists(long id) throws EntityValidationException {
		if (null == mapper.get(id)) {
			throw new EntityValidationException(MessageFormat.format("The specified {0} does not exist!", entityType.getName()));
		}
	}

}


text:
package com.facebook.buck.android;

import static com.facebook.buck.java.JavaCompilationConstants.ANDROID_JAVAC_OPTIONS;

import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.AbstractNodeBuilder;
import com.facebook.buck.rules.SourcePath;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.util.concurrent.MoreExecutors;

public class AndroidInstrumentationApkBuilder
    extends AbstractNodeBuilder<AndroidInstrumentationApkDescription.Arg> {

  private AndroidInstrumentationApkBuilder(BuildTarget target) {
    super(
        new AndroidInstrumentationApkDescription(
            new ProGuardConfig(new FakeBuckConfig()),
            ANDROID_JAVAC_OPTIONS,
            ImmutableMap.<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform>of(),
            MoreExecutors.newDirectExecutorService()),
        target);
  }

  public static AndroidInstrumentationApkBuilder createBuilder(BuildTarget buildTarget) {
    return new AndroidInstrumentationApkBuilder(buildTarget);
  }

  public AndroidInstrumentationApkBuilder setManifest(SourcePath manifest) {
    arg.manifest = manifest;
    return this;
  }

  public AndroidInstrumentationApkBuilder setDeps(ImmutableSortedSet<BuildTarget> deps) {
    arg.deps = Optional.of(deps);
    return this;
  }

  public AndroidInstrumentationApkBuilder setApk(BuildTarget apk) {
    arg.apk = apk;
    return this;
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>A Let's Encrypt Client for Go | posts</title>
    <link rel="stylesheet" href="/css/style.css" />
    <link rel="stylesheet" href="/css/fonts.css" />

posts

about

license

A Let's Encrypt Client for Go

2015/11/13

Just want to jump into the GitHub project? Click here.

If you haven’t heard, Let’s Encrypt is trying to secure the internet with automated and free TLS certificates.

In preperation for the Public Beta in December, I’ve written a simple client in Go which you can go get on GitHub. This post uses that client to take you through the workflow of signing up, completing challenges, and requesting certificates. Let’s Encrypt!

For these examples, I’ve spun up a Let’s Encrypt server in dev mode on my local machine, made some edits to the server’s configuration, and added an entry to my /etc/hosts. See details here if you want to follow along.

Step 1: Registration

To start the client registers a key pair with the server, then uses the private key to sign all future messages and confirm its identity.

First let’s generate a key pair for our account.

ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f letsencrypt -N ''

Then we’ll load the private key and register it with the server.

package main

import (
	// hint, hint: use goimports to fill in the imports

	"github.com/ericchiang/letsencrypt"
)

func main() {
	// Create a client.
	cli, err := letsencrypt.NewClient("http://localhost:4000/directory")
	if err != nil {
		log.Fatal(err)
	}

	// Load the private key and register with the ACME server.
	key, err := loadKey("letsencrypt")
	if err != nil {
		log.Fatal(err)
	}
	if _, err := cli.NewRegistration(key); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Registration successful!")
}

// loadKey reads and parses a private RSA key.
func loadKey(file string) (*rsa.PrivateKey, error) {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(data)
	if block == nil {
		return nil, errors.New("pem decode: no key found")
	}
	return x509.ParsePKCS1PrivateKey(block.Bytes)
}

Nothing too crazy yet.

$ go run step1.go
Registration successful!

Step 2: Requesting challenges

Once we’ve registered a key pair the next step is to begin a challenge for a specific domain. In this case we’ll be asking for the DNS name example.org.

The server responds to an authorization request with a list of challenges supported for that domain and a list of combinations of challenges to perform. We’ll print the response and take a look at the results.

auth, _, err := cli.NewAuthorization(key, "dns", "example.org")
if err != nil {
	log.Fatal(err)
}

fmt.Println("Challenges:")
for _, chal := range auth.Challenges {
	fmt.Println(chal.Type, chal.URI)
}
fmt.Println("Combinations:")
for _, comb := range auth.Combs {
	fmt.Println(comb)
}

$ go run step2.go
Challenges:
simpleHttp http://127.0.0.1:4000/acme/challenge/aOOnrY65LHMSYK6HftGeK795dqEII40NYGVESqqKmGA/1
dvsni http://127.0.0.1:4000/acme/challenge/aOOnrY65LHMSYK6HftGeK795dqEII40NYGVESqqKmGA/2
http-01 http://127.0.0.1:4000/acme/challenge/aOOnrY65LHMSYK6HftGeK795dqEII40NYGVESqqKmGA/3
tls-sni-01 http://127.0.0.1:4000/acme/challenge/aOOnrY65LHMSYK6HftGeK795dqEII40NYGVESqqKmGA/4
Combinations:
[0]
[1]
[2]
[3]

The server has issued four different challenges for the domain name.

Since simpleHttp and dvsni are depricated we care about http-01 and tls-sni-01. The first is a challenge to provision an HTTP response at a given path for the domain, the second requires some trickery with TLS Server Name Identification.

The Combinations field displays the set of challenges a client can complete to prove ownership over a domain. In this case, completing any of the challenges is enough.

Step 3: Complete a challenge

The server has now challenged us to provision either an HTTP or TLS resource. It’s our turn to do so then inform the server we’re ready.

Let’s take a look at the HTTP challenge.

// grab the HTTP challenge again
httpChalURL := "http://127.0.0.1:4000/acme/challenge/aOOnrY65LHMSYK6HftGeK795dqEII40NYGVESqqKmGA/3"
chal, err := cli.Challenge(httpChalURL)
if err != nil {
	log.Fatal(err)
}

// print the challenge
out, err := json.MarshalIndent(&chal, "", "  ")
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%s\n", out)

// get the challenge details
path, resource, err := chal.HTTP(key)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Path:    ", path)
fmt.Println("Resource:", resource)

$ go run step3.go
{
  "type": "http-01",
  "uri": "http://127.0.0.1:4000/acme/challenge/aOOnrY65LHMSYK6HftGeK795dqEII40NYGVESqqKmGA/3",
  "status": "pending",
  "token": "1UMQfJKJWZwOmisxPTso_nR9tEP_42PHsq3EcibGbtE"
}
Path:     /.well-known/acme-challenge/1UMQfJKJWZwOmisxPTso_nR9tEP_42PHsq3EcibGbtE
Resource: 1UMQfJKJWZwOmisxPTso_nR9tEP_42PHsq3EcibGbtE.wF6w7g9k8byiDJcjhwNpLP883uGpxGZL0NdPTEy5PSc

As you can see the server has returned a challenge of type http-01 and a token. The spec documents how to combine that token with the client’s private key into a URL path and a HTTP response.

To actually serve the file, we’ll need to spin up a HTTP server on the domain we’ve requested. We then notify the server that the challenge is ready for verification, and poll the challenge until we get a result.

go func() {
	// serve the resource at the given path
	http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, resource)
	})
	// Start the HTTP server.
	// The test Let's Encrypt server uses port 5002 instead of 80.
	log.Fatal(http.ListenAndServe(":5002", nil))
}()

if err := cli.ChallengeReady(key, chal); err != nil {
	log.Fatal(err)
}
fmt.Println("You've completed the challenge!")

$ go run step3.go
You've completed the challenge!

And that’s it. We’ve provisioned the resource, the server checked that it was there, and the challenge has been verified.

For examples of completing other challenges, see the README.

Step 4: Getting a certificate

Once we’ve completed a set of combinations, the server will finally issue us a certificate. This comes in two steps.

First, the client generates a certificate request. This holds information like which domain we want a certificate for, what public key it will use, and what algorithms the server should use to sign it. Second, we send the certificate request to server and (if all goes well) it will respond with a certificate.

Step 4.1: Creating a certificate request

You can use tools like openssl to generate these request. But since we’re talking Go, here’s how you make one using the standard library.

package main

import (
	// ...
)

func main() {
	certKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		log.Fatal(err)
	}

	template := &x509.CertificateRequest{
		SignatureAlgorithm: x509.SHA256WithRSA,
		PublicKeyAlgorithm: x509.RSA,
		PublicKey:          &certKey.PublicKey,
		Subject:            pkix.Name{CommonName: "example.org"},
		DNSNames:           []string{"example.org"},
	}
	csrDER, err := x509.CreateCertificateRequest(rand.Reader, template, certKey)
	if err != nil {
		log.Fatal(err)
	}

	pemEncode := func(b []byte, t string) []byte {
		return pem.EncodeToMemory(&pem.Block{Bytes: b, Type: t})
	}

	keyPEM := pemEncode(x509.MarshalPKCS1PrivateKey(certKey), "RSA PRIVATE KEY")
	csrPEM := pemEncode(csrDER, "CERTIFICATE REQUEST")

	if err := ioutil.WriteFile("example.org.csr", csrPEM, 0644); err != nil {
		log.Fatal(err)
	}
	if err := ioutil.WriteFile("example.org.key", keyPEM, 0644); err != nil {
		log.Fatal(err)
	}
}

Running this will create example.org.csr and example.org.key.

Step 4.2: Requesting a certificate

Finally we sign the certificate request using our account’s key (not the one used to generate the request) and send it to the server. Since the account associated with the key has completed the challenges for the domain we’ve requested, it should issue us a certificate.

package main

import (
	// ...

	"github.com/ericchiang/letsencrypt"
)

func main() {
	cli, err := letsencrypt.NewClient("http://localhost:4000/directory")
	if err != nil {
		log.Fatal(err)
	}

	// load the account's private key and the certificate request
	key, err := loadKey("letsencrypt")
	if err != nil {
		log.Fatal(err)
	}
	csr, err := loadCSR("example.org.csr")
	if err != nil {
		log.Fatal(err)
	}

	// ask for a new certifiate
	cert, err := cli.NewCertificate(key, csr)
	if err != nil {
		log.Fatal(err)
	}
	data := pem.EncodeToMemory(&pem.Block{Bytes: cert.Raw, Type: "CERTIFICATE"})
	if err := ioutil.WriteFile("example.org.crt", data, 0644); err != nil {
		log.Fatal(err)
	}
}

func loadKey(file string) (*rsa.PrivateKey, error) {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(data)
	if block == nil {
		return nil, errors.New("pem decode: no key found")
	}
	return x509.ParsePKCS1PrivateKey(block.Bytes)
}

func loadCSR(file string) (*x509.CertificateRequest, error) {
	data, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}
	block, _ := pem.Decode(data)
	if block == nil {
		return nil, errors.New("pem decode: no key found")
	}
	return x509.ParseCertificateRequest(block.Bytes)
}

$ go run step4.go
$ cat example.org.crt
-----BEGIN CERTIFICATE-----
MIIEVzCCAz+gAwIBAgITAP9Jk5pSbvv6cgNUQrFxf/pzITANBgkqhkiG9w0BAQsF
ADAfMR0wGwYDVQQDExRoYXBweSBoYWNrZXIgZmFrZSBDQTAeFw0xNTExMTMyMDAx
MDBaFw0xNjAyMTEyMDAxMDBaMBYxFDASBgNVBAMTC2V4YW1wbGUub3JnMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwGoE3CugCDyiUflgcaRRi7Zmll39
G4zNMFhsV++rlH5OBb0ChFrEESyQfgH9trNlyRrTSB9qm8JMhDfHS9Fx9taAesYB
XxPGrjcPnWFEgOGZ+CuN6R2akR7LMPuZ4vaoC/y1kMg/ixYa6agsrgoi14OGkOhy
FhwklqsywCUtCBHYDaXVn+Fd4ivukw7nHeBxn5KxdQsItB9EuOukTe1i+fkmvFob
ESigpUO+stDPyKEvuT0WHetTD44MqlBJA2fD2Cl232ZIVr/QZOyUxet1SjcWoWdb
X/BvNpXHvUM+WYggwVRpYea142o/Q2RbttovyhA8fRO2/m6bc2IQryWL0wIDAQAB
o4IBkzCCAY8wDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggr
BgEFBQcDAjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBT1ynbTWvxbpnI9LR7i1p1p
pt5OhzAfBgNVHSMEGDAWgBT7eE8S+WAVgyyfF380GbMuNupBiTBqBggrBgEFBQcB
AQReMFwwJgYIKwYBBQUHMAGGGmh0dHA6Ly8xMjcuMC4wLjE6NDAwMi9vY3NwMDIG
CCsGAQUFBzAChiZodHRwOi8vMTI3LjAuMC4xOjQwMDAvYWNtZS9pc3N1ZXItY2Vy
dDAWBgNVHREEDzANggtleGFtcGxlLm9yZzAnBgNVHR8EIDAeMBygGqAYhhZodHRw
Oi8vZXhhbXBsZS5jb20vY3JsMGMGA1UdIARcMFowCgYGZ4EMAQIBMAAwTAYDKgME
MEUwIgYIKwYBBQUHAgEWFmh0dHA6Ly9leGFtcGxlLmNvbS9jcHMwHwYIKwYBBQUH
AgIwEwwRRG8gV2hhdCBUaG91IFdpbHQwDQYJKoZIhvcNAQELBQADggEBAHUcscRK
WYkWiTmtJY2cvNdpYU6bYKFhS4Mpkj96MnoWQM9o3ScrLdqdmsH6ObRuK2268M8g
8wH7LqkcUC/4Fn0+nO1b0nSJnZUqtr4l9RvtXceJfIJ8J9/l5MEkWuv/U+V4BuI7
Jo7uOCpEQkh+Rm4SSxRXL0ra69UljUKWkKqf6Ln5Pt74jR8VYBwiBpV9p3aoStwr
waSqKijW4zg5U5n66Ypb5CXRw+0LOtV+U64Fd9ifGBVReNRxvx+k23+3/3YO38YW
rqbQUkp9UsCPuWlxTNXHefV0D/p2SmwAa2No7b7WxXV37nGH+5Uh+rUBsIQ18JOy
IeNqHO/uy/bkmCg=
-----END CERTIFICATE-----

Holy moley, it worked.

Conclusion

This Go client isn’t a “one click TLS” tool like Let’s Encrypt’s existing command line application, but hopefully provides building blocks for similar Go programs. It should also give users the tooling to deal with challenges in custom ways, particularly for those with existing websites that they wish to secure.

The upcoming Public Beta on December 3rd will be a huge step for the Let’s Encrypt project and hopefully make HTTPS easier and easier for everyone. Even if you never use the Go package, go check them out!


text:
<?php

// SVN Fluf
//$svn_version = 'Subversion ' . trim('$Rev: 2276 $','$ ');

// Use output buffering, this gains us a few things and
// fixes some CSS issues
ob_start();

// Do a check for PHP5 because nothing will work without it
if (floatval(phpversion()) < 5) {
	echo "ERROR: Ampache requires PHP5";
	exit;
}

error_reporting(E_ERROR);			// Only show fatal errors in production

// This makes this file nolonger need customization
// the config file is in the same dir as this (init.php) file.
$ampache_path = dirname(__FILE__);
$prefix = realpath($ampache_path . "/../");
$configfile = "$prefix/config/ampache.cfg.php";
require_once $prefix . '/lib/general.lib.php';
require_once $prefix . '/lib/class/config.class.php';
require_once $prefix . '/lib/class/vauth.class.php'; // Fix for synology Fast-CGI __autoload failures in some cases

if (!function_exists('gettext')) {
	require_once $prefix . '/modules/emulator/gettext.php';
}

// Define some base level config options
Config::set('prefix',$prefix);

/*
 Check to see if this is Http or https
*/
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
	$http_type = "https://";
}
else {
	$http_type = "http://";
}

/*
 See if the Config File Exists if it doesn't
 then go ahead and move them over to the install
 script
*/
if (!file_exists($configfile)) {
        $path = preg_replace("/(.*)\/(\w+\.php)$/","\${1}", $_SERVER['PHP_SELF']);
	$link = $http_type . $_SERVER['HTTP_HOST'] . $path . "/install.php";
	header ("Location: $link");
	exit();
}

// Use the built in PHP function, supress errors here so we can handle it properly
$results = @parse_ini_file($configfile);

if (!count($results)) {
	$path = preg_replace("/(.*)\/(\w+\.php)$/","\${1}", $_SERVER['PHP_SELF']);
	$link = $http_type . $_SERVER['HTTP_HOST'] . $path . "/test.php?action=config";
	header ("Location: $link");
	exit();
}

/** Verify a few commonly removed PHP functions exist and re-direct to /test if not **/
if (!function_exists('hash') OR !function_exists('inet_pton') OR (strtoupper(substr(PHP_OS,0,3)) == 'WIN' AND floatval(phpversion()) < 5.3)) {
	$path = preg_replace("/(.*)\/(\w+\.php)$/","\${1}", $_SERVER['PHP_SELF']);
	$link = $http_type . $_SERVER['HTTP_HOST'] . $path . "/test.php";
	header ("Location: $link");
	exit();
}

/** This is the version.... fluf nothing more... **/
$results['version']		= '3.5.4'. $svn_version;
$results['int_config_version']	= '10';

$results['raw_web_path']	= $results['web_path'];
$results['web_path']		= $http_type . $_SERVER['HTTP_HOST'] . $results['web_path'];
$results['http_port']		= $_SERVER['SERVER_PORT'];
if (!$results['http_port']) {
	$results['http_port']	= '80';
}
if (!$results['site_charset']) {
	$results['site_charset'] = "UTF-8";
}
if (!$results['raw_web_path']) {
	$results['raw_web_path'] = '/';
}
if (!$_SERVER['SERVER_NAME']) {
	$_SERVER['SERVER_NAME'] = '';
}
if (isset($results['user_ip_cardinality']) && !$results['user_ip_cardinality']) {
	$results['user_ip_cardinality'] = 42;
}

/* Variables needed for vauth class */
$results['cookie_path'] 	= $results['raw_web_path'];
$results['cookie_domain']	= $_SERVER['SERVER_NAME'];
$results['cookie_life']		= $results['session_cookielife'];
$results['cookie_secure']	= $results['session_cookiesecure'];
$results['mysql_password']	= $results['database_password'];
$results['mysql_username']	= $results['database_username'];
$results['mysql_hostname']	= $results['database_hostname'];
$results['mysql_db']		= $results['database_name'];

// Define that we've loaded the INIT file
define('INIT_LOADED','1');

// Library and module includes we can't do with the autoloader
require_once $prefix . '/lib/search.php';
require_once $prefix . '/lib/preferences.php';
require_once $prefix . '/lib/log.lib.php';
require_once $prefix . '/lib/ui.lib.php';
require_once $prefix . '/lib/gettext.php';
require_once $prefix . '/lib/batch.lib.php';
require_once $prefix . '/lib/themes.php';
require_once $prefix . '/lib/xmlrpc.php';
require_once $prefix . '/lib/class/localplay.abstract.php';
require_once $prefix . '/lib/class/database_object.abstract.php';
require_once $prefix . '/lib/class/media.interface.php';
require_once $prefix . '/modules/pearxmlrpc/rpc.php';
require_once $prefix . '/modules/getid3/getid3.php';
require_once $prefix . '/modules/nusoap/nusoap.php';
require_once $prefix . '/modules/infotools/Snoopy.class.php';
require_once $prefix . '/modules/infotools/AmazonSearchEngine.class.php';
require_once $prefix . '/modules/infotools/lastfm.class.php';
//require_once $prefix . '/modules/infotools/jamendoSearch.class.php';

/* Temp Fixes */
$results = Preference::fix_preferences($results);

Config::set_by_array($results,1);

// Modules (These are conditionaly included depending upon config values)
if (Config::get('ratings')) {
	require_once $prefix . '/lib/class/rating.class.php';
	require_once $prefix . '/lib/rating.lib.php';
}

/* Set a new Error Handler */
$old_error_handler = set_error_handler('ampache_error_handler');

/* Check their PHP Vars to make sure we're cool here */
$post_size = @ini_get('post_max_size');
if (substr($post_size,strlen($post_size)-1,strlen($post_size)) != 'M') {
	/* Sane value time */
	ini_set('post_max_size','8M');
}

if ($results['memory_limit'] < 24) {
	$results['memory_limit'] = 24;
}

// Incase the local setting is 0
ini_set('session.gc_probability','2');

set_memory_limit($results['memory_limit']);

/**** END Set PHP Vars ****/

/* We have to check for HTTP Auth, only run this if we don't have an ampache session cookie */
$session_name = Config::get('session_name');
if (in_array("http",$results['auth_methods']) AND empty($_COOKIE[$session_name])) {

	$username = scrub_in($_SERVER['PHP_AUTH_USER']);
	$results = vauth::http_auth($username);

	// We've found someone or were able to create them, go ahead and generate the session
	if ($results['success']) {
		vauth::create_cookie();
		vauth::session_create($results);
		$session_name = Config::get('session_name');
		$_SESSION['userdata'] = $results;
		$_COOKIE[$session_name] = session_id();
	}

} // end if http auth

// If we want a session
if (NO_SESSION != '1' AND Config::get('use_auth')) {
	/* Verify Their session */
	if (!vauth::session_exists('interface',$_COOKIE[Config::get('session_name')])) { vauth::logout($_COOKIE[Config::get('session_name')]); exit; }

	// Actually start the session
	vauth::check_session();

	/* Create the new user */
	$GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);

	/* If they user ID doesn't exist deny them */
	if (!$GLOBALS['user']->id AND !Config::get('demo_mode')) { vauth::logout(session_id()); exit; }

	/* Actually extend the session */
	vauth::session_extend(session_id());

	/* Load preferences and theme */
	$GLOBALS['user']->update_last_seen();
}
elseif (!Config::get('use_auth')) {
	$auth['success'] = 1;
	$auth['username'] = '-1';
	$auth['fullname'] = "Ampache User";
	$auth['id'] = -1;
	$auth['offset_limit'] = 50;
	$auth['access'] = Config::get('default_auth_level') ? User::access_name_to_level(Config::get('default_auth_level')) : '100';
	if (!vauth::session_exists('interface',$_COOKIE[Config::get('session_name')])) {
		vauth::create_cookie();
		vauth::session_create($auth);
		vauth::check_session();
		$GLOBALS['user'] = new User($auth['username']);
		$GLOBALS['user']->username = $auth['username'];
		$GLOBALS['user']->fullname = $auth['fullname'];
		$GLOBALS['user']->access = $auth['access'];
	}
	else {
		vauth::check_session();
		if ($_SESSION['userdata']['username']) {
			$GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);
		}
		else {
			$GLOBALS['user'] = new User($auth['username']);
			$GLOBALS['user']->id = '-1';
	                $GLOBALS['user']->username = $auth['username'];
	                $GLOBALS['user']->fullname = $auth['fullname'];
	                $GLOBALS['user']->access = $auth['access'];
		}
		if (!$GLOBALS['user']->id AND !Config::get('demo_mode')) { vauth::logout(session_id()); exit; }
		vauth::session_extend(session_id());
		$GLOBALS['user']->update_last_seen();
	}
}
// If Auth, but no session is set
else {
	if (isset($_REQUEST['sid'])) {
		session_name(Config::get('session_name'));
		session_id(scrub_in($_REQUEST['sid']));
		session_start();
		$GLOBALS['user'] = User::get_from_username($_SESSION['userdata']['username']);
	}
	else {
		$GLOBALS['user'] = new User();
	}
} // If NO_SESSION passed

// Load the Preferences from the database
Preference::init();

// We need to create the tmp playlist for our user only if we have a session
if (session_id()) {
	$GLOBALS['user']->load_playlist();
}

/* Add in some variables for ajax done here because we need the user */
Config::set('ajax_url',Config::get('web_path') . '/server/ajax.server.php',1);

// Load gettext mojo
load_gettext();

/* Set CHARSET */
header ("Content-Type: text/html; charset=" . Config::get('site_charset'));

/* Clean up a bit */
unset($array);
unset($results);

/* Setup the flip class */
flip_class(array('odd','even'));

/* Check to see if we need to perform an update */
if (!preg_match('/update\.php/', $_SERVER['PHP_SELF'])) {
	if (Update::need_update()) {
		header("Location: " . Config::get('web_path') . "/update.php");
		exit();
	}
}
// For the XMLRPC stuff
$GLOBALS['xmlrpc_internalencoding'] = Config::get('site_charset');

// If debug is on GIMMIE DA ERRORS
if (Config::get('debug')) {
	error_reporting(E_ALL);
}

// Merge GET then POST into REQUEST effectivly striping COOKIE without depending on
// a PHP setting change to take affect
$_REQUEST = array_merge($_GET,$_POST);
?>


text:
package edu.jhuapl.openessence.datasource.jdbc.filter;

public class EqFilter extends OneArgOpFilter {

    public EqFilter(String filterId, Object argument) {
        super(filterId, argument, "=");
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index of new symbols in 0.9.41: HarfBuzz Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="index.html" title="HarfBuzz Manual">
<link rel="up" href="pt02.html" title="Part II. Reference manual">
<link rel="prev" href="api-index-0-9-39.html" title="Index of new symbols in 0.9.39">
<link rel="next" href="api-index-0-9-42.html" title="Index of new symbols in 0.9.42">
<meta name="generator" content="GTK-Doc V1.27.1 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

B

Index of new symbols in 0.9.41

B

hb_buffer_reverse_range, function in Buffers

Generated by GTK-Doc V1.27.1


text:
var dateRegex = /(\d{4})[._-](\d{2})[-_.](\d{2})/;

/**
 * Attempts to extract a Date from the specified file's name.
 * @param {string} imageFile - The file whose name is to be used
 * @returns {Date|undefined} If successful, the extracted date.  undefined otherwise.
 */
function getDate(imageFile) {
    "use strict";

    var matches = dateRegex.exec(imageFile),
        retDate,
        year,
        month,
        day;

    if (matches) {
        year = matches[1];
        month = matches[2] - 1; // zero-based
        day = matches[3];

        retDate = new Date(year, month, day);
    }

    return retDate;
}

module.exports = {
    getDate: getDate
};


text:
DATE=`date +%m-%d-%s`
rm -rf www && eleventy --input=src --output=www --config=.eleventy.js && cd www && zip -r ../site-$DATE.zip .