text:
package com.adgaudio.ApproxDictMatch;

import java.util.Collection;
import java.util.HashMap;

/**
 * Created by Alex Gaudio on 1/30/17.
 *

 * A simple frequency distribution.  By default, count occurrences of values.
 */
class FreqDist<K> extends HashMap<K, Double> {
    private static final long serialVersionUID = 1L;
    static final UpdateFunc updateAdd = new UpdateAdd();
    static final UpdateFunc updateDivide = new UpdateDivide();

    // Empty constructor
    FreqDist() {
    }

    FreqDist(Collection<K> col) {
        for (K itm : col) {
            this.put(itm, this.getOrCreate(itm) + 1);
        }
    }
    FreqDist(Collection<? extends Collection<K>> collections, Integer ignore_for_type_erasure) {
        for (Collection<K> c : collections) {
            FreqDist<K> d = new FreqDist<>(c);
            this.update(d, updateAdd);
        }
    }

    public void normalizeOverSum() {
        Double sum = 0.0;
        for (K k : this.keySet()) {
            sum += this.get(k);
        }
        this.update(sum, updateDivide);
    }

    private Double getOrCreate(K key) {
        Double returnValue = get(key);
        if (returnValue == null) {
            returnValue = 0.0;
            this.put(key, returnValue);
        }
        return returnValue;
    }

    /**
     * Merge values of two FreqDists using the apply method of given UpdateFunc
     *

     * - If keys exist in otherDist and not in this instance,
     * initialize this.key to 0 before passing values to UpdateFunc
     * - Keys that exist in this instance that do not exist in otherDist
     * are left unmodified and not passed to the given UpdateFunc
     */
    public void update(FreqDist<K> otherDist, UpdateFunc func) {
        update(otherDist.keySet(), otherDist, func);
    }

    /**
     * Merge values of two FreqDists using the apply method of given UpdateFunc
     *

     * - If given keys exist in otherDist and not in this instance,
     * initialize this.key to 0 before passing values to UpdateFunc
     * - Keys that exist in this instance that do not exist in otherDist
     * are left unmodified and not passed to the given UpdateFunc
     */
    public void update(Collection<K> keys, FreqDist<K> otherDist, UpdateFunc func) {
        for (K key : keys) {
            this.put(key, func.apply(this.getOrCreate(key), otherDist.get(key)));
        }
    }

    /**
     * Put value for key into the FreqDist using the given update method.
     *

     * This is different than the `put` method, as it will consider pre-existing values.
     *

     * - If key exists, the given UpdateFunc determines how to combine the two values
     * - If key does not exist, the given UpdateFunc determines how to combine the values (0, value)
     */
    public void update(K key, Double value, UpdateFunc func) {
        this.put(key, func.apply(this.getOrCreate(key), value));
    }

    /**
     * Transform all values in this FreqDist.
     *

     * This is different than the `put` method, as it will consider pre-existing values.
     *

     * - If key exists, the given UpdateFunc determines how to combine the two values
     * - If key does not exist, the given UpdateFunc determines how to combine the values (0, value)
     */
    public void update(Double value, UpdateFunc func) {
        for (K key : this.keySet()) {
            this.put(key, func.apply(this.get(key), value));
        }
    }

    /**
     * A standard interface that defines how to merge values of two FreqDists.
     */
    public interface UpdateFunc {
        Double apply(Double a, Double b);
    }

    private static class UpdateAdd implements UpdateFunc {
        public Double apply(Double a, Double b) {
            return a + b;
        }
    }

    private static class UpdateDivide implements UpdateFunc {
        public Double apply(Double a, Double b) {
            return a / b;
        }
    }
}


text:
package com.google.gerrit.client.admin;

import static com.google.gerrit.client.Dispatcher.toGroup;

import com.google.gerrit.client.groups.GroupApi;
import com.google.gerrit.client.groups.GroupInfo;
import com.google.gerrit.client.rpc.GerritCallback;
import com.google.gerrit.client.ui.MenuScreen;
import com.google.gerrit.reviewdb.client.AccountGroup;

public abstract class AccountGroupScreen extends MenuScreen {
  public static final String INFO = "info";
  public static final String MEMBERS = "members";

  private final GroupInfo group;
  private final String membersTabToken;

  public AccountGroupScreen(final GroupInfo toShow, final String token) {
    setRequiresSignIn(true);

    this.group = toShow;
    this.membersTabToken = getTabToken(token, MEMBERS);

    link(Util.C.groupTabGeneral(), getTabToken(token, INFO));
    link(Util.C.groupTabMembers(), membersTabToken,
        AccountGroup.isInternalGroup(group.getGroupUUID())
        && !AccountGroup.isSystemGroup(group.getGroupUUID()));
  }

  private String getTabToken(final String token, final String tab) {
    if (token.startsWith("/admin/groups/uuid-")) {
      return toGroup(group.getGroupUUID(), tab);
    } else {
      return toGroup(group.getGroupId(), tab);
    }
  }

  @Override
  protected void onLoad() {
    super.onLoad();
    setPageTitle(Util.M.group(group.name()));
    display();
    GroupApi.isGroupOwner(group.name(), new GerritCallback<Boolean>() {
      @Override
      public void onSuccess(Boolean result) {
        display(group, result);
      }
    });
  }

  protected abstract void display(final GroupInfo group, final boolean canModify);

  protected AccountGroup.UUID getGroupUUID() {
    return group.getGroupUUID();
  }

  protected void updateOwnerGroup(GroupInfo ownerGroup) {
    group.setOwnerUUID(ownerGroup.getGroupUUID());
    group.owner(ownerGroup.name());
  }

  protected AccountGroup.UUID getOwnerGroupUUID() {
    return group.getOwnerUUID();
  }

  protected void setMembersTabVisible(final boolean visible) {
    setLinkVisible(membersTabToken, visible);
  }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.appcontainers.fluent;

import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.appcontainers.fluent.models.CertificateInner;
import com.azure.resourcemanager.appcontainers.models.CertificatePatch;

/**
 * An instance of this class provides access to all the operations defined in ConnectedEnvironmentsCertificatesClient.
 */
public interface ConnectedEnvironmentsCertificatesClient {
    /**
     * Get the Certificates in a given connected environment.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the Certificates in a given connected environment as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<CertificateInner> list(String resourceGroupName, String connectedEnvironmentName);

    /**
     * Get the Certificates in a given connected environment.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the Certificates in a given connected environment as paginated response with {@link PagedIterable}.
     */
    @ServiceMethod(returns = ReturnType.COLLECTION)
    PagedIterable<CertificateInner> list(String resourceGroupName, String connectedEnvironmentName, Context context);

    /**
     * Get the specified Certificate.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the specified Certificate along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<CertificateInner> getWithResponse(
        String resourceGroupName, String connectedEnvironmentName, String certificateName, Context context);

    /**
     * Get the specified Certificate.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the specified Certificate.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    CertificateInner get(String resourceGroupName, String connectedEnvironmentName, String certificateName);

    /**
     * Create or Update a Certificate.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @param certificateEnvelope Certificate to be created or updated.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return certificate used for Custom Domain bindings of Container Apps in a Managed Environment along with {@link
     *     Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<CertificateInner> createOrUpdateWithResponse(
        String resourceGroupName,
        String connectedEnvironmentName,
        String certificateName,
        CertificateInner certificateEnvelope,
        Context context);

    /**
     * Create or Update a Certificate.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return certificate used for Custom Domain bindings of Container Apps in a Managed Environment.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    CertificateInner createOrUpdate(String resourceGroupName, String connectedEnvironmentName, String certificateName);

    /**
     * Deletes the specified Certificate.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<Void> deleteWithResponse(
        String resourceGroupName, String connectedEnvironmentName, String certificateName, Context context);

    /**
     * Deletes the specified Certificate.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    void delete(String resourceGroupName, String connectedEnvironmentName, String certificateName);

    /**
     * Update properties of a certificate
     *
     *
Patches a certificate. Currently only patching of tags is supported.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @param certificateEnvelope Properties of a certificate that need to be updated.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return certificate used for Custom Domain bindings of Container Apps in a Managed Environment along with {@link
     *     Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    Response<CertificateInner> updateWithResponse(
        String resourceGroupName,
        String connectedEnvironmentName,
        String certificateName,
        CertificatePatch certificateEnvelope,
        Context context);

    /**
     * Update properties of a certificate
     *
     *
Patches a certificate. Currently only patching of tags is supported.
     *
     * @param resourceGroupName The name of the resource group. The name is case insensitive.
     * @param connectedEnvironmentName Name of the Connected Environment.
     * @param certificateName Name of the Certificate.
     * @param certificateEnvelope Properties of a certificate that need to be updated.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.resourcemanager.appcontainers.models.DefaultErrorResponseErrorException thrown if the request
     *     is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return certificate used for Custom Domain bindings of Container Apps in a Managed Environment.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    CertificateInner update(
        String resourceGroupName,
        String connectedEnvironmentName,
        String certificateName,
        CertificatePatch certificateEnvelope);
}


text:
/*
 * @test
 * @bug 6993301
 * @summary catch parameters do not have correct kind (i.e. ElementKind.EXCEPTION_PARAMETER)
 */

import sbql4j8.com.sun.source.tree.CompilationUnitTree;
import sbql4j8.com.sun.source.tree.IdentifierTree;
import sbql4j8.com.sun.source.tree.VariableTree;
import sbql4j8.com.sun.source.util.TreePathScanner;
import sbql4j8.com.sun.source.util.Trees;
import sbql4j8.com.sun.tools.javac.api.JavacTaskImpl;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

/**
 *
 * @author Jan Lahoda
 */
public class T6993301 {
    public static void main(String... args) throws Exception {
        new T6993301().testExceptionParameterCorrectKind();
    }

    static class MyFileObject extends SimpleJavaFileObject {
        private String text;
        public MyFileObject(String text) {
            super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
            this.text = text;
        }
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return text;
        }
    }

    public void testExceptionParameterCorrectKind() throws IOException {
        final String bootPath = System.getProperty("sun.boot.class.path");
        final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
        assert tool != null;

        String code = "package test; public class Test { { try { } catch (NullPointerException ex) {} } }";

        final JavacTaskImpl ct = (JavacTaskImpl)tool.getTask(null, null, null,
                Arrays.asList("-bootclasspath",  bootPath),
                null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ct.analyze();

        new TreePathScanner<Void, Void>() {
            @Override
            public Void visitVariable(VariableTree node, Void p) {
                Element el = Trees.instance(ct).getElement(getCurrentPath());

                assertNotNull(el);
                assertEquals(ElementKind.EXCEPTION_PARAMETER, el.getKind());

                return super.visitVariable(node, p);
            }
        }.scan(cut, null);
    }

    private void assertNotNull(Object o) {
        if (o == null)
            throw new AssertionError();
    }

    private <T> void assertEquals(T expected, T actual) {
        if (expected == null ? actual == null : expected.equals(actual))
            return;
        throw new AssertionError("expected: " + expected + ", actual: " + actual);
    }

}


text:
#import "PWBeaconManager.h"

#import <UriBeacon/UriBeacon.h>

#import "PWBeacon.h"
#import "PWMetadataRequest.h"

#define DISCOVERY_DELAY_KEY @"discoveryDelay"

@interface PWBeaconManager ()<PWMetadataRequestDelegate,
                              NSNetServiceBrowserDelegate, NSNetServiceDelegate>

@end

@implementation PWBeaconManager {
  // Underlying beacon scanner from UriBeacon library.
  UBUriBeaconScanner* _scanner;
  // Map of URL to augmented beacons.
  NSMutableDictionary* _beaconsDict; /* URL -> PWBeacon */
  // Handler when the list of beacons change.
  NSMutableArray* /* Block */ _changeBlocks;
  // Handler when the list of configurable beacons change.
  NSMutableArray* /* Block */ _configurationChangeBlocks;
  // List of metadata requests.
  NSMutableArray* /* PWMetadataRequest */ _requests;
  // Set of URLs that are being requested.
  NSMutableSet* /* NSURL */ _pendingURLRequest;
  // Whether the beacon manager started.
  BOOL _started;
  // mDNS browser for http.
  NSNetServiceBrowser* _httpServiceBrowser;
  // mDNS browser for https.
  NSNetServiceBrowser* _httpsServiceBrowser;
  // mDNS found that we need to resolve.
  NSMutableArray* _pendingNetServices;
  // Whether a resolution is in progress.
  BOOL _resolving;
  // URL related to a given service.
  NSMutableDictionary* _discoveredNetServicesURLs;
  // Names of the discovered services.
  NSMutableSet* _netServicesNames;
  NSTimeInterval _startTime;
  NSMutableArray* _pendingBeaconsInfos;
}

- (id)init {
  self = [super init];
  if (!self) {
    return nil;
  }
  _beaconsDict = [NSMutableDictionary dictionary];
  _changeBlocks = [NSMutableArray array];
  _configurationChangeBlocks = [NSMutableArray array];
  _requests = [NSMutableArray array];
  _pendingURLRequest = [NSMutableSet set];
  _pendingNetServices = [[NSMutableArray alloc] init];
  _pendingBeaconsInfos = [[NSMutableArray alloc] init];
  _stableMode = YES;
  return self;
}

+ (instancetype)sharedManager {
  static dispatch_once_t onceToken;
  static PWBeaconManager* instance = nil;
  dispatch_once(&onceToken, ^{
    if (instance == nil) {
      instance = [[PWBeaconManager alloc] init];
    }
  });
  return instance;
}

- (NSArray* /* PWBeacon */)beacons {
  return [_beaconsDict allValues];
}

- (NSArray* /* UBConfigurableUriBeacon */)configurableBeacons {
  return [_scanner configurableBeacons];
}

- (id)registerChangeBlock:(void (^)(void))block {
  void (^blockCopy)(void) = [block copy];
  [_changeBlocks addObject:blockCopy];
  return blockCopy;
}

- (void)unregisterChangeBlock:(id)registeredBlock {
  [_changeBlocks removeObject:registeredBlock];
}

- (id)registerConfigurationChangeBlock:(void (^)(void))block {
  void (^blockCopy)(void) = [block copy];
  [_configurationChangeBlocks addObject:blockCopy];
  return blockCopy;
}

- (void)unregisterConfigurationChangeBlock:(id)registeredBlock {
  [_configurationChangeBlocks removeObject:registeredBlock];
}

- (void)start {
  _startTime = [NSDate timeIntervalSinceReferenceDate];
  _started = YES;
  PWBeaconManager* __weak weakSelf = self;
#if TODAY_EXTENSION
  _scanner = [[UBUriBeaconScanner alloc] initWithApplication:nil];
#else
  _scanner = [[UBUriBeaconScanner alloc]
      initWithApplication:[UIApplication sharedApplication]];
#endif
  [_scanner startScanningWithUpdateBlock:^{
    PWBeaconManager* strongSelf = weakSelf;
    [strongSelf _updateBeacons];
  }];
  _httpServiceBrowser = [[NSNetServiceBrowser alloc] init];
  [_httpServiceBrowser setDelegate:self];
  _httpsServiceBrowser = [[NSNetServiceBrowser alloc] init];
  [_httpsServiceBrowser setDelegate:self];
  [_httpServiceBrowser searchForServicesOfType:@"_http._tcp." inDomain:@""];
  [_httpsServiceBrowser searchForServicesOfType:@"_https._tcp." inDomain:@""];
  [_pendingNetServices removeAllObjects];
  _discoveredNetServicesURLs = [NSMutableDictionary dictionary];
  _netServicesNames = [NSMutableSet set];
  _resolving = NO;
}

- (NSURL*)_urlWithNetService:(NSNetService*)service {
  NSDictionary* txtRecords =
      [NSNetService dictionaryFromTXTRecordData:[service TXTRecordData]];
  NSString* path =
      [[NSString alloc] initWithData:[txtRecords objectForKey:@"path"]
                            encoding:NSUTF8StringEncoding];
  NSString* scheme = @"http";
  if ([[service type] isEqualToString:@"_http._tcp."]) {
    scheme = @"http";
  } else if ([[service type] isEqualToString:@"_https._tcp."]) {
    scheme = @"https";
  }
  NSString* hostname = [service hostName];
  NSString* urlString = nil;
  if ([hostname hasSuffix:@"."]) {
    hostname = [hostname substringToIndex:[hostname length] - 1];
  }
  if (([scheme isEqualToString:@"http"] && [service port] == 80) ||
      ([scheme isEqualToString:@"https"] && [service port] == 443)) {
    urlString = [NSString stringWithFormat:@"%@://%@", scheme, hostname];
  } else {
    urlString = [NSString
        stringWithFormat:@"%@://%@:%i", scheme, hostname, (int)[service port]];
  }
  if ([path length] != 0) {
    if ([path hasPrefix:@"/"]) {
      urlString = [urlString stringByAppendingString:path];
    } else {
      urlString = [urlString stringByAppendingFormat:@"/%@", path];
    }
  }
  return [NSURL URLWithString:urlString];
}

- (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser
           didFindService:(NSNetService*)netService
               moreComing:(BOOL)moreServicesComing {
  [_pendingNetServices addObject:netService];
  NSString* name = [NSString
      stringWithFormat:@"%@:%@", [netService type], [netService name]];
  [_netServicesNames addObject:name];

  if (!moreServicesComing) {
    [self _resolveNextNetService];
  }
}

- (void)netServiceBrowser:(NSNetServiceBrowser*)netServiceBrowser
         didRemoveService:(NSNetService*)netService
               moreComing:(BOOL)moreServicesComing {
  NSString* name = [NSString
      stringWithFormat:@"%@:%@", [netService type], [netService name]];
  [_netServicesNames removeObject:name];
  [_discoveredNetServicesURLs removeObjectForKey:name];
  [self _cleanup];
}

- (void)_resolveNextNetService {
  if (_resolving) {
    return;
  }
  if ([_pendingNetServices count] == 0) {
    return;
  }

  _resolving = YES;

  NSNetService* netService = [_pendingNetServices objectAtIndex:0];
  [netService setDelegate:self];
  [netService resolveWithTimeout:0.5];

  [self performSelector:@selector(_skipResolve) withObject:nil afterDelay:0.5];
}

- (void)_skipResolve {
  _resolving = NO;
  NSNetService* netService = [_pendingNetServices objectAtIndex:0];
  [netService stop];

  [self _resolveNextNetService];
}

- (void)netServiceDidResolveAddress:(NSNetService*)netService {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(_skipResolve)
                                             object:nil];
  _resolving = NO;
  NSURL* url = [self _urlWithNetService:netService];
  NSString* name = [NSString
      stringWithFormat:@"%@:%@", [netService type], [netService name]];
  [_discoveredNetServicesURLs setObject:url forKey:name];
  [netService stop];
  [_pendingNetServices removeObject:netService];
  [self _resolveNextNetService];

  PWBeacon* beacon = [_beaconsDict objectForKey:url];
  if (beacon == nil) {
    if (![_pendingURLRequest containsObject:url]) {
      // Request metadata of a new beacon.
      UBUriBeacon* uriBeacon =
          [[UBUriBeacon alloc] initWithURI:url txPowerLevel:0];
      NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
      NSTimeInterval discoveryDelay = currentTime - _startTime;
      NSMutableDictionary* pendingBeaconInfo =
          [[NSMutableDictionary alloc] init];
      pendingBeaconInfo[DISCOVERY_DELAY_KEY] =
          [NSNumber numberWithDouble:discoveryDelay];
      [_pendingBeaconsInfos addObject:pendingBeaconInfo];
      PWMetadataRequest* request = [[PWMetadataRequest alloc] init];
      [request setUriBeacons:@[ uriBeacon ]];
      [request setDelegate:self];
      [request start];
      [_pendingURLRequest addObject:[uriBeacon URI]];
      [_requests addObject:request];
    }
  }
}

- (void)netService:(NSNetService*)netService
     didNotResolve:(NSDictionary*)errorDict {
  [NSObject cancelPreviousPerformRequestsWithTarget:self
                                           selector:@selector(_skipResolve)
                                             object:nil];
  _resolving = NO;
  [netService stop];
  [_pendingNetServices removeObject:netService];
  [self _resolveNextNetService];
}

- (void)resetBeacons {
  [_beaconsDict removeAllObjects];
  [self _notify];
}

- (void)_updateBeacons {
  [self _notifyConfiguration];

  BOOL hasChange = NO;
  for (UBUriBeacon* uriBeacon in [_scanner beacons]) {
    if ([uriBeacon URI] == nil) {
      continue;
    }
    if ([uriBeacon RSSI] == 127) {
      continue;
    }
    if (!([[[[uriBeacon URI] scheme] lowercaseString]
              isEqualToString:@"http"] ||
          [[[[uriBeacon URI] scheme] lowercaseString]
              isEqualToString:@"https"])) {
      continue;
    }
    PWBeacon* beacon = [_beaconsDict objectForKey:[uriBeacon URI]];
    if (beacon == nil) {
      if (![_pendingURLRequest containsObject:[uriBeacon URI]]) {
        // Request metadata of a new beacon.
        NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
        NSTimeInterval discoveryDelay = currentTime - _startTime;
        NSMutableDictionary* pendingBeaconInfo =
            [[NSMutableDictionary alloc] init];
        pendingBeaconInfo[DISCOVERY_DELAY_KEY] =
            [NSNumber numberWithDouble:discoveryDelay];
        [_pendingBeaconsInfos addObject:pendingBeaconInfo];
        PWMetadataRequest* request = [[PWMetadataRequest alloc] init];
        [request setUriBeacons:@[ uriBeacon ]];
        [request setDelegate:self];
        [request start];
        [_pendingURLRequest addObject:[uriBeacon URI]];
        [_requests addObject:request];
      }
    } else {
      // Updated existing beacon.
      [beacon setUriBeacon:uriBeacon];
      hasChange = YES;
    }
  }
  if ([self _cleanup]) {
    hasChange = YES;
  }
  if (hasChange) {
    [self _notify];
  }
}

- (void)metadataRequest_done:(PWMetadataRequest*)request {
  UBUriBeacon* uriBeacon = [[request uriBeacons] objectAtIndex:0];
  PWBeacon* beacon = nil;
  if ([request error] == nil && [[request results] count] > 0) {
    beacon = [[request results] objectAtIndex:0];
  } else {
    beacon = [[PWBeacon alloc] initWithUriBeacon:uriBeacon info:nil];
  }

  [_beaconsDict setObject:beacon forKey:[[beacon uriBeacon] URI]];
  NSUInteger idx = [_requests indexOfObject:request];
  if (idx != NSNotFound && idx < [_pendingBeaconsInfos count]) {
    NSDictionary* beaconInfo = [_pendingBeaconsInfos objectAtIndex:idx];
    NSTimeInterval discoveryDelay =
        [beaconInfo[DISCOVERY_DELAY_KEY] doubleValue];
    NSTimeInterval requestDelay = [request delay];
    [beacon setDiscoveryDelay:discoveryDelay];
    [beacon setRequestDelay:requestDelay];
    [_pendingURLRequest removeObject:[uriBeacon URI]];
    [_pendingBeaconsInfos removeObjectAtIndex:idx];
    [_requests removeObjectAtIndex:idx];
  }
  [self _notify];
}

// Remove expired beacons.
- (BOOL)_cleanup {
  BOOL hasChange = NO;
  if (![self isStableMode]) {
    NSMutableSet* existingUrls = [NSMutableSet set];
    for (UBUriBeacon* beacon in [_scanner beacons]) {
      if ([beacon URI] != nil) {
        [existingUrls addObject:[beacon URI]];
      }
    }
    [existingUrls addObjectsFromArray:[_discoveredNetServicesURLs allValues]];
    for (NSURL* key in [_beaconsDict allKeys]) {
      if (![existingUrls containsObject:key]) {
        [_beaconsDict removeObjectForKey:key];
        hasChange = YES;
      }
    }
  }
  return hasChange;
}

- (void)_notify {
  for (void (^block)(void)in [_changeBlocks copy]) {
    block();
  }
}

- (void)_notifyConfiguration {
  for (void (^block)(void)in [_configurationChangeBlocks copy]) {
    block();
  }
}

- (void)stop {
  [_httpServiceBrowser stop];
  [_httpsServiceBrowser stop];
  [_scanner stopScanning];
  _started = NO;
}

- (BOOL)isStarted {
  return _started;
}

- (void)serializeBeacons:(NSArray*)beacons {
  NSUserDefaults* shared =
      [[NSUserDefaults alloc] initWithSuiteName:@"group.karma.konnect"];
  NSMutableArray* encoded = [[NSMutableArray alloc] init];
  for (PWBeacon* beacon in beacons) {
    NSMutableDictionary* item = [[NSMutableDictionary alloc] init];
    if ([beacon URL] != nil) {
      item[@"url"] = [[beacon URL] absoluteString];
    }
    if ([beacon title] != nil) {
      item[@"title"] = [beacon title];
    }
    [encoded addObject:item];
  }
  [shared setObject:encoded forKey:@"LastSeenBeacons"];
  [shared synchronize];
}

- (NSArray*)unserializedBeacons {
  NSUserDefaults* shared =
      [[NSUserDefaults alloc] initWithSuiteName:@"group.karma.konnect"];
  NSArray* encoded = [shared objectForKey:@"LastSeenBeacons"];
  NSMutableArray* beacons = [[NSMutableArray alloc] init];
  for (NSDictionary* item in encoded) {
    PWBeacon* beacon = [[PWBeacon alloc] init];
    if (item[@"url"] != nil) {
      [beacon setURL:[NSURL URLWithString:item[@"url"]]];
    }
    [beacon setTitle:item[@"title"]];
    [beacons addObject:beacon];
  }
  return beacons;
}

- (NSTimeInterval)startTime {
  return _startTime;
}

@end


text:
<?php

namespace Matthias\SymfonyConsoleForm\Tests\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ColorWithChoicesAsValuesType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('color', 'choice', array(
                'label' => 'Select color',
                'choices' => array(
                    'Red' => 'red',
                    'Blue' => 'blue',
                    'Yellow' => 'yellow'
                ),
                'data' => 'red',
                'choices_as_values' => true
            ));
    }

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


text:
<BroadcastMonitor>
  <updated>2015-08-10T13:42:03</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime></startTime>
    <itemId></itemId>
    <titleId></titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName></titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode></CategoryCode>
    <CategoryName></CategoryName>
    <itemDuration></itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-10T13:41:58</startTime>
    <itemId>1000080614:1245312</itemId>
    <titleId>216017673</titleId>
    <itemCode>MW7</itemCode>
    <itemReference></itemReference>
    <titleName>Gaucho</titleName>
    <artistName>Steely Dan</artistName>
    <albumName></albumName>
    <CategoryCode>747</CategoryCode>
    <CategoryName>POP</CategoryName>
    <itemDuration>331</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
/*
 * Copyright 2013 Claude Mamo
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.jrubycxf.aegis.type;

import org.jrubycxf.aegis.DatabindingException;
import org.jrubycxf.aegis.type.basic.BeanType;
import org.jrubycxf.aegis.type.basic.BeanTypeInfo;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

public class DefaultTypeCreator extends AbstractTypeCreator {
    public DefaultTypeCreator() {
    }

    public DefaultTypeCreator(TypeCreationOptions configuration) {
        setConfiguration(configuration);
    }

    @Override
    public org.jrubycxf.aegis.type.TypeClassInfo createClassInfo(Method m, int index) {
        org.jrubycxf.aegis.type.TypeClassInfo info = new org.jrubycxf.aegis.type.TypeClassInfo();
        info.setDescription("method " + m.getName() + " parameter " + index);

        if (index >= 0) {
            info.setType(m.getParameterTypes()[index]);
        } else {
            info.setType(m.getReturnType());
        }

        return info;
    }

    @Override
    public org.jrubycxf.aegis.type.TypeClassInfo createClassInfo(PropertyDescriptor pd) {
        return createBasicClassInfo(pd.getPropertyType());
    }

    @Override
    public org.jrubycxf.aegis.type.AegisType createCollectionType(org.jrubycxf.aegis.type.TypeClassInfo info) {
        if (!(info.getType() instanceof ParameterizedType)) {
            throw new DatabindingException("Cannot create mapping for " + info.getType()
                                           + ", unspecified component type for " + info.getDescription());
        }

        return createCollectionTypeFromGeneric(info);
    }

    @Override
    public org.jrubycxf.aegis.type.AegisType createDefaultType(org.jrubycxf.aegis.type.TypeClassInfo info) {
        BeanType type = new BeanType();
        /*
         * As of this point, we refuse to do this for generics in general.
         * This might be revisited ... it might turn out to 'just work'.
         */
        Class<?> typeClass = org.jrubycxf.aegis.type.TypeUtil.getTypeClass(info.getType(), false);
        if (typeClass == null) {
            throw new DatabindingException("Unable to map generic type " + info.getType());
        }
        type.setSchemaType(createQName(typeClass));
        type.setTypeClass(typeClass);
        type.setTypeMapping(getTypeMapping());

        BeanTypeInfo typeInfo = type.getTypeInfo();
        typeInfo.setDefaultMinOccurs(getConfiguration().getDefaultMinOccurs());
        typeInfo.setExtensibleAttributes(getConfiguration().isDefaultExtensibleAttributes());
        typeInfo.setExtensibleElements(getConfiguration().isDefaultExtensibleElements());

        return type;
    }
    protected org.jrubycxf.aegis.type.AegisType getOrCreateMapKeyType(org.jrubycxf.aegis.type.TypeClassInfo info) {
        return createObjectType();
    }

    protected AegisType getOrCreateMapValueType(TypeClassInfo info) {
        return createObjectType();
    }
}


text:
#ifndef _EGF_AUDIO_OGGSOUNDBUILDER_HPP
#define _EGF_AUDIO_OGGSOUNDBUILDER_HPP

#include <stdexcept>
#include <string>

#include <boost/shared_ptr.hpp>

#include <vorbis/codec.h>
#include <vorbis/vorbisfile.h>

#include <Singleton.hpp>

#include <Audio/Sound.hpp>

namespace EGF {

    namespace Audio {

        /** Класс для создания звуков из Ogg Vorbis данных.
          * @author Elijah Vlasov
        */

        class OGGSoundBuilder: public Singleton<OGGSoundBuilder> {

            SINGLETON(OGGSoundBuilder)

            public:

                /** Создать звук.
                  * @param oggBuffer Содержимое ogg-файла.
                */

                boost::shared_ptr<Sound> createSound(const std::string& oggBuffer)
                                                    throw(std::invalid_argument, std::runtime_error);

                static bool ReadOggBlock(OggVorbis_File* oggVorbisFile, std::string& out, std::size_t blockSize);

                static std::size_t ReadOgg(void* out, std::size_t size, std::size_t num, void* datasource);
                static int SeekOgg(void* dataSource, ogg_int64_t offset, int whence);
                static long TellOgg(void* dataSource);
                static int CloseOgg(void* dataSource);

            private:

                static const std::size_t MAX_PCM_SOUND_SIZE;

        };

    }

}

#endif


text:
UAnimationGraph::UAnimationGraph(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
}

#undef LOCTEXT_NAMESPACE


text:
<?php

namespace ElkArte\sources\subs\SettingsFormAdapter;
use BBC\ParserWrapper;

/**
 * Class Db
 *
 * @package ElkArte\sources\subs\SettingsFormAdapter
 */
class Db extends Adapter
{
	/**
	 * Helper method, it sets up the context for database settings.
	 */
	public function prepare()
	{
		global $modSettings;

		loadLanguage('Help');

		foreach ($this->configVars as $configVar)
		{
			// HR?
			if (!is_array($configVar))
			{
				$this->context[] = $configVar;
			}
			else
			{
				// If it has no name it doesn't have any purpose!
				if (empty($configVar[1]))
				{
					continue;
				}

				// Special case for inline permissions
				if ($configVar[0] === 'permissions' && !allowedTo('manage_permissions'))
				{
					continue;
				}

				$this->context[$configVar[1]] = array(
					'type' => $configVar[0],
					'size' => !empty($configVar[2]) && !is_array($configVar[2]) ? $configVar[2] : (in_array($configVar[0], array('int', 'float')) ? 6 : 0),
					'data' => array(),
					'name' => str_replace(' ', '_', $configVar[1]),
					'value' => isset($modSettings[$configVar[1]]) ? ($configVar[0] === 'select' ? $modSettings[$configVar[1]] : htmlspecialchars($modSettings[$configVar[1]], ENT_COMPAT, 'UTF-8')) : (in_array($configVar[0], array('int', 'float')) ? 0 : ''),
					'disabled' => false,
					'invalid' => !empty($configVar['invalid']),
					'javascript' => '',
				);
				foreach (array('helptext', 'message', 'preinput', 'postinput', 'icon') as $k)
				{
					if (isset($configVar[$k]))
					{
						$this->context[$configVar[1]][$k] = $configVar[$k];
					}
				}

				$this->prepareLabel($configVar);

				// If this is a select box handle any data.
				$this->handleSelect($configVar);

				// Revert masks if necessary
				$this->context[$configVar[1]]['value'] = $this->revertMasks($configVar, $this->context[$configVar[1]]['value']);

				// Finally allow overrides - and some final cleanups.
				$this->allowOverrides($configVar);
			}
		}

		// If we have inline permissions we need to prep them.
		$this->init_inline_permissions();

		// What about any BBC selection boxes?
		$this->initBbcChoices();

		$this->prepareContext();
	}

	/**
	 * Initialize inline permissions settings.
	 */
	private function init_inline_permissions()
	{
		global $context;

		$inlinePermissions = array_filter($this->configVars,
			function ($configVar)
			{
				return isset($configVar[0]) && $configVar[0] === 'permissions';
			}
		);

		if (empty($inlinePermissions))
		{
			return;
		}

		$permissionsForm = new InlinePermissions;
		$permissionsForm->setExcludedGroups(isset($context['permissions_excluded']) ? $context['permissions_excluded'] : array());
		$permissionsForm->setPermissions($inlinePermissions);
		$permissionsForm->prepare();
	}

	/**
	 * @param mixed[] $configVar
	 * @param string  $str
	 *
	 * @return string
	 */
	private function revertMasks(array $configVar, $str)
	{
		$known_rules = array(
			'nohtml' => 'htmlspecialchars_decode[' . ENT_NOQUOTES . ']',
		);
		return $this->applyMasks($configVar, $str, $known_rules);
	}

	/**
	 * @param mixed[] $configVar
	 * @param string  $str
	 *
	 * @return string
	 */
	private function setMasks(array $configVar, $str)
	{
		$known_rules = array(
			'nohtml' => 'Util::htmlspecialchars[' . ENT_QUOTES . ']',
			'email' => 'valid_email',
			'url' => 'valid_url',
		);
		return $this->applyMasks($configVar, $str, $known_rules);
	}

	/**
	 * @param mixed[] $configVar
	 * @param string  $str
	 * @param array   $known_rules
	 *
	 * @return string
	 */
	private function applyMasks(array $configVar, $str, $known_rules)
	{
		if (isset($configVar['mask']))
		{
			$rules = array();
			if (!is_array($configVar['mask']))
			{
				$configVar['mask'] = array($configVar['mask']);
			}
			foreach ($configVar['mask'] as $key => $mask)
			{
				if (isset($known_rules[$mask]))
				{
					$rules[$configVar[1]][] = $known_rules[$mask];
				}
				else
				{
					$rules[$configVar[1]][] = $mask;
				}
			}
			if (!empty($rules))
			{
				$rules[$configVar[1]] = implode('|', $rules[$configVar[1]]);

				$validator = new \Data_Validator();
				$validator->sanitation_rules($rules);
				$validator->validate(array($configVar[1] => $str));

				return $validator->{$configVar[1]};
			}
		}

		return $str;
	}

	/**
	 * @param mixed[] $configVar
	 */
	private function handleSelect(array $configVar)
	{
		if (!empty($configVar[2]) && is_array($configVar[2]))
		{
			// If we allow multiple selections, we need to adjust a few things.
			if ($configVar[0] === 'select' && !empty($configVar['multiple']))
			{
				$this->context[$configVar[1]]['name'] .= '[]';
				$this->context[$configVar[1]]['value'] = !empty($this->context[$configVar[1]]['value']) ? \Util::unserialize($this->context[$configVar[1]]['value']) : array();
			}

			// If it's associative
			if (isset($configVar[2][0]) && is_array($configVar[2][0]))
			{
				$this->context[$configVar[1]]['data'] = $configVar[2];
			}
			else
			{
				foreach ($configVar[2] as $key => $item)
				{
					$this->context[$configVar[1]]['data'][] = array($key, $item);
				}
			}
		}
	}

	/**
	 * @param mixed[] $configVar
	 */
	private function allowOverrides(array $configVar)
	{
		global $txt, $helptxt;

		foreach ($configVar as $k => $v)
		{
			if (!is_numeric($k))
			{
				if (substr($k, 0, 2) === 'on')
				{
					$this->context[$configVar[1]]['javascript'] .= ' ' . $k . '="' . $v . '"';
				}
				else
				{
					$this->context[$configVar[1]][$k] = $v;
				}
			}
		}
		if (isset($configVar['message'], $txt[$configVar['message']]))
		{
			$this->context[$configVar[1]]['message'] = $txt[$configVar['message']];
		}
		if (isset($helptxt[$configVar[1]]))
		{
			$this->context[$configVar[1]]['helptext'] = $configVar[1];
		}
	}

	/**
	 * @param string[] $var
	 *
	 * @return string
	 */
	private function setBbcChoices($var)
	{
		$codes = ParserWrapper::instance()->getCodes();
		$bbcTags = $codes->getTags();

		if (!isset($this->configValues[$var[1] . '_enabledTags']))
		{
			$this->configValues[$var[1] . '_enabledTags'] = array();
		}
		elseif (!is_array($this->configValues[$var[1] . '_enabledTags']))
		{
			$this->configValues[$var[1] . '_enabledTags'] = array($this->configValues[$var[1] . '_enabledTags']);
		}

		return implode(',', array_diff($bbcTags, $this->configValues[$var[1] . '_enabledTags']));
	}

	/**
	 * Simply create the config var label value
	 *
	 * @param array $configVar
	 */
	private function prepareLabel($configVar)
	{
		global $txt;

		// See if there are any labels that might fit?
		if (isset($configVar['text_label']))
		{
			$this->context[$configVar[1]]['label'] = $configVar['text_label'];
		}
		elseif (isset($txt[$configVar[1]]))
		{
			$this->context[$configVar[1]]['label'] = $txt[$configVar[1]];
		}
		elseif (isset($txt['setting_' . $configVar[1]]))
		{
			$this->context[$configVar[1]]['label'] = $txt['setting_' . $configVar[1]];
		}
		elseif (isset($txt['groups_' . $configVar[1]]))
		{
			$this->context[$configVar[1]]['label'] = $txt['groups_' . $configVar[1]];
		}
		else
		{
			$this->context[$configVar[1]]['label'] = $configVar[1];
		}
	}

	/**
	 * Initialize a list of available BB codes.
	 */
	private function initBbcChoices()
	{
		global $helptxt, $modSettings;

		$bbcChoice = array_filter($this->configVars,
			function ($configVar)
			{
				return isset($configVar[0]) && $configVar[0] === 'bbc';
			}
		);
		if (empty($bbcChoice))
		{
			return;
		}

		// What are the options, eh?
		$codes = ParserWrapper::instance()->getCodes();
		$bbcTags = $codes->getTags();
		$bbcTags = array_unique($bbcTags);
		$bbc_sections = array();
		foreach ($bbcTags as $tag)
		{
			$bbc_sections[] = array(
				'tag' => $tag,
				// @todo  'tag_' . ?
				'show_help' => isset($helptxt[$tag]),
			);
		}

		// Now put whatever BBC options we may have into context too!
		foreach ($bbcChoice as $configVar)
		{
			$disabled = empty($modSettings['bbc_disabled_' . $configVar[1]]);
			$this->context[$configVar[1]] = array_merge_recursive(array(
				'disabled_tags' => $disabled ? array() : $modSettings['bbc_disabled_' . $configVar[1]],
				'all_selected' => $disabled,
				'data' => $bbc_sections,
			), $this->context[$configVar[1]]);
		}
	}

	/**
	 * Cast all the config vars as defined
	 *
	 * @return array
	 */
	protected function sanitizeVars()
	{
		$setTypes = array();
		$setArray = array();
		foreach ($this->configVars as $var)
		{
			if (!isset($var[1]) || !isset($this->configValues[$var[1]]) && $var[0] !== 'check')
			{
				continue;
			}
			$setTypes[$var[1]] = $var[1];
			switch ($var[0])
			{
				case 'check':
					$setTypes[$var[1]] = 'int';
					$setArray[$var[1]] = (int) !empty($this->configValues[$var[1]]);
					break;
				case 'select':
					// Select boxes!
					$setTypes[$var[1]] = 'string';
					if (empty($var['multiple']) && in_array($this->configValues[$var[1]], array_keys($var[2])))
					{
						$setArray[$var[1]] = $this->configValues[$var[1]];
					}
					elseif (!empty($var['multiple']))
					{
						// For security purposes we validate this line by line.
						$setArray[$var[1]] = serialize(array_intersect($this->configValues[$var[1]], array_keys($var[2])));
					}
					break;
				case 'int':
					// Integers!
					$setArray[$var[1]] = (int) $this->configValues[$var[1]];
					break;
				case 'float':
					// Floating point!
					$setArray[$var[1]] = (float) $this->configValues[$var[1]];
					break;
				case 'text':
				case 'color':
				case 'large_text':
					// Text!
					$setTypes[$var[1]] = 'string';
					$setArray[$var[1]] = $this->setMasks($var, $this->configValues[$var[1]]);
					break;
				case 'password':
					// Passwords!
					$setTypes[$var[1]] = 'string';
					if (isset($this->configValues[$var[1]][1]) && $this->configValues[$var[1]][0] == $this->configValues[$var[1]][1])
					{
						$setArray[$var[1]] = $this->configValues[$var[1]][0];
					}
					break;
				case 'bbc':
					// BBC.
					$setTypes[$var[1]] = 'string';
					$setArray[$var[1]] = $this->setBbcChoices($var);
					break;
			}
		}
		return array($setArray, $setTypes);
	}

	/**
	 * Helper method for saving database settings.
	 */
	public function save()
	{
		list ($setArray) = $this->sanitizeVars();
		$inlinePermissions = array();

		foreach ($this->configVars as $var)
		{
			if (!isset($var[1]) || (!isset($this->configValues[$var[1]]) && $var[0] !== 'permissions'))
			{
				continue;
			}
			// Permissions?
			elseif ($var[0] === 'permissions')
			{
				$inlinePermissions[] = $var;
			}
		}

		if (!empty($setArray))
		{
			// Just in case we cached this.
			$setArray['settings_updated'] = time();

			updateSettings($setArray);
		}

		// If we have inline permissions we need to save them.
		if (!empty($inlinePermissions) && allowedTo('manage_permissions'))
		{
			$permissionsForm = new InlinePermissions;
			$permissionsForm->setPermissions($inlinePermissions);
			$permissionsForm->save();
		}
	}
}


text:
package org.apache.atlas.security;

import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory;
import com.sun.jersey.client.urlconnection.URLConnectionClientHandler;
import org.apache.atlas.AtlasException;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.alias.CredentialProviderFactory;
import org.apache.hadoop.security.authentication.client.Authenticator;
import org.apache.hadoop.security.authentication.client.ConnectionConfigurator;
import org.apache.hadoop.security.ssl.SSLFactory;
import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticatedURL;
import org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticator;
import org.apache.hadoop.security.token.delegation.web.KerberosDelegationTokenAuthenticator;
import org.apache.hadoop.security.token.delegation.web.PseudoDelegationTokenAuthenticator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.GeneralSecurityException;
import java.security.PrivilegedExceptionAction;

import static org.apache.atlas.security.SecurityProperties.CERT_STORES_CREDENTIAL_PROVIDER_PATH;
import static org.apache.atlas.security.SecurityProperties.CLIENT_AUTH_KEY;
import static org.apache.atlas.security.SecurityProperties.KEYSTORE_FILE_KEY;
import static org.apache.atlas.security.SecurityProperties.TRUSTSTORE_FILE_KEY;

/**
 *
 */
public class SecureClientUtils {

    public final static int DEFAULT_SOCKET_TIMEOUT = 1 * 60 * 1000; // 1 minute
    private static final Logger LOG = LoggerFactory.getLogger(SecureClientUtils.class);

    public static URLConnectionClientHandler getClientConnectionHandler(DefaultClientConfig config,
            org.apache.commons.configuration.Configuration clientConfig, String doAsUser,
            final UserGroupInformation ugi) {
        config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);
        Configuration conf = new Configuration();
        conf.addResource(conf.get(SSLFactory.SSL_CLIENT_CONF_KEY, SecurityProperties.SSL_CLIENT_PROPERTIES));
        UserGroupInformation.setConfiguration(conf);
        final ConnectionConfigurator connConfigurator = newConnConfigurator(conf);
        String authType = "simple";
        if (clientConfig != null) {
            authType = clientConfig.getString("atlas.http.authentication.type", "simple");
        }
        Authenticator authenticator = new PseudoDelegationTokenAuthenticator();
        if (!authType.equals("simple")) {
            authenticator = new KerberosDelegationTokenAuthenticator();
        }
        authenticator.setConnectionConfigurator(connConfigurator);
        final DelegationTokenAuthenticator finalAuthenticator = (DelegationTokenAuthenticator) authenticator;
        final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
        HttpURLConnectionFactory httpURLConnectionFactory = null;
        try {
            UserGroupInformation ugiToUse = ugi != null ? ugi : UserGroupInformation.getCurrentUser();
            final UserGroupInformation actualUgi =
                    (ugiToUse.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY)
                    ? ugiToUse.getRealUser() : ugiToUse;
            LOG.info("Real User: {}, is from ticket cache? {}", actualUgi, actualUgi.isLoginTicketBased());
            if (StringUtils.isEmpty(doAsUser)) {
                doAsUser = actualUgi.getShortUserName();
            }
            LOG.info("doAsUser: {}", doAsUser);
            final String finalDoAsUser = doAsUser;
            httpURLConnectionFactory = new HttpURLConnectionFactory() {
                @Override
                public HttpURLConnection getHttpURLConnection(final URL url) throws IOException {
                    try {
                        return actualUgi.doAs(new PrivilegedExceptionAction<HttpURLConnection>() {
                            @Override
                            public HttpURLConnection run() throws Exception {
                                try {
                                    return new DelegationTokenAuthenticatedURL(finalAuthenticator, connConfigurator)
                                        .openConnection(url, token, finalDoAsUser);
                                } catch (Exception e) {
                                    throw new IOException(e);
                                }
                            }
                        });
                    } catch (Exception e) {
                        if (e instanceof IOException) {
                            throw (IOException) e;
                        } else {
                            throw new IOException(e);
                        }
                    }
                }
            };
        } catch (IOException e) {
            LOG.warn("Error obtaining user", e);
        }

        return new URLConnectionClientHandler(httpURLConnectionFactory);
    }

    private final static ConnectionConfigurator DEFAULT_TIMEOUT_CONN_CONFIGURATOR = new ConnectionConfigurator() {
        @Override
        public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
            setTimeouts(conn, DEFAULT_SOCKET_TIMEOUT);
            return conn;
        }
    };

    private static ConnectionConfigurator newConnConfigurator(Configuration conf) {
        try {
            return newSslConnConfigurator(DEFAULT_SOCKET_TIMEOUT, conf);
        } catch (Exception e) {
            LOG.debug("Cannot load customized ssl related configuration. " + "Fallback to system-generic settings.", e);
            return DEFAULT_TIMEOUT_CONN_CONFIGURATOR;
        }
    }

    private static ConnectionConfigurator newSslConnConfigurator(final int timeout, Configuration conf)
    throws IOException, GeneralSecurityException {
        final SSLFactory factory;
        final SSLSocketFactory sf;
        final HostnameVerifier hv;

        factory = new SSLFactory(SSLFactory.Mode.CLIENT, conf);
        factory.init();
        sf = factory.createSSLSocketFactory();
        hv = factory.getHostnameVerifier();

        return new ConnectionConfigurator() {
            @Override
            public HttpURLConnection configure(HttpURLConnection conn) throws IOException {
                if (conn instanceof HttpsURLConnection) {
                    HttpsURLConnection c = (HttpsURLConnection) conn;
                    c.setSSLSocketFactory(sf);
                    c.setHostnameVerifier(hv);
                }
                setTimeouts(conn, timeout);
                return conn;
            }
        };
    }

    private static void setTimeouts(URLConnection connection, int socketTimeout) {
        connection.setConnectTimeout(socketTimeout);
        connection.setReadTimeout(socketTimeout);
    }

    private static File getSSLClientFile() throws AtlasException {
        String confLocation = System.getProperty("atlas.conf");
        File sslDir;
        try {
            if (confLocation == null) {
                String persistDir = null;
                URL resource = SecureClientUtils.class.getResource("/");
                if (resource != null) {
                    persistDir = resource.toURI().getPath();
                }
                assert persistDir != null;
                sslDir = new File(persistDir);
            } else {
                sslDir = new File(confLocation);
            }
            LOG.info("ssl-client.xml will be created in {}", sslDir);
        } catch (Exception e) {
            throw new AtlasException("Failed to find client configuration directory", e);
        }
        return new File(sslDir, SecurityProperties.SSL_CLIENT_PROPERTIES);
    }

    public static void persistSSLClientConfiguration(org.apache.commons.configuration.Configuration clientConfig)
    throws AtlasException, IOException {
        //trust settings
        Configuration configuration = new Configuration(false);
        File sslClientFile = getSSLClientFile();
        if (!sslClientFile.exists()) {
            configuration.set("ssl.client.truststore.type", "jks");
            configuration.set("ssl.client.truststore.location", clientConfig.getString(TRUSTSTORE_FILE_KEY));
            if (clientConfig.getBoolean(CLIENT_AUTH_KEY, false)) {
                // need to get client key properties
                configuration.set("ssl.client.keystore.location", clientConfig.getString(KEYSTORE_FILE_KEY));
                configuration.set("ssl.client.keystore.type", "jks");
            }
            // add the configured credential provider
            configuration.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
                    clientConfig.getString(CERT_STORES_CREDENTIAL_PROVIDER_PATH));
            String hostnameVerifier = clientConfig.getString(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY);
            if (hostnameVerifier != null) {
                configuration.set(SSLFactory.SSL_HOSTNAME_VERIFIER_KEY, hostnameVerifier);
            }

            configuration.writeXml(new FileWriter(sslClientFile));
        }
    }

}


text:
package gw.internal.gosu.parser;

import gw.internal.gosu.parser.expressions.BlockExpression;
import gw.internal.gosu.parser.expressions.Identifier;
import gw.internal.gosu.parser.expressions.MethodCallExpression;
import gw.internal.gosu.parser.statements.ClassFileStatement;
import gw.internal.gosu.parser.statements.ClassStatement;
import gw.internal.gosu.parser.statements.MethodCallStatement;
import gw.internal.gosu.parser.statements.NoOpStatement;
import gw.internal.gosu.parser.statements.VarStatement;
import gw.lang.parser.GosuParserTypes;
import gw.lang.parser.ICapturedSymbol;
import gw.lang.parser.IReducedSymbol;
import gw.lang.parser.ISymbol;
import gw.lang.parser.ISymbolTable;
import gw.lang.parser.Keyword;
import gw.lang.parser.ScriptPartId;
import gw.lang.parser.exceptions.ParseResultsException;
import gw.lang.parser.statements.IUsesStatement;
import gw.lang.reflect.FunctionType;
import gw.lang.reflect.IParameterInfo;
import gw.lang.reflect.IType;
import gw.lang.reflect.TypeSystem;
import gw.lang.reflect.gs.IGosuConstructorInfo;
import gw.lang.reflect.java.GosuTypes;
import gw.lang.reflect.java.JavaTypes;
import gw.util.fingerprint.FP64;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 */
public class GosuClassParseInfo {
  transient private IGosuClassInternal _gosuClass;
  transient private ClassStatement _classStmt;
  transient private ParseResultsException _pe;
  transient private List<DynamicFunctionSymbol> _listStaticFunctions;
  transient private Map<String, DynamicFunctionSymbol> _mapMemberFunctions;
  transient private Map<String, DynamicFunctionSymbol> _mapConstructorFunctions;
  transient private List<DynamicPropertySymbol> _listStaticProperties;
  transient private Map<String, DynamicPropertySymbol> _mapMemberProperties;
  transient private Map<String, VarStatement> _mapStaticFields;
  transient private Map<String, VarStatement> _mapMemberFields;
  transient private Map<CharSequence, ISymbol> _memberFieldIndexByName;
  transient private Symbol _thisSymbol;
  transient private Map<String, ICapturedSymbol> _capturedSymbols;
  transient private long _sourceFingerprint;

  transient private BlockExpression _block;

  public GosuClassParseInfo(IGosuClassInternal gosuClass) {
    _gosuClass = gosuClass;
    _classStmt = new ClassStatement(gosuClass);
    _listStaticFunctions = Collections.emptyList();
    _mapMemberFunctions = Collections.emptyMap();
    _mapConstructorFunctions = Collections.emptyMap();
    _listStaticProperties = Collections.emptyList();
    _mapMemberProperties = Collections.emptyMap();
    _mapStaticFields = Collections.emptyMap();
    _mapMemberFields = Collections.emptyMap();
    _memberFieldIndexByName = Collections.emptyMap();
    _capturedSymbols = Collections.emptyMap();
  }

  public ClassStatement getClassStatement() {
    return _classStmt;
  }

  public ClassFileStatement getClassFileStatement() {
    return (ClassFileStatement) _classStmt.getParent();
  }

  public void setParseResultsException(ParseResultsException pe) {
    _pe = pe;
  }

  public ParseResultsException getParseResultsException() {
    return _pe;
  }

  public void addStaticFunction( DynamicFunctionSymbol function )
  {
    assert function.isClassMember();
    if( _listStaticFunctions == Collections.EMPTY_LIST )
    {
      _listStaticFunctions = new ArrayList<DynamicFunctionSymbol>( 2 );
    }
    else
    {
      // Remove duplicates. Remain consistent with how non-static functions are maintained (i.e., Map.put() replaces duplicate)
      _listStaticFunctions.remove( function );
    }

    _listStaticFunctions.add( function );
  }

  private void clearDebugInfoOnFunctions( Collection<DynamicFunctionSymbol> mapFunctions )
  {
    for( DynamicFunctionSymbol function : mapFunctions )
    {
      function.clearDebugInfo();
    }
  }

  private void clearDebugInfoOnProperties( Collection<DynamicPropertySymbol> mapProperties )
  {
    for( DynamicPropertySymbol property : mapProperties )
    {
      property.clearDebugInfo();
    }
  }

  private void clearDebugInfoOnAnnotations( List<IGosuAnnotation> annotations )
  {
    if( annotations != null )
    {
      for( IGosuAnnotation annotation : annotations )
      {
        if( annotation instanceof GosuAnnotation)
        {
          ((GosuAnnotation)annotation).clearDebugInfo();
        }
      }
    }
  }

  private void clearDebugInfoOnFields( Collection<VarStatement> fields )
  {
    for( VarStatement field : fields )
    {
      field.clearParseTreeInformation();
    }
  }

  public List<DynamicFunctionSymbol> getStaticFunctions() {
    return _listStaticFunctions;
  }

  public Map<String, DynamicFunctionSymbol> getMemberFunctions() {
    return _mapMemberFunctions;
  }

  public void addMemberFunction( DynamicFunctionSymbol function )
  {
    assert function.isClassMember();
    if( function.isStatic() )
    {
      addStaticFunction( function );
      return;
    }
    if( _mapMemberFunctions == Collections.EMPTY_MAP )
    {
      //noinspection unchecked
      _mapMemberFunctions = new LinkedHashMap( 2 );
    }
    _mapMemberFunctions.put( function.getName(), function );
  }

  public Map<String, DynamicFunctionSymbol> getConstructorFunctions() {
    return _mapConstructorFunctions;
  }

  public void addConstructorFunction( DynamicFunctionSymbol function )
  {
    if( _mapConstructorFunctions == Collections.EMPTY_MAP )
    {
      //noinspection unchecked
      _mapConstructorFunctions = new LinkedHashMap(2);
    }
    _mapConstructorFunctions.put( function.getName(), function);
  }

  protected boolean addDefaultConstructor( ISymbolTable symbolTable )
  {
    NoOpStatement value = new NoOpStatement();
    value.initEmptyParseTree();
    DynamicFunctionSymbol dfsCtor =
      new DynamicFunctionSymbol( symbolTable, _gosuClass.getRelativeName(), GosuTypes.DEF_CTOR_TYPE(), null, value );
    dfsCtor.setScriptPart( new ScriptPartId(_gosuClass, null ) );
    if( _gosuClass.getSuperClass() != null )
    {
      // If the supertype is Enum, we need to look for a super constructor that takes (String, int) instead of a no-arg one
      // The appropriate arguments to super() will be generated by the compiler and won't appear in the parse tree
      DynamicFunctionSymbol defCtorFromSuper;
      if( _gosuClass.getSupertype().getGenericType() == JavaTypes.ENUM() )
      {
        defCtorFromSuper = _gosuClass.getSuperClass().getConstructorFunction( "Enum(java.lang.String, int)" );
      }
      else
      {
        defCtorFromSuper = _gosuClass.getSuperClass().getDefaultConstructor();
      }

      if( defCtorFromSuper == null || !_gosuClass.getSuperClass().isAccessible( _gosuClass, defCtorFromSuper ) )
      {
        return false;
      }
      MethodCallExpression e = new MethodCallExpression();
      e.setFunctionSymbol( new SuperConstructorFunctionSymbol( defCtorFromSuper ) );
      e.setArgs( null );
      e.setType( GosuParserTypes.NULL_TYPE() );
      MethodCallStatement initializer = new MethodCallStatement();
      initializer.setMethodCall( e );
      dfsCtor.setInitializer( initializer );
    }
    else
    {
      MethodCallExpression e = new MethodCallExpression();
      e.setFunctionSymbol( new InitConstructorFunctionSymbol( symbolTable ) );
      e.setArgs( null );
      e.setType( GosuParserTypes.NULL_TYPE() );
      MethodCallStatement initializer = new MethodCallStatement();
      initializer.setMethodCall( e );
      dfsCtor.setInitializer( initializer );
    }
    if( _mapConstructorFunctions == Collections.EMPTY_MAP )
    {
      //noinspection unchecked
      _mapConstructorFunctions = new LinkedHashMap(2);
    }
    if( _gosuClass.isEnum() )
    {
      dfsCtor.setPrivate( true );
    }
    _mapConstructorFunctions.put( dfsCtor.getName(), dfsCtor );
    return true;
  }

  boolean addAnonymousConstructor( ISymbolTable symTable, GosuConstructorInfo superCtor )
  {
    symTable.pushIsolatedScope(new GosuClassTransparentActivationContext(_gosuClass, true));
    try
    {
      NoOpStatement value = new NoOpStatement();
      value.initEmptyParseTree();
      List<ISymbol> argSymbols = makeArgSymbols( superCtor, symTable );
      DynamicFunctionSymbol dfsCtor =
        new DynamicFunctionSymbol( symTable, _gosuClass.getRelativeName(),
                                   new FunctionType( GosuTypes.DEF_CTOR_TYPE().getDisplayName(), JavaTypes.pVOID(), typesFromSymbols( argSymbols ) ),
                                   argSymbols, value );
      dfsCtor.setScriptPart( new ScriptPartId(_gosuClass, null ) );
      IGosuConstructorInfo ctorFromSuper = superCtor;
      while( ctorFromSuper instanceof ParameterizedGosuConstructorInfo )
      {
        ctorFromSuper = ctorFromSuper.getBackingConstructorInfo();
      }
      MethodCallExpression e = new MethodCallExpression();
      DynamicFunctionSymbol dfsCtorFromSuper;
      if( ctorFromSuper == null || !_gosuClass.getSuperClass().isAccessible( _gosuClass, dfsCtorFromSuper = getSuperDfsFromSuperCtor( ctorFromSuper ) ) )
      {
        return false;
      }
      e.setFunctionSymbol( new SuperConstructorFunctionSymbol( dfsCtorFromSuper ) );
      e.setArgs( makeArgs( argSymbols, symTable ) );
      e.setType( GosuParserTypes.NULL_TYPE() );
      MethodCallStatement initializer = new MethodCallStatement();
      initializer.setMethodCall( e );
      dfsCtor.setInitializer( initializer );

      if( _mapConstructorFunctions == Collections.EMPTY_MAP )
      {
        //noinspection unchecked
        _mapConstructorFunctions = new LinkedHashMap(2);
      }
      _mapConstructorFunctions.put( dfsCtor.getName(), dfsCtor );
      return true;
    }
    finally
    {
      symTable.popScope();
    }
  }

  private DynamicFunctionSymbol getSuperDfsFromSuperCtor(IGosuConstructorInfo ctorFromSuper) {
    IGosuClassInternal gsClass = (IGosuClassInternal) ctorFromSuper.getOwnersType();
    List<DynamicFunctionSymbol> constructors = gsClass.getConstructorFunctions();
    for (DynamicFunctionSymbol constructor : constructors) {
      if (equals(constructor, ctorFromSuper)) {
        return constructor;
      }
    }
    return null;
  }

  private boolean equals(DynamicFunctionSymbol constructor, IGosuConstructorInfo ctorFromSuper) {
    IType[] args1 = constructor.getArgTypes();
    List<IReducedSymbol> args2 = ctorFromSuper.getArgs();
    if (args1.length != args2.size()) {
      return false;
    }
    for (int i = 0; i < args1.length; i++) {
      if (!args1[i].equals(args2.get(i).getType())) {
        return false;
      }
    }
    return true;
  }

  private Identifier[] makeArgs( List<ISymbol> argSymbols, ISymbolTable symTable )
  {
    Identifier[] args = new Identifier[argSymbols.size()];
    for( int i = 0; i < args.length; i++ )
    {
      ISymbol sym = argSymbols.get( i );
      Identifier id = new Identifier();
      id.setSymbol( sym, symTable );
      id.setType( sym.getType() );
      args[i] = id;
    }
    return args;
  }

  private List<ISymbol> makeArgSymbols( GosuConstructorInfo ci, ISymbolTable symTable )
  {
    if(ci == null)
    {
      return Collections.emptyList();
    }
    int i = 0;
    List<ISymbol> args = new ArrayList<ISymbol>( ci.getParameters().length );
    for( IParameterInfo pi : ci.getParameters() )
    {
      Symbol sym = new Symbol( "p" + i++, pi.getFeatureType(), symTable, null );
      symTable.putSymbol( sym );
      args.add( sym );
    }
    return args;
  }

  private IType[] typesFromSymbols( List<ISymbol> argSymbols )
  {
    if( argSymbols.size() == 0 )
    {
      return IType.EMPTY_ARRAY;
    }

    IType[] types = new IType[argSymbols.size()];
    for( int i = 0; i < types.length; i++ )
    {
      types[i] = argSymbols.get( i ).getType();
    }
    return types;
  }

  public void addStaticProperty( DynamicPropertySymbol property )
  {
    if( _listStaticProperties == Collections.EMPTY_LIST )
    {
      _listStaticProperties = new ArrayList<DynamicPropertySymbol>( 2 );
    }
    _listStaticProperties.add( property );
  }

  public List<DynamicPropertySymbol> getStaticProperties() {
    return _listStaticProperties;
  }

  public Map<String, VarStatement> getMemberFields() {
    return _mapMemberFields;
  }

  public void addMemberProperty( DynamicPropertySymbol property )
  {
    if( property.isStatic() )
    {
      addStaticProperty(property);
      return;
    }
    if( _mapMemberProperties == Collections.EMPTY_MAP )
    {
      //noinspection unchecked
      _mapMemberProperties = new LinkedHashMap(2);
    }
    _mapMemberProperties.put( property.getName(), property );
  }

  private void addStaticField( VarStatement varStmt )
  {
    // Static vars must be maintained in the order declared. They must evaluate in that order.
    if( _mapStaticFields == Collections.EMPTY_MAP )
    {
      //noinspection unchecked
      _mapStaticFields = new LinkedHashMap(2);
    }
    _mapStaticFields.put( varStmt.getIdentifierName(), varStmt );
  }

  public Map<String, DynamicPropertySymbol> getMemberProperties() {
    return _mapMemberProperties;
  }

  public Map<String, VarStatement> getStaticFields() {
    return _mapStaticFields;
  }

  public void addMemberField( VarStatement varStmt )
  {
    if( varStmt.isStatic() )
    {
      addStaticField( varStmt );
      return;
    }
    if( _mapMemberFields == Collections.EMPTY_MAP )
    {
      //noinspection unchecked
      _mapMemberFields = new LinkedHashMap(2);
    }
    // Static vars must be maintained in the order declared. They must evaluate in that order.
    String varName = varStmt.getIdentifierName();
    _mapMemberFields.put( varName, varStmt );
    if( !_memberFieldIndexByName.containsKey( varName ) )
    {
      int iIndex = _memberFieldIndexByName.size();
      if( _memberFieldIndexByName == Collections.EMPTY_MAP )
      {
        _memberFieldIndexByName = new HashMap<CharSequence, ISymbol>( 4 );
      }
      _memberFieldIndexByName.put( varName, new MemberFieldSymbol( iIndex, varName ) );
    }

    if (_gosuClass instanceof GosuProgram) {
      // Remove initializers, fields are assigned in the programs entry point function
      varStmt.setAsExpression( null );
    }
  }

  public Map<CharSequence, ISymbol> getMemberFieldIndexByName() {
    return _memberFieldIndexByName;
  }

  public Symbol getStaticThisSymbol()
  {
    if( _thisSymbol == null )
    {
      if( _gosuClass.isParameterizedType() )
      {
        GosuClass genericType = (GosuClass) _gosuClass.getGenericType();
        _thisSymbol = ((GosuClass) genericType.dontEverCallThis()).getStaticThisSymbol();
      }
      else
      {
        _thisSymbol = makeThisSymbol();
      }
    }
    return _thisSymbol;
  }

  private Symbol makeThisSymbol()
  {
    return new ReadOnlySymbol( Keyword.KW_this.getName(), TypeLord.getConcreteType( _gosuClass ), Symbol.MEMBER_STACK_PROVIDER, null );
  }

  public Map<String, ICapturedSymbol> getCapturedSymbols() {
    return _capturedSymbols;
  }

  public void addCapturedSymbolSilent( ICapturedSymbol sym )
  {
    if( _capturedSymbols.isEmpty() )
    {
      _capturedSymbols = new HashMap<String, ICapturedSymbol>( 2 );
    }
    _capturedSymbols.put( sym.getName(), sym );
  }

  public static void clear() {
//    int n = 0;
//    for (GosuClassParseInfo info : new ArrayList<GosuClassParseInfo>(_allParseInfos)) {
//      IGosuClassInternal gosuClass = info._gosuClass;
//      for (IGosuClassInternal parameterizedType : gosuClass.getParameterizedTypes()) {
//        parameterizedType.clearParseInfo();
//        n++;
//      }
//      gosuClass.clearParseInfo();
//      n++;
//    }
//    System.out.println("Dropped " + n);
//    _allParseInfos = null;
  }

  public void setBlock(BlockExpression blk) {
    _block = blk;
  }

  public BlockExpression getBlock() {
    return _block;
  }

  public void maybeClearDebugInfo() {
    if (_gosuClass.getTypeLoader().getModule().getExecutionEnvironment().isSingleModuleMode()) {
      TypeSystem.lock();
      try {
        if (!_gosuClass.getTypeLoader().shouldKeepDebugInfo(_gosuClass)) {
          clearDebugInfoOnFields(_mapStaticFields.values());
          clearDebugInfoOnFields(_mapMemberFields.values());
          clearDebugInfoOnProperties(_listStaticProperties);
          clearDebugInfoOnProperties(_mapMemberProperties.values());
          clearDebugInfoOnFunctions(_mapMemberFunctions.values());
          clearDebugInfoOnFunctions(_listStaticFunctions);
          clearDebugInfoOnFunctions(_mapConstructorFunctions.values());
          clearDebugInfoOnAnnotations(_gosuClass.getModifierInfo().getAnnotations());
          getClassStatement().clearParseTreeInformation();
          Set<IUsesStatement> usesStatements = _gosuClass.getTypeUsesMap() == null ? null : _gosuClass.getTypeUsesMap().getUsesStatements();
          if (usesStatements != null) {
            for (IUsesStatement usesStatement : usesStatements) {
              usesStatement.clearParseTreeInformation();
            }
          }
        }
      } finally {
        TypeSystem.unlock();
      }
    }
  }

  public void updateSource(String source) {
    _sourceFingerprint = new FP64(source).getRawFingerprint();
  }

  public long getSourceFingerprint() {
    return _sourceFingerprint;
  }
}


text:
ClassLike.prototype = new Connectable();           // Inheritance
ClassLike.prototype.constructor = ClassLike;

function ClassLike () {} // Abstract class

ClassLike.prototype.innitClassLike = function (desiredId, container) {
    this.inheritingFrom = null;
    this.toString = null;
    this.constructor = false;

    this.innitConnectable(desiredId, container);

    this.children = [];
};

ClassLike.prototype.setInheritingFrom = function (parentId) {
    var parent;

    if (parentId != null) {
        this.inheritingFrom = parentId;

        parent = Item.prototype.items[this.inheritingFrom];

        parent.children.push(this.id);
    } else { //Un-inherit
        parent = Item.prototype.items[this.inheritingFrom];

        parent.children.remove(this.id);

        this.inheritingFrom = null;
    }
};

ClassLike.prototype.getInheritedFrom = function () {
    return this.inheritingFrom;
};

ClassLike.prototype.inheritAttributes = function () {
    var parent = Item.prototype.items[this.inheritingFrom];
    var ia;

    for (var i = 0; i < parent.getNumberAttributes(); i++) {
        if (parent.getAttribute(i) instanceof InheritedAttribute)
            ia = new InheritedAttribute(parent.getAttribute(i).getParentId());
        else
            ia = new InheritedAttribute(parent.getAttribute(i).getId());

        this.addInheritedAttribute(ia);
    }

    // Has to skip the ones that are already inherited
    // May need to inherit to the grandchildren
};

ClassLike.prototype.unInheritAttributes = function () {
    var parent = Item.prototype.items[this.inheritingFrom];

    for (var i = 0; i < parent.getNumberAttributes(); i++) {
        var ia = parent.getAttribute(i);

        this.removeInheritedAttribute(ia);
    }

    // Uninherit to children
};

ClassLike.prototype.getParent = function () {
    if (this.inheritingFrom == null) {
        return null;
    } else {
        return Connectable.prototype.connectables[this.inheritingFrom];
    }
};

ClassLike.prototype.setToString = function (toString) {
    this.toString = toString;
};

ClassLike.prototype.getToString = function () {
    return this.toString;
};

ClassLike.prototype.destroyClassLike = function () {
    this.destroyConnectable();
};

ClassLike.prototype.setConstructor = function (c) {
    this.constructor = c;

    return this;
};

ClassLike.prototype.getConstructor = function () {
    return this.constructor;
};

ClassLike.prototype.canInheritFrom = function (potentialParent) {
    var i, j;
    var attribute;

    for (i = 0; i < potentialParent.getNumberAttributes(); i++) {
        attribute = potentialParent.getAttribute(i);

        for (j = 0; j < this.getNumberAttributes(); j++) {
            if (attribute.getName() === this.getAttribute(j).getName()) {
                return false;
            }
        }
    }

    if (this.children.length > 0) {
        for (i = 0; i < this.children.length; i++) {
            if (!Connectable.prototype.connectables[this.children[i]].canInheritFrom(potentialParent)) {
                return false;
            }
        }
    }

    return true;
};

ClassLike.prototype.getChildren = function ()
{
    return this.children;
};

ClassLike.prototype.getImplementing = function()
{
    var r = [];
    var link;

    for (var i in this.links) {
        link = Link.prototype.links[this.links[i]];

        if (undefined !== link && link.getType() === 'implements' && link.getFrom() === this.getId()) {
            r.push(link.getTo());
        }
    }

    return r;
};


text:
import numpy as np
from rmgpy.scoop_framework.util import logger as logging

CLOSE_TO_ZERO = 1E-20

def computeReactionRate(rxn, forward, T, P, coreSpeciesConcentrations):
    """

    Computes reaction rate r as follows:

    r = k * Product(Ci^nuij, for all j)
    with:

    k = rate coefficient for rxn,
    Cij = the concentration for molecule i ,
    nuij = the stoichiometric coefficient for molecule i in reaction j.

    ...
    """

    speciesList = rxn.reactants if forward == 'reactants' else rxn.products

    totconc = 1.0
    for spc in speciesList:
        ci = coreSpeciesConcentrations[spc.label]
        if abs(ci) < CLOSE_TO_ZERO:
            return 0.
        nui = rxn.getStoichiometricCoefficient(spc, forward)
        conc = ci**nui

        totconc *= conc

    k = rxn.getRateCoefficient(T,P) if forward == 'reactants' else rxn.getReverseRateCoefficient(T,P)
    r = k * totconc

    return r

def calcRij(rxn, spc, isReactant, T, P, coreSpeciesConcentrations):
    """
    This function computes the rate of formation of species i
    through the reaction j.

    This function multiplies:
    - nu(i): stoichiometric coefficient of spc in rxn
    - r(rxn): reaction rate of rxn

    Returns a reaction rate

    Units: mol / m^3 s
    """

    nui = rxn.getStoichiometricCoefficient(spc, isReactant)
    sign = -1 if isReactant else 1

    forward = isReactant

    rj = computeReactionRate(rxn, forward, T, P, coreSpeciesConcentrations)

    rij = nui * sign * rj
    return rij

def calcRf(spc, reactions, reactantOrProduct, T, P, coreSpeciesConcentrations, formationOrConsumption):
    """
    Calculates the total rate of formation/consumption of species i.

    Computes the sum of the rates of formation/consumption of spc for all of
    the reactions in which spc is a product.

    if formationOrConsumption == 'formation', spc will be compared to the
    products of the reaction. Else, spc will be compared to the reactants of
    the reaction.

    units of rate: mol/(m^3.s)
    """
    rate = 0.0

    for reaction in reactions:
        molecules = reaction.products if formationOrConsumption == 'formation:' else reaction.reactants
        labels = [mol.label for mol in molecules]
        if spc.label in labels:
            rij = calcRij(reaction, spc,  reactantOrProduct, T, P, coreSpeciesConcentrations)
            rate = rate + rij

    logging.debug('Rf: {rate}'.format(**locals()))

    return rate

def calcRfClosure(spc, reactions, reactantOrProduct, T, P, coreSpeciesConcentrations):
    """
    Closure to avoid replicating function calls to calcRf.
    """
    def myfilter(formationOrConsumption):
        return calcRf(spc, reactions, reactantOrProduct, T, P, coreSpeciesConcentrations, formationOrConsumption)

    return myfilter

def calcRi(spc,rij, reactions, reactantOrProduct, T, P, coreSpeciesConcentrations):
    """

    Checks whether the sign of rij to decide to compute the
    total rate of formation or consumption of spc.

    units of rate: mol/(m^3.s)
    """

    closure = calcRfClosure(spc, reactions, reactantOrProduct, T, P, coreSpeciesConcentrations)

    if rij > 0:
        return closure('formation')
    elif rij < 0:
        return closure('consumption')
    elif np.absolute([rij]) < CLOSE_TO_ZERO:
        """Pick the largest value so that the ratio rij / RX remains small."""
        Rf = closure('formation')
        Rb = closure('consumption')

        """What happens when Rf ~ Rb <<< 1?"""
        return max(abs(Rf),abs(Rb))

def isImportant(rxn, spc, reactions, reactantOrProduct, tolerance, T, P, coreSpeciesConcentrations):
    """
    This function computes:
    - Ri = R(spc)
    - rij = r(rxn)
    - alpha = ratio of rij / Ri

    Range of values of alpha:
    0 <= alpha <= 1

    This function also compares alpha to a user-defined tolerance TOLERANCE.
    if alpha >= tolerance:
        this reaction is important for this species.
    else:
        this reaction is unimportant for this species.

    Returns whether or not rxn is important for spc.
    keep = True
    remove = False
    """

    rij = calcRij(rxn, spc, reactantOrProduct, T, P, coreSpeciesConcentrations)
    Ri = calcRi(spc, rij, reactions, reactantOrProduct, T, P, coreSpeciesConcentrations)

    logging.debug("rij: {rij}, Ri: {Ri}, rxn: {rxn}, species: {spc}, reactant: {reactantOrProduct}, tol: {tolerance}"\
    .format(**locals()))

    if np.any(np.absolute([rij, Ri]) < CLOSE_TO_ZERO):
       return False

    else:
        assert Ri != 0, "rij: {0}, Ri: {1}, rxn: {2}, species: {3}, reactant: {4}".format(rij, Ri, rxn, spc, reactantOrProduct)
        alpha = rij / Ri
        if alpha < 0: return False

    if alpha > tolerance :
        """
        If both values are very close to 1, then the comparison of alpha and the tolerance
        might sometimes return an unexpected value.

        When we set the tolerance to a value of 1, we want all the reactions to be unimportant,
        regardless of the value of alpha.

        """
        if np.allclose([tolerance, alpha], [1.0, 1.0]):
            return False

        return True
        #where tolerance is user specified tolerance

    elif alpha <= tolerance:
        return False


text:
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT

namespace SilverNeedle
{
    using System.Collections.Generic;

    /// <summary>
    /// Represents an entity that can modify stats
    /// </summary>
    public interface IModifiesStats
    {
        /// <summary>
        /// Gets the modifiers for the stats that are to be modified.
        /// </summary>
        /// <value>The modifiers for stats effected by this class.</value>
        IList<IValueStatModifier> Modifiers { get; }
    }
}


text:
#ifndef __ColourFaderAffector2_H__
#define __ColourFaderAffector2_H__

#include "OgreParticleFXPrerequisites.h"
#include "OgreParticleAffector.h"
#include "OgreStringInterface.h"

namespace Ogre {

    /** This plugin subclass of ParticleAffector allows you to alter the colour of particles.
    @remarks
        This class supplies the ParticleAffector implementation required to modify the colour of
        particle in mid-flight.
    */
    class _OgreParticleFXExport ColourFaderAffector2 : public ParticleAffector
    {
    public:

        /** Command object for red adjust (see ParamCommand).*/
        class CmdRedAdjust1 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for green adjust (see ParamCommand).*/
        class CmdGreenAdjust1 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for blue adjust (see ParamCommand).*/
        class CmdBlueAdjust1 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for alpha adjust (see ParamCommand).*/
        class CmdAlphaAdjust1 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for red adjust (see ParamCommand).*/
        class CmdRedAdjust2 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for green adjust (see ParamCommand).*/
        class CmdGreenAdjust2 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for blue adjust (see ParamCommand).*/
        class CmdBlueAdjust2 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for alpha adjust (see ParamCommand).*/
        class CmdAlphaAdjust2 : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Command object for alpha adjust (see ParamCommand).*/
        class CmdStateChange : public ParamCommand
        {
        public:
            String doGet(const void* target) const;
            void doSet(void* target, const String& val);
        };

        /** Default constructor. */
        ColourFaderAffector2(ParticleSystem* psys);

        /** See ParticleAffector. */
        void _affectParticles(ParticleSystem* pSystem, Real timeElapsed);

        /** Sets the colour adjustment to be made per second to particles.
        @param red, green, blue, alpha
            Sets the adjustment to be made to each of the colour components per second. These
            values will be added to the colour of all particles every second, scaled over each frame
            for a smooth adjustment.
        */
        void setAdjust1(float red, float green, float blue, float alpha = 0.0);
        void setAdjust2(float red, float green, float blue, float alpha = 0.0);
        /** Sets the red adjustment to be made per second to particles.
        @param red
            The adjustment to be made to the colour component per second. This
            value will be added to the colour of all particles every second, scaled over each frame
            for a smooth adjustment.
        */
        void setRedAdjust1(float red);
        void setRedAdjust2(float red);

        /** Gets the red adjustment to be made per second to particles. */
        float getRedAdjust1(void) const;
        float getRedAdjust2(void) const;

        /** Sets the green adjustment to be made per second to particles.
        @param green
            The adjustment to be made to the colour component per second. This
            value will be added to the colour of all particles every second, scaled over each frame
            for a smooth adjustment.
        */
        void setGreenAdjust1(float green);
        void setGreenAdjust2(float green);
        /** Gets the green adjustment to be made per second to particles. */
        float getGreenAdjust1(void) const;
        float getGreenAdjust2(void) const;
        /** Sets the blue adjustment to be made per second to particles.
        @param blue
            The adjustment to be made to the colour component per second. This
            value will be added to the colour of all particles every second, scaled over each frame
            for a smooth adjustment.
        */
        void setBlueAdjust1(float blue);
        void setBlueAdjust2(float blue);
        /** Gets the blue adjustment to be made per second to particles. */
        float getBlueAdjust1(void) const;
        float getBlueAdjust2(void) const;

        /** Sets the alpha adjustment to be made per second to particles.
        @param alpha
            The adjustment to be made to the colour component per second. This
            value will be added to the colour of all particles every second, scaled over each frame
            for a smooth adjustment.
        */
        void setAlphaAdjust1(float alpha);
        void setAlphaAdjust2(float alpha);
        /** Gets the alpha adjustment to be made per second to particles. */
        float getAlphaAdjust1(void) const;
        float getAlphaAdjust2(void) const;

        void setStateChange(Real NewValue );
        Real getStateChange(void) const;

        static CmdRedAdjust1 msRedCmd1;
        static CmdRedAdjust2 msRedCmd2;
        static CmdGreenAdjust1 msGreenCmd1;
        static CmdGreenAdjust2 msGreenCmd2;
        static CmdBlueAdjust1 msBlueCmd1;
        static CmdBlueAdjust2 msBlueCmd2;
        static CmdAlphaAdjust1 msAlphaCmd1;
        static CmdAlphaAdjust2 msAlphaCmd2;
        static CmdStateChange msStateCmd;

    protected:
        float mRedAdj1, mRedAdj2;
        float mGreenAdj1,  mGreenAdj2;
        float mBlueAdj1, mBlueAdj2;
        float mAlphaAdj1, mAlphaAdj2;
        Real StateChangeVal;

        /** Internal method for adjusting while clamping to [0,1] */
        inline void applyAdjustWithClamp(float* pComponent, float adjust)
        {
            *pComponent += adjust;
            // Limit to 0
            if (*pComponent < 0.0)
            {
                *pComponent = 0.0f;
            }
            // Limit to 1
            else if (*pComponent > 1.0)
            {
                *pComponent = 1.0f;
            }
        }

    };

}

#endif


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

    <com.hss01248.image.bigimage2.MyLargeImageView
        android:layout_width="match_parent"
        android:id="@+id/my_big_image"
        android:layout_height="match_parent" />

    <pl.droidsonroids.gif.GifImageView
        android:id="@+id/gifview"
        android:layout_width="match_parent"
        android:visibility="gone"
        android:layout_height="match_parent" />
</FrameLayout>


text:
require "govuk_security_audit/version"

module GovukSecurityAudit
end