text:
NSString * const kAFOAuthCodeGrantType = @"authorization_code";
NSString * const kAFOAuthClientCredentialsGrantType = @"client_credentials";
NSString * const kAFOAuthPasswordCredentialsGrantType = @"password";
NSString *const kAFOAuthPasswordCredentialsResponseType = @"code";
NSString * const kAFOAuthRefreshGrantType = @"refresh_token";

#ifdef _SECURITY_SECITEM_H_
NSString * const kAFOAuthCredentialServiceName = @"AFOAuthCredentialService";

static NSMutableDictionary * AFKeychainQueryDictionaryWithIdentifier(NSString *identifier) {
    NSMutableDictionary *queryDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:(__bridge id)kSecClassGenericPassword, kSecClass, kAFOAuthCredentialServiceName, kSecAttrService, nil];
    [queryDictionary setValue:identifier forKey:(__bridge id)kSecAttrAccount];

    return queryDictionary;
}
#endif

#pragma mark -

@interface AFOAuth2Client ()
@property (readwrite, nonatomic) NSString *serviceProviderIdentifier;
@property (readwrite, nonatomic) NSString *clientID;
@property (readwrite, nonatomic) NSString *secret;
@end

@implementation AFOAuth2Client

+ (instancetype)clientWithBaseURL:(NSURL *)url
                         clientID:(NSString *)clientID
                           secret:(NSString *)secret
{
    return [[self alloc] initWithBaseURL:url clientID:clientID secret:secret];
}

- (id)initWithBaseURL:(NSURL *)url
             clientID:(NSString *)clientID
               secret:(NSString *)secret
{
    NSParameterAssert(clientID);

    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    self.serviceProviderIdentifier = [self.baseURL host];
    self.clientID = clientID;
    self.secret = secret;

    return self;
}

#pragma mark -

- (void)setAuthorizationHeaderWithToken:(NSString *)token {
    // Use the "Bearer" type as an arbitrary default
    [self setAuthorizationHeaderWithToken:token ofType:@"Bearer"];
}

- (void)setAuthorizationHeaderWithCredential:(AFOAuthCredential *)credential {
    [self setAuthorizationHeaderWithToken:credential.accessToken ofType:credential.tokenType];
}

- (void)setAuthorizationHeaderWithToken:(NSString *)token
                                 ofType:(NSString *)type
{
    // See http://tools.ietf.org/html/rfc6749#section-7.1
    if ([[type lowercaseString] isEqualToString:@"bearer"]) {
        AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
        [serializer setValue:[NSString stringWithFormat:@"Bearer %@", token] forHTTPHeaderField:@"Authorization"];
        self.requestSerializer = serializer;

    }
}

#pragma mark -

- (void)authenticateUsingOAuthWithURLString:(NSString *)urlString
                                   username:(NSString *)username
                                   password:(NSString *)password
                                      scope:(NSString *)scope
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure
{
    NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
    [mutableParameters setObject:kAFOAuthPasswordCredentialsGrantType forKey:@"grant_type"];
    [mutableParameters setObject:kAFOAuthPasswordCredentialsResponseType forKey:@"response_type"];
    [mutableParameters setValue:username forKey:@"username"];
    [mutableParameters setValue:password forKey:@"password"];
    [mutableParameters setValue:scope forKey:@"scope"];
    NSDictionary *parameters = [NSDictionary dictionaryWithDictionary:mutableParameters];

    [self authenticateUsingOAuthWithURLString:urlString parameters:parameters success:success failure:failure];
}

- (void)authenticateUsingOAuthWithURLString:(NSString *)urlString
                                      scope:(NSString *)scope
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure
{
    NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
    [mutableParameters setObject:kAFOAuthClientCredentialsGrantType forKey:@"grant_type"];
    [mutableParameters setValue:scope forKey:@"scope"];
    NSDictionary *parameters = [NSDictionary dictionaryWithDictionary:mutableParameters];

    [self authenticateUsingOAuthWithURLString:urlString parameters:parameters success:success failure:failure];
}

- (void)authenticateUsingOAuthWithURLString:(NSString *)urlString
                               refreshToken:(NSString *)refreshToken
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure
{
    NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
    [mutableParameters setObject:kAFOAuthRefreshGrantType forKey:@"grant_type"];
    [mutableParameters setValue:refreshToken forKey:@"refresh_token"];
    NSDictionary *parameters = [NSDictionary dictionaryWithDictionary:mutableParameters];

    [self authenticateUsingOAuthWithURLString:urlString parameters:parameters success:success failure:failure];
}

- (void)authenticateUsingOAuthWithURLString:(NSString *)urlString
                                       code:(NSString *)code
                                redirectURI:(NSString *)uri
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure
{
    NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
    [mutableParameters setObject:kAFOAuthCodeGrantType forKey:@"grant_type"];
    [mutableParameters setValue:code forKey:@"code"];
    [mutableParameters setValue:uri forKey:@"redirect_uri"];
    NSDictionary *parameters = [NSDictionary dictionaryWithDictionary:mutableParameters];

    [self authenticateUsingOAuthWithURLString:urlString parameters:parameters success:success failure:failure];
}

- (void)authenticateUsingOAuthWithURLString:(NSString *)urlString
                                 parameters:(NSDictionary *)parameters
                                    success:(void (^)(AFOAuthCredential *credential))success
                                    failure:(void (^)(NSError *error))failure
{
    NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
    [mutableParameters setObject:self.clientID forKey:@"client_id"];
    [mutableParameters setValue:self.secret forKey:@"client_secret"];
    parameters = [NSDictionary dictionaryWithDictionary:mutableParameters];

    self.requestSerializer = [AFHTTPRequestSerializer serializer];

    NSMutableURLRequest *mutableRequest = [self.requestSerializer requestWithMethod:@"POST" URLString:urlString parameters:parameters];
    [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    AFHTTPRequestOperation *requestOperation = [self HTTPRequestOperationWithRequest:mutableRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject valueForKey:@"error"]) {
            if (failure) {
                // TODO: Resolve the `error` field into a proper NSError object
                // http://tools.ietf.org/html/rfc6749#section-5.2
                failure(nil);
            }

            return;
        }

        NSString *refreshToken = [responseObject valueForKey:@"refresh_token"];
        if (refreshToken == nil || [refreshToken isEqual:[NSNull null]]) {
            refreshToken = [parameters valueForKey:@"refresh_token"];
        }

        AFOAuthCredential *credential = [AFOAuthCredential credentialWithOAuthToken:[responseObject valueForKey:@"access_token"] tokenType:[responseObject valueForKey:@"token_type"] response:responseObject];

        NSDate *expireDate = nil;
        id expiresIn = [responseObject valueForKey:@"expires_in"];
        if (expiresIn != nil && ![expiresIn isEqual:[NSNull null]]) {
            expireDate = [NSDate dateWithTimeIntervalSinceNow:[expiresIn doubleValue]];
        }

        [credential setRefreshToken:refreshToken expiration:expireDate];

        [self setAuthorizationHeaderWithCredential:credential];

        if (success) {
            success(credential);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    [requestOperation start];
}

@end

#pragma mark -

@interface AFOAuthCredential ()
@property (readwrite, nonatomic) NSString *accessToken;
@property (readwrite, nonatomic) NSString *tokenType;
@property (readwrite, nonatomic) NSString *refreshToken;
@property (readwrite, nonatomic) NSDate *expiration;
@property (readwrite, nonatomic) NSDictionary *authorizationResponse;

@end

@implementation AFOAuthCredential
@synthesize accessToken = _accessToken;
@synthesize tokenType = _tokenType;
@synthesize refreshToken = _refreshToken;
@synthesize expiration = _expiration;
@synthesize authorizationResponse = _authorizationResponse;
@dynamic expired;

#pragma mark -

+ (instancetype)credentialWithOAuthToken:(NSString *)token
                               tokenType:(NSString *)type
								response:(NSDictionary*)response
{
    return [[self alloc] initWithOAuthToken:token tokenType:type response:response];
}

- (id)initWithOAuthToken:(NSString *)token
               tokenType:(NSString *)type
				response:(NSDictionary*)response
{
    self = [super init];
    if (!self) {
        return nil;
    }

    self.accessToken = token;
    self.tokenType = type;
    self.authorizationResponse = response;

    return self;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@ accessToken:\"%@\" tokenType:\"%@\" refreshToken:\"%@\" expiration:\"%@\">", [self class], self.accessToken, self.tokenType, self.refreshToken, self.expiration];
}

- (void)setRefreshToken:(NSString *)refreshToken
             expiration:(NSDate *)expiration
{
    if (!refreshToken || !expiration) {
        return;
    }

    self.refreshToken = refreshToken;
    self.expiration = expiration;
}

- (BOOL)isExpired {
    return [self.expiration compare:[NSDate date]] == NSOrderedAscending;
}

#pragma mark Keychain

#ifdef _SECURITY_SECITEM_H_

+ (BOOL)storeCredential:(AFOAuthCredential *)credential
         withIdentifier:(NSString *)identifier
{
    NSMutableDictionary *queryDictionary = AFKeychainQueryDictionaryWithIdentifier(identifier);

    if (!credential) {
        return [self deleteCredentialWithIdentifier:identifier];
    }

    NSMutableDictionary *updateDictionary = [NSMutableDictionary dictionary];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:credential];
    [updateDictionary setObject:data forKey:(__bridge id)kSecValueData];

    OSStatus status;
    BOOL exists = ([self retrieveCredentialWithIdentifier:identifier] != nil);

    if (exists) {
        status = SecItemUpdate((__bridge CFDictionaryRef)queryDictionary, (__bridge CFDictionaryRef)updateDictionary);
    } else {
        [queryDictionary addEntriesFromDictionary:updateDictionary];
        status = SecItemAdd((__bridge CFDictionaryRef)queryDictionary, NULL);
    }

    if (status != errSecSuccess) {
        NSLog(@"Unable to %@ credential with identifier \"%@\" (Error %li)", exists ? @"update" : @"add", identifier, (long int)status);
    }

    return (status == errSecSuccess);
}

+ (BOOL)deleteCredentialWithIdentifier:(NSString *)identifier {
    NSMutableDictionary *queryDictionary = AFKeychainQueryDictionaryWithIdentifier(identifier);

    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)queryDictionary);

    if (status != errSecSuccess) {
        NSLog(@"Unable to delete credential with identifier \"%@\" (Error %li)", identifier, (long int)status);
    }

    return (status == errSecSuccess);
}

+ (AFOAuthCredential *)retrieveCredentialWithIdentifier:(NSString *)identifier {
    NSMutableDictionary *queryDictionary = AFKeychainQueryDictionaryWithIdentifier(identifier);
    [queryDictionary setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [queryDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];

    CFDataRef result = nil;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)queryDictionary, (CFTypeRef *)&result);

    if (status != errSecSuccess) {
        NSLog(@"Unable to fetch credential with identifier \"%@\" (Error %li)", identifier, (long int)status);
        return nil;
    }

    NSData *data = (__bridge_transfer NSData *)result;
    AFOAuthCredential *credential = [NSKeyedUnarchiver unarchiveObjectWithData:data];

    return credential;
}

#endif

#pragma mark - NSCoding

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];
    self.accessToken = [decoder decodeObjectForKey:@"accessToken"];
    self.tokenType = [decoder decodeObjectForKey:@"tokenType"];
    self.refreshToken = [decoder decodeObjectForKey:@"refreshToken"];
    self.expiration = [decoder decodeObjectForKey:@"expiration"];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.accessToken forKey:@"accessToken"];
    [encoder encodeObject:self.tokenType forKey:@"tokenType"];
    [encoder encodeObject:self.refreshToken forKey:@"refreshToken"];
    [encoder encodeObject:self.expiration forKey:@"expiration"];
}

@end


text:
// Copyright 2017 Per Grön. All Rights Reserved.
//
// 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.

#pragma once

#include <functional>
#include <string>

#include <util/file_descriptor.h>

#include "kdebug.h"
#include "tracing_server.h"

namespace shk {

/**
 * Helper class for reading and writing a debug capture log. A debug capture log
 * has all the information that a shk-trace server process receives from Kdebug,
 * along with all the tracing requests that it received at the time. With such
 * a log it is possible to replay whatever a shk-trace server process has done,
 * without having to use Kdebug and trigger the same system behavior again. This
 * can be useful to debug bugs that only occur occasionally and to make it
 * possible to attach shk-trace to a normal debugger.
 *
 * Because this is intended for debugging, it does not have careful error
 * handling, it just aborts if things go wrong when writing.
 */
class DebugCaptureLog {
 public:
  DebugCaptureLog(FileDescriptor &&fd);

  void writeTraceRequest(const TracingServer::TraceRequest &trace_request);
  void writeKdBufs(const kd_buf *begin, const kd_buf *end);

  static bool parse(
      const FileDescriptor &fd,
      const std::function<
          void (std::unique_ptr<TracingServer::TraceRequest> &&)> &
              trace_request_callback,
      const std::function<void (
          const kd_buf *begin, const kd_buf *end)> &kd_bufs_callback,
      std::string *err);
 private:
  void writeToFile(void *buf, size_t size);

  FileDescriptor _fd;
};

}  // namespace shk

redpajama_set_name: RedPajamaGithub


text:
#ifndef OVERKIZ_THREAD_H_
#define OVERKIZ_THREAD_H_

#include <pthread.h>
#include <vector>
#include <stdio.h>

#include <kizbox/framework/core/Shared.h>
#include <kizbox/framework/core/Exception.h>
#include <kizbox/framework/core/Errno.h>

namespace Overkiz
{

  /**
   * Class used to manage a thread.
   */
  class Thread
  {
  public:

    /**
     * Thread timeout definition.
     */
    typedef struct timespec Timeout;

    /**
     * Define ClockId.
     */
    typedef clockid_t ClockId;

    class Configuration;

    /**
     * Class used to define a thread scheduler.
     */
    class Scheduler
    {
    public:
      /**
       * Define the different scheduling policies
       */
      typedef enum
      {
        POLICY_OTHER = SCHED_OTHER, //!< POLICY_OTHER
        POLICY_FIFO = SCHED_FIFO, //!< POLICY_FIFO
        POLICY_RR = SCHED_RR
                    //!< POLICY_RR
      } Policy;

      /**
       * Define the scheduling parameters.
       * Depends on the choosen policy.
       *
       * @see pthread
       */
      typedef struct sched_param Parameters;

      /**
       * Constructor.
       * The scheduler inherits his properties from his parent
       * (inheritance = true).
       *
       * @return
       */
      Scheduler();

      /**
       * Constructor whith scecified policies and associated parameters.
       * The scheduler does not inherit his properties from his parent
       * (inheritance = false).
       *
       * @param policy : the policy to use
       * @param parameters : the parameters associated to the policy.
       * @return
       */
      Scheduler(Policy policy, Parameters& parameters);

      /**
       * Destructor.
       *
       * @return
       */
      virtual ~Scheduler();

      /**
       * Get policy
       *
       * @return the policy
       */
      Policy getPolicy();

      /**
       * Set policy
       *
       * @param policy : the new policy
       */
      void setPolicy(Policy policy);

      /**
       * Get the policy parameters.
       *
       * @return the policy parameters
       */
      Parameters& getParameters();

      /**
       * Set the policy parameters.
       *
       * @param params : the new params.
       */
      void setParameters(Parameters& params);

      /**
       * Get inheritance property.
       *
       * @return true if the scheduler inherits from his parent,
       * else return false.
       */
      bool isInheritedFromParent();

      /**
       * Set inheritance property.
       *
       * @param inherits : true if you want the scheduler to inherit from his parent,
       * else false
       */
      void inheritsFromParent(bool inherits);

    private:
      Policy policy;
      Parameters parameters;
      bool inheritance;

      friend class Configuration;

    };

    /**
     * Define the scope for any thread elem (thread, lock, read/write lock, condition).
     *
     * SCOPE_SYSTEM means the thread elem is shared upon all thread inside any processes.
     * SCOPE_PROCESS means the thread elem is shared upon all thread inside this process.
     */
    typedef enum
    {
      SCOPE_SYSTEM = PTHREAD_SCOPE_SYSTEM,  //!< SCOPE_SYSTEM
      SCOPE_PROCESS = PTHREAD_SCOPE_PROCESS,  //!< SCOPE_PROCESS
    } Scope;

    /**
     * Used to define a thread stack.
     */
    class Stack
    {
    public:

      /**
       * Constructor of an empty stack.
       *
       * @return
       */
      Stack();

      /**
       * Constructor of a stack from given address and size.
       *
       * @param addr : the start address of the stack
       * @param size : the stack size.
       * @return
       */
      Stack(void *addr, size_t size);

      /**
       * Destructor.
       *
       * @return
       */
      virtual ~Stack();

      /**
       * Get stack size.
       *
       * @return
       */
      size_t getStackSize();

      /**
       * Get the start address of the stack.
       *
       * @return start address of the stack.
       */
      void *getStackAddress();

      /**
       * Set a new stack address and size.
       *
       * @param address : the new address.
       * @param size : the new size.
       */
      void setStack(void *address, size_t size);

      /**
       * Get the size a the guard area.
       *
       * @return
       */
      size_t getGuardSize();

      /**
       * Set a guard area to control thread stack overflow.
       * Cannot be set if address is not NULL
       * (ie thread stack not dynamically allocated).
       *
       * @param size : the size of the guard area
       */
      void setGuardSize(size_t size);

    private:
      size_t size;
      void *address;
      size_t guardSize;

      friend class Configuration;
    };

    /**
     * Class used to specify thread configuration.
     */
    class Configuration
    {
    public:

      /**
       * Constructor.
       *
       * @return
       */
      Configuration();

      /**
       * Destructor.
       *
       * @return
       */
      virtual ~Configuration();

      /**
       * Get the scheduling inheritance attribute.
       *
       * @return SCHEDULING_INHERITANCE_ACTIVATED if thread inherits scheduling properties
       * from his parent, else return SCHEDULING_INHERITANCE_DEACTIVATED
       */
      void getSchedulingProperties(Scheduler& sched);

      /**
       * Set the scheduling inheritance attribute.
       *
       * @param attr : SCHEDULING_INHERITANCE_ACTIVATED if thread inherits scheduling properties
       * from his parent, else return SCHEDULING_INHERITANCE_DEACTIVATED
       */
      void setSchedulingProperties(Scheduler& sched);

      /**
       * Get scope property.
       *
       * @return the scope property
       *
       * @see Scope
       */
      Scope getScopeProperty();

      /**
       * Set scope property.
       *
       * @param scope
       */
      void setScopeProperty(Scope scope);

      /**
       * Get the stack properties.
       *
       * @param stack : used to store the result.
       */
      void getStack(Stack& stack);

      /**
       * Set the stack properties
       *
       * @param stack : the new properties.
       */
      void setStack(Stack& stack);

      /**
       * Test if a thread is joined to parent thread.
       *
       * @return
       */
      bool isJoindedToParent();

      /**
       * Set the join property of the thread.
       *
       * @param join
       */
      void joinToParent(bool join);

      size_t getStackSize();

      size_t setStackSize(const size_t stacksize);

    private:
      pthread_attr_t attributes;

      friend class Thread;
    };

    /**
     * Class template used to define an object which is unique to
     * any thread launched by a process.
     * Replace T by the type of data you want to store.
     * T must implement void cleanup () method.
     * This method is called when a key is destroyed.
     */
    template<class T>
    class Key
    {
    public:
      /**
       * Constructor.
       *
       * @return
       */
      Key()
      {
        pthread_key_create(&key, destroy);
        Shared::Pointer<T> *value = new Shared::Pointer<T>();
        pthread_setspecific(key, value);
      }

      /**
       * Constructor with new key object.
       *
       * @param t : the new key object.
       * @return
       */
      Key(const Shared::Pointer<T>& val)
      {
        pthread_key_create(&key, destroy);
        Shared::Pointer<T> *value = new Shared::Pointer<T> (val);
        pthread_setspecific(key, value);
      }

      /**
       * Destructor
       *
       * @return
       */
      virtual ~Key()
      {
        pthread_key_delete(key);
      }

      Shared::Pointer<T>& operator *()
      {
        Shared::Pointer<T> *val =
          static_cast<Shared::Pointer<T> *>(pthread_getspecific(key));

        if(val == NULL)
        {
          val = new Shared::Pointer<T>();
          pthread_setspecific(key, val);
        }

        return *val;
      }

      const Shared::Pointer<T>& operator *() const
      {
        Shared::Pointer<T> *val =
          static_cast<Shared::Pointer<T> *>(pthread_getspecific(key));

        if(val == NULL)
        {
          val = new Shared::Pointer<T>();
          pthread_setspecific(key, val);
        }

        return *val;
      }

      Shared::Pointer<T> *operator ->()
      {
        Shared::Pointer<T> *val =
          static_cast<Shared::Pointer<T> *>(pthread_getspecific(key));

        if(val == NULL)
        {
          val = new Shared::Pointer<T>();
          pthread_setspecific(key, val);
        }

        return val;
      }

      const Shared::Pointer<T> *operator ->() const
      {
        Shared::Pointer<T> *val =
          static_cast<Shared::Pointer<T> *>(pthread_getspecific(key));

        if(val == NULL)
        {
          val = new Shared::Pointer<T>();
          pthread_setspecific(key, val);
        }

        return val;
      }

      Key& operator = (const Shared::Pointer<T>& val)
      {
        Shared::Pointer<T> *value =
          static_cast<Shared::Pointer<T> *>(pthread_getspecific(key));

        if(value == NULL)
        {
          value = new Shared::Pointer<T> (val);
          pthread_setspecific(key, value);
        }
        else
        {
          *value = val;
        }

        return *this;
      }

    private:
      pthread_key_t key;

      static void destroy(void *ptr)
      {
        Shared::Pointer<T> *val = static_cast<Shared::Pointer<T> *>(ptr);

        if(val)
        {
          delete val;
        }
      }
    };

    class Signal;

    /**
     * Used to manage simple locks.
     */
    class Lock
    {
    public:

      /**
       * Define the type of lock.
       *
       * @see pthread
       */
      typedef enum
      {
        TIMED_TYPE = PTHREAD_MUTEX_TIMED_NP,          //!< TIMED_TYPE
        RECURSIVE_TYPE = PTHREAD_MUTEX_RECURSIVE_NP,  //!< RECURSIVE_TYPE
        ERRORCHECK_TYPE = PTHREAD_MUTEX_ERRORCHECK_NP,  //!< ERRORCHECK_TYPE
        ADAPTIVE_TYPE = PTHREAD_MUTEX_ADAPTIVE_NP,    //!< ADAPTIVE_TYPE
      } Type;

      /**
       * Class used to configure the mutex.
       */
      class Configuration
      {
      public:
        /**
         * Constructor.
         *
         * @return
         */
        Configuration();

        /**
         * Destructor.
         *
         * @return
         */
        virtual ~Configuration();

        /**
         * Type getter.
         *
         * @return
         */
        Type getType();

        /**
         * Type setter.
         *
         * @param type
         */
        void setType(Type type);

        /**
         * Scope getter.
         *
         * @return the scope of the mutex.
         */
        Scope getScope();

        /**
         * Scope setter.
         *
         * @param scope : the new scope of mutex.
         */
        void setScope(Scope scope);

      private:
        pthread_mutexattr_t attributes;

        friend class Lock;
        friend class Signal;
      };

      /**
       * Constructor with default mutex configuration.
       *
       * @return
       */
      Lock();

      /**
       * Constructor with given configuration.
       *
       * @param config
       * @return
       */
      Lock(Configuration& config);

      /**
       * Destructor.
       *
       * @return
       */
      virtual ~Lock();

      /**
       * Method used to acquire this mutex lock.
       *
       */
      void acquire();

      /**
       * Method used to try to acquire this mutex lock.
       *
       * @return true if it succeed else false.
       */
      bool tryToAcquire();

      /**
       * Method used to release this mutex lock.
       *
       */
      void release();
    private:
      pthread_mutex_t lock;
    };

    /**
     * Used to manage read-write locks.
     */
    class ReadWriteLock
    {
    public:

      /**
       * Define the type of read/write lock policy.
       *
       * @see pthread
       */
      typedef enum
      {
        POLICY_PREFER_READER = PTHREAD_RWLOCK_PREFER_READER_NP,
        POLICY_PREFER_WRITER = PTHREAD_RWLOCK_PREFER_WRITER_NP,
        POLICY_PREFER_NONRECURSIVE_WRITER = PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP,
        POLICY_DEFAULT = PTHREAD_RWLOCK_DEFAULT_NP,
      } Policy;

      class Configuration
      {
      public:
        /**
         * Constructor.
         *
         * @return
         */
        Configuration();

        /**
         * Destructor.
         *
         * @return
         */
        virtual ~Configuration();

        /**
         * Scope getter.
         *
         * @return the scope of the mutex.
         */
        Scope getScope();

        /**
         * Scope setter.
         *
         * @param scope : the new scope of mutex.
         */
        void setScope(Scope scope);

        /**
         * Policy getter.
         *
         * @return
         */
        Policy getPolicy();

        /**
         * Policy setter.
         *
         * @param policy
         */
        void setPolicy(Policy policy);

      private:
        pthread_rwlockattr_t attributes;

        friend class ReadWriteLock;
      };

      /**
       * Constructor.
       *
       * @return
       */
      ReadWriteLock();

      /**
       * Constructor with specified config.
       *
       * @param config
       * @return
       */
      ReadWriteLock(Configuration& config);

      /**
       * Destructor.
       *
       * @return
       */
      virtual ~ReadWriteLock();

      /**
       * Method used to acquire a read lock.
       */
      void acquireReadAccess();

      /**
       * Method used to try to acquire a read lock.
       *
       * @return true if it succeed else false.
       */
      bool tryToAcquireReadAccess();

      /**
       * Method used to acquire a write lock.
       */
      void acquireWriteAccess();

      /**
       * Method used to try to acquire a write lock.
       *
       * @return true if it succeed else false.
       */
      bool tryToAcquireWriteAccess();

      /**
       * Method used to release a lock.
       */
      void release();
    private:
      pthread_rwlock_t lock;
    };

    /**
     * Class used to manage signal between threads.
     *
     */
    class Signal
    {
    public:

      class Configuration
      {
      public:
        /**
         * Constructor.
         *
         * @return
         */
        Configuration();

        /**
         * Destructor.
         *
         * @return
         */
        virtual ~Configuration();

        /**
         * Scope getter.
         *
         * @return the scope of the mutex.
         */
        Scope getScope();

        /**
         * Scope setter.
         *
         * @param scope : the new scope of mutex.
         */
        void setScope(Scope scope);

      private:
        pthread_condattr_t attributes;

        friend class Signal;
      };

      /**
       * Constructor.
       *
       * @return
       */
      Signal();

      /**
       * Constructor with specified config.
       *
       * @param config
       * @return
       */
      Signal(Configuration& config);

      /**
       * Constructor with specified lock config.
       *
       * @param lockConfig
       * @return
       */
      Signal(Lock::Configuration& lockConfig);

      /**
       * Constructor with config and lock config both specified.
       *
       * @param config
       * @param lockConfig
       * @return
       */
      Signal(Configuration& config, Lock::Configuration& lockConfig);

      /**
       * Destructor.
       *
       * @return
       */
      virtual ~Signal();

      /**
       * Send this signal in broadcast.
       */
      void broadcast();

      /**
       * Send this signal.
       */
      void send();

      /**
       * Wait for a signal to be emmited.
       */
      void wait();

      /**
       * Wait a signal for a given time.
       *
       * @param timeout : the max time to wait.
       * @return true if signal has been received before the timeout expired
       * else false
       */
      bool wait(Timeout& timeout);

    private:
      pthread_mutex_t lock;
      pthread_cond_t condition;
    };

    class Delegate
    {
    public:
      virtual void release(Thread *thread) = 0;
    private:

    };

    /**
     * Get current thread.
     *
     * @return
     */
    static Shared::Pointer<Thread>& self();

    /**
     * Add a child thread to this thread.
     * If this thread is currently running,
     * the new child is automatically launched.
     *
     * @param child : the new child to add.
     */
    static void addChild(Shared::Pointer<Thread>& child) throw(Overkiz::Errno::Exception);

    /**
     * Remove a child thread from this thread.
     * If the child thread is running,
     * it is stopped before the removal takes place.
     *
     * @param child : the child to remove.
     */
    static void removeChild(Shared::Pointer<Thread>& child);

    /**
     * Function used to cancel all running children.
     */
    static void cancelChildren();

    /**
     * Remove a child from the thread children.
     * The child continue to run but is no longer attached to his parent.
     *
     * @param child : the child to detach.
     */
    static void detach(Shared::Pointer<Thread>& child);

    /**
     * Exit from the running thread.
     *
     * @param ret
     */
    static void exit(long ret);

    /**
     *
     * @param child
     * @return
     */
    static long join(Shared::Pointer<Thread>& child);

    /**
     * Send a signal to this thread.
     * This thread must be one of your direct child.
     *
     * @param sig
     */
    void kill(long sig);

    /**
     * Set a new delegate to handle thread end.
     *
     * @param delegate : the new delegate.
     */
    void setDelegate(Delegate *delegate);

    /**
     * Execute this thread inside the current one.
     * Used to start a process execution.
     *
     * @return
     */
    long start();

    Configuration getConfiguration();

    void setConfiguration(Configuration& newConfig);

  protected:
    /**
     * Run function called by startCallback.
     * Represent the 'int main (void)' function of the thread.
     * Must be implemented by class derived from thread.
     *
     * @return
     */
    virtual int run();

    /**
     *
     * @param child
     */
    virtual void cancel();

    /**
     * Called by the child thread when it has started.
     *
     * @param child
     */
    virtual void started(Thread *child);

    /**
     * Called by the child thread when it has stopped.
     *
     * @param child
     */
    virtual void stopped(Thread *child);

    /**
     * Init method called before run method is called.
     * Any initialization of the thread can takes place here.
     */
    virtual int init();

    /**
     * Cleanup function called when a thread stops
     * (when run function returns or when cancel or exit is called).
     */
    virtual void cleanup();

    /**
     * Function used to check children status and launch the appropriate actions.
     *
     * STATUS_IDLE : the child is launched.
     * STATUS_STARTING : nothing is done.
     * STATUS_RUNNING : nothing is done.
     * STATUS_STOPPING : nothing is done.
     * STATUS_STOPPED : the child is joined, cleanup and released,
     *  the child entry is removed from the children vector.
     *
     */
    void checkChildren() throw(Overkiz::Errno::Exception);

    /**
     * Constructor with default configuration.
     *
     * @return
     */
    Thread();

    /**
     *
     * @param config
     * @return
     */
    Thread(Configuration& config);

    /**
     * Constructor with given delegate.
     *
     * @param delegate
     * @return
     */
    Thread(Delegate *delegate);

    /**
     *
     * @param config
     * @param delegate
     * @return
     */
    Thread(Configuration& config, Delegate *delegate);

    /**
     * Destructor.
     *
     * @return
     */
    virtual ~Thread();

    void getSchedulingProperties(Scheduler& sched);

    void setSchedulingProperties(Scheduler& sched);

    int getSchedulingMaxPriority(Scheduler::Policy policy);

    int getSchedulingMinPriority(Scheduler::Policy policy);

  private:

    /**
     * Define the thread status.
     */
    typedef enum
    {
      STATUS_IDLE = 0,    //!< STATUS_IDLE
      STATUS_STARTING = 1,    //!< STATUS_STARTING
      STATUS_RUNNING = 2, //!< STATUS_RUNNING
      STATUS_STOPPING = 3, //!< STATUS_STOPPING
      STATUS_STOPPED = 4, //!< STATUS_STOPPED
    } Status;

    typedef std::vector<Shared::Pointer<Thread> > ThreadVector;
    typedef ThreadVector::iterator ThreadIterator;

    static Key<Thread> key;

    pthread_t id;
    Configuration config;
    Status status;

    ThreadVector children;
    Lock lock;

    Shared::Pointer<Thread> parent;

    Delegate *delegate;

    static void cleanupCallback(void *arg);
    static void stoppedCallback(void *arg);
    static void *startCallback(void *arg);

    template<typename T> friend class Shared::Pointer;

  };

}

#endif /* OVERKIZ_THREAD_H_ */


text:
package org.kuali.kra.s2s.generator.impl;

import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument;
import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument.PHS398ResearchPlan;
import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument.PHS398ResearchPlan.ApplicationType;
import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument.PHS398ResearchPlan.ApplicationType.TypeOfApplication;
import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument.PHS398ResearchPlan.ResearchPlanAttachments;
import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument.PHS398ResearchPlan.ResearchPlanAttachments.*;
import gov.grants.apply.forms.phs398ResearchPlanV10.PHS398ResearchPlanDocument.PHS398ResearchPlan.ResearchPlanAttachments.HumanSubjectSection.*;
import gov.grants.apply.system.attachmentsV10.AttachedFileDataType;
import gov.grants.apply.system.attachmentsV10.AttachmentGroupMin0Max100DataType;
import org.apache.xmlbeans.XmlObject;
import org.kuali.kra.proposaldevelopment.bo.Narrative;
import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument;
import org.kuali.kra.s2s.util.S2SConstants;

import java.util.ArrayList;
import java.util.List;

/**
 * Class for generating the XML object for grants.gov PHS398ResearchPlanV1_0. Form is generated using XMLBean classes and is based
 * on PHS398ResearchPlanV1_0 schema.
 *
 * @author Kuali Research Administration Team (kualidev@oncourse.iu.edu)
 */
public class PHS398ResearchPlanV1_0Generator extends PHS398ResearchPlanBaseGenerator {

    /**
     *
     * This method gives the list of attachments for PHS398ResearchPlan form
     *
     * @return phsResearchPlanDocument {@link XmlObject} of type PHS398ResearchPlanDocument.
     */
    private PHS398ResearchPlanDocument getPHS398ResearchPlan() {
        PHS398ResearchPlanDocument phsResearchPlanDocument = PHS398ResearchPlanDocument.Factory.newInstance();
        PHS398ResearchPlan phsResearchPlan = PHS398ResearchPlan.Factory.newInstance();

        phsResearchPlan.setFormVersion(S2SConstants.FORMVERSION_1_0);
        phsResearchPlan.setApplicationType(getApplicationType());
        ResearchPlanAttachments researchPlanAttachments = ResearchPlanAttachments.Factory.newInstance();
        HumanSubjectSection humanSubjectSection = HumanSubjectSection.Factory.newInstance();
        AttachedFileDataType attachedFileDataType = null;
        for (Narrative narrative : pdDoc.getDevelopmentProposal().getNarratives()) {
            if (narrative.getNarrativeTypeCode() != null) {
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == INTRODUCTION_TO_APPLICATION) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    IntroductionToApplication introductionToApplication = IntroductionToApplication.Factory.newInstance();
                    introductionToApplication.setAttFile(attachedFileDataType);
                    researchPlanAttachments.setIntroductionToApplication(introductionToApplication);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == SPECIFIC_AIMS) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    SpecificAims specificAims = SpecificAims.Factory.newInstance();
                    specificAims.setAttFile(attachedFileDataType);
                    researchPlanAttachments.setSpecificAims(specificAims);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == BACKGROUND_SIGNIFICANCE) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    BackgroundSignificance backgroundSignificance = BackgroundSignificance.Factory.newInstance();
                    backgroundSignificance.setAttFile(attachedFileDataType);
                    researchPlanAttachments.setBackgroundSignificance(backgroundSignificance);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == PROGRESS_REPORT) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    ProgressReport progressReport = ProgressReport.Factory.newInstance();
                    progressReport.setAttFile(attachedFileDataType);
                    researchPlanAttachments.setProgressReport(progressReport);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == RESEARCH_DESIGN_METHODS) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    ResearchDesignMethods researchDesignMethods = ResearchDesignMethods.Factory.newInstance();
                    researchDesignMethods.setAttFile(attachedFileDataType);
                    researchPlanAttachments.setResearchDesignMethods(researchDesignMethods);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == PROTECTION_OF_HUMAN_SUBJECTS) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    ProtectionOfHumanSubjects protectionOfHumanSubjects = ProtectionOfHumanSubjects.Factory.newInstance();
                    protectionOfHumanSubjects.setAttFile(attachedFileDataType);
                    humanSubjectSection.setProtectionOfHumanSubjects(protectionOfHumanSubjects);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == INCLUSION_OF_WOMEN_AND_MINORITIES) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    InclusionOfWomenAndMinorities inclusionOfWomenAndMinorities = InclusionOfWomenAndMinorities.Factory
                            .newInstance();
                    inclusionOfWomenAndMinorities.setAttFile(attachedFileDataType);
                    humanSubjectSection.setInclusionOfWomenAndMinorities(inclusionOfWomenAndMinorities);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == TARGETED_PLANNED_ENROLLMENT_TABLE) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    TargetedPlannedEnrollmentTable targetedPlannedEnrollmentTable = TargetedPlannedEnrollmentTable.Factory
                            .newInstance();
                    targetedPlannedEnrollmentTable.setAttFile(attachedFileDataType);
                    humanSubjectSection.setTargetedPlannedEnrollmentTable(targetedPlannedEnrollmentTable);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == INCLUSION_OF_CHILDREN) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    InclusionOfChildren inclusionOfChildren = InclusionOfChildren.Factory.newInstance();
                    inclusionOfChildren.setAttFile(attachedFileDataType);
                    humanSubjectSection.setInclusionOfChildren(inclusionOfChildren);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == DATA_AND_SAFETY_MONITORING_PLAN) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    DataAndSafetyMonitoringPlan dataAndSafetyMonitoringPlan = DataAndSafetyMonitoringPlan.Factory.newInstance();
                    dataAndSafetyMonitoringPlan.setAttFile(attachedFileDataType);
                    humanSubjectSection.setDataAndSafetyMonitoringPlan(dataAndSafetyMonitoringPlan);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == VERTEBRATE_ANIMALS) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    VertebrateAnimals vertebrateAnimals = VertebrateAnimals.Factory.newInstance();
                    vertebrateAnimals.setAttFile(attachedFileDataType);
                    humanSubjectSection.setVertebrateAnimals(vertebrateAnimals);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == CONSORTIUM_CONTRACTUAL_ARRANGEMENTS) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    ConsortiumContractualArrangements consortiumContractualArrangements = ConsortiumContractualArrangements.Factory
                            .newInstance();
                    consortiumContractualArrangements.setAttFile(attachedFileDataType);
                    humanSubjectSection.setConsortiumContractualArrangements(consortiumContractualArrangements);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == LETTERS_OF_SUPPORT) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    LettersOfSupport lettersOfSupport = LettersOfSupport.Factory.newInstance();
                    lettersOfSupport.setAttFile(attachedFileDataType);
                    humanSubjectSection.setLettersOfSupport(lettersOfSupport);
                }
                if (Integer.parseInt(narrative.getNarrativeTypeCode()) == RESOURCE_SHARING_PLANS) {
                    attachedFileDataType = getAttachedFileType(narrative);
                    if(attachedFileDataType == null){
                        continue;
                    }
                    ResourceSharingPlans resourceSharingPlans = ResourceSharingPlans.Factory.newInstance();
                    resourceSharingPlans.setAttFile(attachedFileDataType);
                    humanSubjectSection.setResourceSharingPlans(resourceSharingPlans);
                }
            }
        }
        researchPlanAttachments.setHumanSubjectSection(humanSubjectSection);

        AttachmentGroupMin0Max100DataType attachmentGroupMin0Max100DataType = AttachmentGroupMin0Max100DataType.Factory
                .newInstance();
        attachmentGroupMin0Max100DataType.setAttachedFileArray(getAttachedFileDataTypes());
        researchPlanAttachments.setAppendix(attachmentGroupMin0Max100DataType);
        phsResearchPlan.setResearchPlanAttachments(researchPlanAttachments);
        phsResearchPlanDocument.setPHS398ResearchPlan(phsResearchPlan);
        return phsResearchPlanDocument;
    }

    /**
     *
     * This method is used to get ApplicationType from ProposalDevelopmentDocument
     *
     * @return ApplicationType corresponding to the proposal type code.
     */
    private ApplicationType getApplicationType() {
        ApplicationType applicationType = ApplicationType.Factory.newInstance();
        if (pdDoc.getDevelopmentProposal().getProposalTypeCode() != null && Integer.parseInt(pdDoc.getDevelopmentProposal().getProposalTypeCode()) < PROPOSAL_TYPE_CODE_6) {
            // Check < 6 to ensure that if proposalType='TASK ORDER", it must not set. THis is because enum ApplicationType has no
            // entry for TASK ORDER
            TypeOfApplication.Enum typeOfApplication = TypeOfApplication.Enum.forInt(Integer.parseInt(pdDoc.getDevelopmentProposal().getProposalTypeCode()));
            applicationType.setTypeOfApplication(typeOfApplication);
        }
        return applicationType;
    }

    /**
     *
     * This method is used to get List of appendix attachments from NarrativeAttachmentList
     *
     * @return AttachedFileDataType[]  array of attachments for the corresponding narrative type code APPENDIX.
     */
    private AttachedFileDataType[] getAttachedFileDataTypes() {
        List<AttachedFileDataType> attachedFileDataTypeList = new ArrayList<AttachedFileDataType>();
        AttachedFileDataType attachedFileDataType = null;
        for (Narrative narrative : pdDoc.getDevelopmentProposal().getNarratives()) {
            if (narrative.getNarrativeTypeCode() != null && Integer.parseInt(narrative.getNarrativeTypeCode()) == APPENDIX) {
            	attachedFileDataType = getAttachedFileType(narrative);
            	if(attachedFileDataType != null){
            		attachedFileDataTypeList.add(attachedFileDataType);
            	}
            }
        }
        return attachedFileDataTypeList.toArray(new AttachedFileDataType[0]);
    }

    /**
     * This method creates {@link XmlObject} of type {@link PHS398ResearchPlanDocument} by populating data from the given
     * {@link ProposalDevelopmentDocument}
     *
     * @param proposalDevelopmentDocument for which the {@link XmlObject} needs to be created
     * @return {@link XmlObject} which is generated using the given {@link ProposalDevelopmentDocument}
     * @see org.kuali.kra.s2s.generator.S2SFormGenerator#getFormObject(ProposalDevelopmentDocument)
     */
    public XmlObject getFormObject(ProposalDevelopmentDocument proposalDevelopmentDocument) {
        this.pdDoc = proposalDevelopmentDocument;
        return getPHS398ResearchPlan();
    }

    /**
     * This method typecasts the given {@link XmlObject} to the required generator type and returns back the document of that
     * generator type.
     *
     * @param xmlObject which needs to be converted to the document type of the required generator
     * @return {@link XmlObject} document of the required generator type
     * @see org.kuali.kra.s2s.generator.S2SFormGenerator#getFormObject(XmlObject)
     */
    public XmlObject getFormObject(XmlObject xmlObject) {

        PHS398ResearchPlan phsResearchPlan = (PHS398ResearchPlan) xmlObject;
        PHS398ResearchPlanDocument phsResearchPlanDocument = PHS398ResearchPlanDocument.Factory.newInstance();
        phsResearchPlanDocument.setPHS398ResearchPlan(phsResearchPlan);
        return phsResearchPlanDocument;
    }
}


text:
 #ifndef DT3_BASECLASS
#define DT3_BASECLASS
//==============================================================================
///
///	File: BaseClass.hpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================

#include "DT3Core/Types/Base/BaseInclude.hpp"
#include <memory>
#include <atomic>

//==============================================================================
//==============================================================================

namespace DT3 {

//==============================================================================
/// Forward declarations
//==============================================================================

class Archive;

//==============================================================================
/// Class
//==============================================================================

class BaseClass: public std::enable_shared_from_this<BaseClass> {
    public:
        DEFINE_TYPE_BASE(BaseClass)

                                    BaseClass                       (void);
                                    BaseClass                       (const BaseClass &rhs);
        BaseClass &					operator =                      (const BaseClass &rhs);
        virtual                     ~BaseClass                      (void);

        virtual void                archive                         (const std::shared_ptr<Archive> &archive);
        virtual void                archive_done                    (const std::shared_ptr<Archive> &archive)  {};

	public:

		//
		// Exception safe initialization
		//

		/// Called to initialize the object
		virtual void				initialize                      (void);

		/// Called to uninitialize the object
		virtual void				uninitialize                    (void);

		//
		// Archiving
		//

		/// Returns the unique ID for this object. The object ID is guaranteed to be unique per
        /// execution of the applcation.
		/// \return unique ID
        inline DTuint				unique_id                       (void) const			{   return _unique_id;					}

		/// Forces the object to get a new unique ID
		void						new_unique_id                   (void);

		/// Sets whether the object will be streamed or not
		/// \param streamable object is streamable
		void						set_streamable                  (DTboolean streamable)	{	_streamable = streamable;			}

		/// Returns whether the object will be streamed or not
		/// \return streamable
		DTboolean					streamable                      (void) const			{	return _streamable;					}

    private:
        static std::atomic<DTuint>  _unique_id_counter;
        DTuint						_unique_id;
		DTboolean					_streamable;
};

//==============================================================================
//==============================================================================

} // DT3

#endif


text:
CREATE TABLE KUG
(
    ID        BIGSERIAL    NOT NULL,
    CONTINENT VARCHAR(500) NOT NULL,
    NAME      VARCHAR(500) NOT NULL,
    COUNTRY   VARCHAR(500) NOT NULL,
    URL       VARCHAR(500) NOT NULL,
    LATITUDE  DOUBLE PRECISION NULL,
    LONGITUDE DOUBLE PRECISION NULL,
    CREATED   DATE         NOT NULL,
    PRIMARY KEY (ID)
);

CREATE TABLE KOTLINER_KUG
(
    KOTLINER_ID BIGINT NOT NULL,
    KUG_ID      BIGINT NOT NULL,
    JOIN_DATE   DATE   NOT NULL,
    CONSTRAINT unique_kotliner_kug UNIQUE (KOTLINER_ID)
);

ALTER TABLE KOTLINER_KUG
    ADD FOREIGN KEY (KOTLINER_ID) REFERENCES KOTLINER (ID);

ALTER TABLE KOTLINER_KUG
    ADD FOREIGN KEY (KUG_ID) REFERENCES KUG (ID);


text:
import argparse
import textwrap

from starthinker.util.configuration import Configuration
from starthinker.task.sheets.run import sheets

def recipe_sheets_to_bigquery(config, auth_read, auth_write, sheets_url, sheets_tab, sheets_range, dataset, table, sheets_header):
  """Import data from a sheet and move it to a BigQuery table.

     Args:
       auth_read (authentication) - Credentials used for reading data.
       auth_write (authentication) - Credentials used for writing data.
       sheets_url (string) - NA
       sheets_tab (string) - NA
       sheets_range (string) - NA
       dataset (string) - NA
       table (string) - NA
       sheets_header (boolean) - NA
  """

  sheets(config, {
    'auth':auth_read,
    'sheet':sheets_url,
    'tab':sheets_tab,
    'range':sheets_range,
    'header':sheets_header,
    'out':{
      'auth':auth_write,
      'bigquery':{
        'dataset':dataset,
        'table':table
      }
    }
  })

if __name__ == "__main__":
  parser = argparse.ArgumentParser(
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=textwrap.dedent("""
      Import data from a sheet and move it to a BigQuery table.

      1. For the sheet, provide the full edit URL.
      2. If the tab does not exist it will be created.
      3. Empty cells in the range will be NULL.
      4. Check Sheets header if first row is a header
  """))

  parser.add_argument("-project", help="Cloud ID of Google Cloud Project.", default=None)
  parser.add_argument("-key", help="API Key of Google Cloud Project.", default=None)
  parser.add_argument("-client", help="Path to CLIENT credentials json file.", default=None)
  parser.add_argument("-user", help="Path to USER credentials json file.", default=None)
  parser.add_argument("-service", help="Path to SERVICE credentials json file.", default=None)
  parser.add_argument("-verbose", help="Print all the steps as they happen.", action="store_true")

  parser.add_argument("-auth_read", help="Credentials used for reading data.", default='user')
  parser.add_argument("-auth_write", help="Credentials used for writing data.", default='service')
  parser.add_argument("-sheets_url", help="", default='')
  parser.add_argument("-sheets_tab", help="", default='')
  parser.add_argument("-sheets_range", help="", default='')
  parser.add_argument("-dataset", help="", default='')
  parser.add_argument("-table", help="", default='')
  parser.add_argument("-sheets_header", help="", default=True)

  args = parser.parse_args()

  config = Configuration(
    project=args.project,
    user=args.user,
    service=args.service,
    client=args.client,
    key=args.key,
    verbose=args.verbose
  )

  recipe_sheets_to_bigquery(config, args.auth_read, args.auth_write, args.sheets_url, args.sheets_tab, args.sheets_range, args.dataset, args.table, args.sheets_header)


text:
package com.wlitsoft.javademo.mybatisquickstart.mapper;

/**
 * Created by liliang on 2017/6/20.
 */
public interface BaseMapper {

}


text:
module Hutamaul

	class Tag

		attr_accessor :text
    attr_accessor :parent

	  def initialize text
			@text = text
		end

		def type
	    if @text =~ /^\<\//
				return :end_tag
			elsif @text =~ /\/\>$/
				return :lone_tag
			elsif @text =~ /^\</
				return :begin_tag
			else
				return :text
			end
		end

		def char_count
			type == :text ? @text.length : 0
		end

		##
		#
		# Take the chars from the current tag
		#
		# We pass the options to the given block which the caller can
		# use to specify specific options for the split.
		#
		# If no action is taken we default to a simple split at word.
		#
		def take_chars chars, ellipses = '', &options_block

			if split_needed(chars)
				split = Split.new(self.main_tag, self, ellipses)
			  split.take_chars(chars)

				options = Options.new split
				if !options_block.nil?
					options_block.call(options)
				end

				if !options.yielded
					# Default is split to previous word
					split.before_word
				end

				return split.split_line
			else
				return Tag.new @text
			end
		end

		##
		#
		# Returns the closing tag for this tag.
		#
		def close_tag
			tag_name = /\<(\w+).*>/.match @text

			tag_name.length > 1 ? "</" + tag_name[1] + ">" : ""
		end

		##
		#
		# Searches up our parents for the main tag that contains this tag.
		#
		def main_tag
			if self.parent.nil?
				# If we have no parent, we are probably just unit testing...
				Tag.new("<html>")
			else
				self.parent.main_tag || Tag.new("<html>")
			end
		end

		def to_html
			@text
		end

	  def to_s
			@text
		end

		def to_indented_s level
	    ('-' * level) + @text + "\n"
		end

	private
		def split_needed chars
			type == :text and @text.length > chars
		end
	end
end


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using BotSuite.ImageLibrary;

namespace BotSuite.Recognition.Character
{
    /// <summary>
    /// receptors for optical character recognition
    /// </summary>
    [Serializable]
    public class MagicMatchSticks
    {
        #region protected properties
        /// <summary>
        /// intern instance of PRNG
        /// </summary>
        protected Random rand = new Random();
        /// <summary>
        /// intern list of receptors
        /// </summary>
        protected List<MagicMatchStick> MagicStickList;
        #endregion

        #region public access to properties
        /// <summary>
        /// handle the list of receptors
        /// </summary>
        /// <param name="index">index of receptor</param>
        /// <returns>receptor from list</returns>
        public MagicMatchStick this[int index]
        {
            get { return MagicStickList[index]; }
        }
        /// <summary>
        /// get the number of magic match sticks
        /// </summary>
        /// <returns>num of magic sticks</returns>
        public int Num()
        {
            return MagicStickList.Count;
        }

        /// <summary>
        /// add a magic stick to list
        /// </summary>
        /// <param name="Stick">magic stick</param>
        /// <returns></returns>
        public void Add(MagicMatchStick Stick)
        {
            MagicStickList.Add(Stick);
        }
        #endregion

        #region construct and initalise
        /// <summary>
        /// Create a Container of Magic match Sticks
        /// </summary>
        /// <returns></returns>
        public MagicMatchSticks()
        {
            MagicStickList = new List<MagicMatchStick> { };
        }
        /// <summary>
        /// generate some magic sticks in [0,1]^2
        /// </summary>
        /// <param name="count">number of magic sticks</param>
        /// <returns></returns>
        public void Generate(int count)
        {
            for (int i = 0; i < count; i++)
            {
                int xa = rand.Next(100);
                int ya = rand.Next(100);
                int xb = rand.Next(100);
                int yb = rand.Next(100);

                int dx = xa - xb;
                int dy = ya - yb;
                int length = (int)Math.Sqrt(dx * dx + dy * dy);

                // if their length is to short, then take another
                if ((length < 9) || (length > 54))
                {
                    i--;
                    continue;
                }
                MagicStickList.Add(new MagicMatchStick(xa, ya, xb, yb));
            }
        }
        #endregion

        #region create pattern for learning
        /// <summary>
        /// Get the pattern of the magics match sticks
        /// </summary>
        /// <param name="Image">image of character</param>
        /// <returns>pattern</returns>
        public float[] GetMagicMatchSticksState(ImageData Image)
        {
            int Width = Image.Width;        // width of image
            int Height = Image.Height;      // height of image
            int n = Num();                  // num of magicsticks
            float[] Pattern = new float[n];   // state

            int lastx = -1, lasty = -1;
            int tmpx = -1, tmpy = -1;

            for (int i = 0; i < n; i++)
            {
                Pattern[i] = 0.0f;
            }

            for (int y = 0; y < Height; y++)
            {
                for (int x = 0; x < Width; x++)
                {
                    // is the pixel black?
                    if (Image.GetPixel(x, y).R == 0)
                    {
                        tmpx = Convert.ToInt16(x * 100 / Width);
                        tmpy = Convert.ToInt16(y * 100 / Height);

                        if ((tmpx != lastx) || (tmpy != lasty))
                        {
                            lastx = tmpx;
                            lasty = tmpy;
                            for (int i = 0; i < n; i++)
                            {
                                // skip already activated receptors
                                if (Pattern[i] == 1.0f)
                                    continue;

                                if (MagicStickList[i].GetMagicMatchStickState(tmpx, tmpy))
                                    Pattern[i] = 1.0f;
                            }
                        }

                    }
                }
            }

            return Pattern;
        }
        #endregion

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<Configuration status="warn" monitorInterval="10">
    <Properties>
        <Property name="bookkeeper.cli.log.dir">.</Property>
        <Property name="bookkeeper.cli.log.file">bookkeeper-server.log</Property>
        <Property name="bookkeeper.cli.log.root.level">INFO</Property>
        <Property name="bookkeeper.cli.log.root.appender">CONSOLE</Property>
    </Properties>
    <Appenders>
        <Console name="CONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{ABSOLUTE} %-5p %m%n"/>
        </Console>
        <Console name="VERBOSECONSOLE" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n"/>
        </Console>
        <RollingFile name="ROLLINGFILE" fileName="${sys:bookkeeper.cli.log.dir}/${sys:bookkeeper.cli.log.file}" filePattern="${sys:bookkeeper.cli.log.dir}/${sys:bookkeeper.cli.log.file}%d{.yyyy-MM-dd}">
            <PatternLayout pattern="%d{ISO8601} - %-5p - [%t:%C{1}@%L] - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true"/>
            </Policies>
            <DefaultRolloverStrategy max="100"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="${sys:bookkeeper.cli.log.root.level}">
            <AppenderRef ref="${sys:bookkeeper.cli.log.root.appender}"/>
        </Root>
        <Logger name="org.apache.zookeeper" level="ERROR"/>
        <Logger name="verbose" level="INFO">
            <AppenderRef ref="VERBOSECONSOLE"/>
        </Logger>
    </Loggers>
</Configuration>


text:
module RedisRepeater

  class Repeater

    attr_reader :servers, :repeats, :logger

    def initialize(configuration, logger = nil)
      raise ConfigurationError.new 'Configuration is empty' unless configuration
      @servers = {}
      @repeats = []
      # Get the logger
      @logger = logger
      @logger ||= Logger.new(configuration['log']) if configuration['log']
      @logger ||= Logger.new(STDOUT)
      # Load the configuration and start the server
      load_hash_configuration configuration
    end

    def run_forever
      raise ConfigurationError.new('No repeat jobs specified in configuration') if @repeats.empty?
      # start the scheduler and run it forever
      EventMachine::run do
        @repeats.each do |job|
          EventMachine::add_periodic_timer(job.timeout) { job.perform }
        end
        @logger.info "Repeating #{@repeats.count} #{@repeats.count == 1 ? 'queue' : 'queues'} forever!"
      end
    end

    private

    def load_hash_configuration(hash)
      hash['servers'] && hash['servers'].each do |name, value|
        options = {}
        value.each { |k, v| options[k.to_sym] = v }
        @servers[name] = Redis.new(options)
      end
      hash['repeats'] && hash['repeats'].each do |repeat|
        options = {}
        options[:source] = find_server_by_name repeat['source']
        # Handle 'magic' queues
        if repeat['queue'] == 'resque:queues' || repeat['queue'] == 'resque:queue:*'
          options[:source].smembers('resque:queues').each do |queue|
            repeat = repeat.dup
            repeat['queue'] = "resque:queue:#{queue}"
            hash['repeats'] << repeat
          end
          next
        end
        options[:destinations] = repeat['destinations'].map { |d| { :server => find_server_by_name(d['server']), :queue => d['queue'] || repeat['queue'] } }
        options[:queue] = repeat['queue']
        options[:timeout] = repeat['timeout'] || 0
        options[:maintain_count] = !!repeat['maintain_count'] # default false
        # Remove duplicates and add this
        @repeats.delete_if { |r| r.source == options[:source] && r.queue == options[:queue] }
        @repeats << TransferSchedulerJob.new(self, options)
      end
    end

    def find_server_by_name(name)
      server = @servers[name]
      raise ConfigurationError.new("No such server found: #{name}") if server.nil?
      server
    end

  end

end


text:
from oslo_config import cfg

from neutron._i18n import _

security_group_opts = [
    cfg.StrOpt(
        'firewall_driver',
        help=_('Driver for security groups firewall in the L2 agent')),
    cfg.BoolOpt(
        'enable_security_group',
        default=True,
        help=_(
            'Controls whether the neutron security group API is enabled '
            'in the server. It should be false when using no security '
            'groups or using the nova security group API.')),
    cfg.BoolOpt(
        'enable_ipset',
        default=True,
        help=_('Use ipset to speed-up the iptables based security groups. '
               'Enabling ipset support requires that ipset is installed on L2 '
               'agent node.')),
    cfg.ListOpt(
        'permitted_ethertypes',
        default=[],
        help=_('Comma-separated list of ethertypes to be permitted, in '
               'hexadecimal (starting with "0x"). For example, "0x4008" '
               'to permit InfiniBand.'))
]

def register_securitygroups_opts(cfg=cfg.CONF):
    cfg.register_opts(security_group_opts, 'SECURITYGROUP')


text:
* [什么是视图实体?](#什么是视图实体)
* [视图实体列](#视图实体列)
* [完整示例](#完整示例)

## 什么是视图实体?

视图实体是一个映射到数据库视图的类。
你可以通过定义一个新类来创建一个视图实体,并用`@ViewEntity()`来标记:

`@ViewEntity()` 接收以下参数:

* `name` - 视图名称。 如果未指定,则从实体类名生成视图名称。
* `database` - 所选DB服务器中的数据库名称。
* `schema` - 架构名称。
* `expression` - 视图定义。 **必需参数**。

`expression`可以是带有正确转义的列和表的字符串,取决于所使用的数据库(示例中为postgres):

```typescript
@ViewEntity({
    expression: `
        SELECT "post"."id" "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `
})
```

或者是QueryBuilder的一个实例

```typescript
@ViewEntity({
    expression: (connection: Connection) => connection.createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
})
```

**注意:** 由于驱动程序的限制,不支持参数绑定。请改用文字参数。

```typescript
@ViewEntity({
    expression: (connection: Connection) => connection.createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
        .where("category.name = :name", { name: "Cars" })  // <-- 这是错的
        .where("category.name = 'Cars'")                   // <-- 这是对的
})
```

每个视图实体都必须在连接选项中注册:

```typescript
import {createConnection, Connection} from "typeorm";
import {UserView} from "./entity/UserView";

const connection: Connection = await createConnection({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: [UserView]
});
```
或者你可以指定包含所有实体的整个目录 - 所有实体都将被加载:

```typescript
import {createConnection, Connection} from "typeorm";

const connection: Connection = await createConnection({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
    entities: ["entity/*.js"]
});
```

## 视图实体列

要将视图中的数据映射到正确的实体列,必须使用`@ViewColumn()`装饰器标记实体列,并将这些列指定为select语句别名。

字符串表达式定义的示例:

```typescript
import {ViewEntity, ViewColumn} from "typeorm";

@ViewEntity({
    expression: `
        SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName"
        FROM "post" "post"
        LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id"
    `
})
export class PostCategory {

    @ViewColumn()
    id: number;

    @ViewColumn()
    name: string;

    @ViewColumn()
    categoryName: string;

}
```

使用QueryBuilder的示例:

```typescript
import {ViewEntity, ViewColumn} from "typeorm";

@ViewEntity({
    expression: (connection: Connection) => connection.createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
})
export class PostCategory {

    @ViewColumn()
    id: number;

    @ViewColumn()
    name: string;

    @ViewColumn()
    categoryName: string;

}
```

## 完整示例

让我们创建两个实体和一个包含来自这些实体的聚合数据的视图:

```typescript
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

}
```

```typescript
import {Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn} from "typeorm";
import {Category} from "./Category";

@Entity()
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    categoryId: number;

    @ManyToOne(() => Category)
    @JoinColumn({ name: "categoryId" })
    category: Category;

}
```

```typescript
import {ViewEntity, ViewColumn} from "typeorm";

@ViewEntity({
    expression: (connection: Connection) => connection.createQueryBuilder()
        .select("post.id", "id")
        .addSelect("post.name", "name")
        .addSelect("category.name", "categoryName")
        .from(Post, "post")
        .leftJoin(Category, "category", "category.id = post.categoryId")
})
export class PostCategory {

    @ViewColumn()
    id: number;

    @ViewColumn()
    name: string;

    @ViewColumn()
    categoryName: string;

}
```

然后用数据填充这些表并从PostCategory视图请求所有数据:

```typescript
import {getManager} from "typeorm";
import {Category} from "./entity/Category";
import {Post} from "./entity/Post";
import {PostCategory} from "./entity/PostCategory";

const entityManager = getManager();

const category1 = new Category();
category1.name = "Cars";
await entityManager.save(category1);

const category2 = new Category();
category2.name = "Airplanes";
await entityManager.save(category2);

const post1 = new Post();
post1.name = "About BMW";
post1.categoryId = category1.id;
await entityManager.save(post1);

const post2 = new Post();
post2.name = "About Boeing";
post2.categoryId = category2.id;
await entityManager.save(post2);

const postCategories = await entityManager.find(PostCategory);
const postCategory = await entityManager.findOne(PostCategory, { id: 1 });
```

`postCategories`的结果将是:

```
[ PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' },
  PostCategory { id: 2, name: 'About Boeing', categoryName: 'Airplanes' } ]
```

在`postCategory`中:

```
PostCategory { id: 1, name: 'About BMW', categoryName: 'Cars' }
```


text:
If-then-else clauses have the form:

````
if <conditional-expression> then <expression1> else <expression2>
````

Both `<expression1>` and `<expression2>` must have the same type, and
`<conditional-expression>` must be a singular boolean.

If `<conditional-expression>` is true, then `<expression1>` is evaluated and
returned; otherwise `<expression2>` is evaluated and returned.

If-then-else clauses have been implemented as late-binding, so potential missing
inspectors on the branch not taken are ignored. This makes it safe to write
cross-platform expressions without worrying about throwing errors for incorrect
OS-specific Inspectors. For instance, you can write:

{{#example}}
Q: if name of operating system contains "Win" then name of application "conf.exe" of registry else "conf.exe"
A: conf.exe
{{/example}}

On a non-Windows OS, this expression will execute the `else` expression and
avoid an attempt to inspect a non-existent registry.

If-statements can be useful for reporting user-defined errors:

{{#example}}
Q: if (year of current date as integer < 2006) then "Still good" else error "Expired"
E: User-defined error: Expired
{{/example}}

This expression throws a user-defined error if the argument is false.

{{#example}}
Q: if (name of operating system = "WinXP") then "wired" else if (name of operating system ="WinNT") then "tired" else "expired"
A: wired
{{/example}}

This expression does a three-way test of the operating system.


text:
package work.technie.popularmovies.utils;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Toast;

import work.technie.popularmovies.R;

/**
 * Created by anupam on 23/12/16.
 */

public class AppRate {

    private final static int DAYS_UNTIL_PROMPT = 3;
    private final static int LAUNCHES_UNTIL_PROMPT = 3;
    private static final String DONT_SHOW_AGAIN = "DONT_SHOW_AGAIN";
    private static final String LAUNCH_COUNT = "LAUNCH_COUNT";
    private static final String DEBUT_LAUNCH = "DEBUT_LAUNCH";

    public static void initializeRater(final Context mContext) {
        String APP_RATING = "APP_RATING";
        SharedPreferences prefs = mContext.getSharedPreferences(APP_RATING, 0);
        if (prefs.getBoolean(DONT_SHOW_AGAIN, false)) {
            return;
        }
        final SharedPreferences.Editor editor = prefs.edit();
        final long launchCount = prefs.getLong(LAUNCH_COUNT, 0) + 1;
        editor.putLong(LAUNCH_COUNT, launchCount);

        final long[] debutLaunch = {prefs.getLong(DEBUT_LAUNCH, 0)};
        if (debutLaunch[0] == 0) {
            debutLaunch[0] = System.currentTimeMillis();
            editor.putLong(DEBUT_LAUNCH, debutLaunch[0]);
        }
        editor.apply();

        if (launchCount >= LAUNCHES_UNTIL_PROMPT) {
            long minTime = debutLaunch[0] + DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000;
            if (System.currentTimeMillis() >= minTime) {

                final AlertDialog dialog = new AlertDialog.Builder(mContext)
                        .setCancelable(false)
                        .setTitle(R.string.rate_our_app)
                        .setMessage(R.string.rate_message)
                        .setPositiveButton(R.string.rate_now, null)
                        .setNegativeButton(R.string.remind_me_later, null)
                        .setNeutralButton(R.string.dont_remind_me, null)
                        .create();
                dialog.show();

                dialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + mContext.getPackageName())));
                        } catch (ActivityNotFoundException e) {
                            Toast.makeText(mContext, mContext.getString(R.string.google_play_store_error), Toast.LENGTH_SHORT).show();
                        }
                        editor.putBoolean(DONT_SHOW_AGAIN, true);
                        editor.apply();
                        dialog.dismiss();
                    }
                });
                dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        editor.putLong(LAUNCH_COUNT, 0);
                        debutLaunch[0] = System.currentTimeMillis();
                        editor.putLong(DEBUT_LAUNCH, debutLaunch[0]);
                        editor.apply();
                        dialog.dismiss();
                    }
                });
                dialog.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        editor.putBoolean(DONT_SHOW_AGAIN, true);
                        editor.apply();
                        dialog.dismiss();
                    }
                });
            }
        }
    }
}


text:
dojo.provide("dojobook.creating_widgets.widgets.Ask");

dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojo.io.script");
dojo.require("dijit.Tooltip");

dojo.declare(
"dojobook.creating_widgets.widgets.Ask",
[dijit._Widget, dijit._Templated],
{
    templatePath: dojo.moduleUrl("dojobook",
             "creating_widgets/templates/Ask.html"),

    postCreate: function(){
       // Don't do anything because all the magic happens in _getQuestions
    },

   _getQuestions: function() {
       // Through JavaScript closures, this variable allows us to reference the
       // surrounding object from within the get(...) methods.
       var hookedTo = this;

       // Go to Yahoo Answers for relevant questions
       dojo.io.script.get({
           // URL for Yahoo Relevant Questions
           url: "http://answers.yahooapis.com/AnswersService/V1/questionSearch",

           // Send search term parameters.  The appid is the one you obtained for
           // chapter 3's example.
           content: {
               appid: "DEMO",
               /* The search term we're sending is the body of the tag */
               query: hookedTo.containerNode.innerHTML,
               output: "json",
               results: 3,
               /* Look only in the questions for the term, not the answers */
               search_in: "question"
           },

           // If the response takes longer than 10000ms (= 10 seconds), error out
           timeout: 10000,

           // Yahoo API requires you to send the callback function name in the
           // parameter "callback"
           callbackParamName: "callback",

           // Function run when Yahoo returns with the answer
           load: function(results) {
              // Build the tooltip text
              var questionTooltipHtml = "
";
              dojo.forEach(results.all.questions, function(question) {
                 questionTooltipHtml +=
                     dojo.string.substitute(
                         "
${Subject}"+
                         "
${Content}
",
                         question
                     );
              });

              // Create a tooltip
              questionTooltipHtml += "
";
              dijit.showTooltip(
                 questionTooltipHtml,
                 hookedTo.domNode
              );
           },

          // And this is the callback used when a web service communication
          // error or timeout occurs.  Note that errors returned from Yahoo
          // in the response are still handled with load()
          error: function(text) {
             alert("An error has occurred.");
             return text;
          }
      });
   }  // End of _getQuestions

});


text:
import { win32 as path } from 'path'
import execa from 'execa'

type IEnvironmentValueMatch = { groups: { name: string, type: string, data: string } } & RegExpMatchArray

export async function setupWindowsEnvironmentPath (pnpmHomeDir: string): Promise<string> {
  const pathRegex = /^ {4}(?<name>PATH) {4}(?<type>\w+) {4}(?<data>.*)$/gim
  const pnpmHomeRegex = /^ {4}(?<name>PNPM_HOME) {4}(?<type>\w+) {4}(?<data>.*)$/gim
  const regKey = 'HKEY_CURRENT_USER\\Environment'

  const queryResult = await execa('reg', ['query', regKey])

  if (queryResult.failed) {
    return 'Win32 registry environment values could not be retrieved'
  }

  const queryOutput = queryResult.stdout
  const pathValueMatch = [...queryOutput.matchAll(pathRegex)] as IEnvironmentValueMatch[]
  const homeValueMatch = [...queryOutput.matchAll(pnpmHomeRegex)] as IEnvironmentValueMatch[]

  let commitNeeded = false
  let homeDir = pnpmHomeDir
  const logger = []

  if (homeValueMatch.length === 1) {
    homeDir = homeValueMatch[0].groups.data
    logger.push(`Currently 'PNPM_HOME' is set to '${homeDir}'`)
  } else {
    logger.push(`Setting 'PNPM_HOME' to value '${homeDir}'`)
    const addResult = await execa('reg', ['add', regKey, '/v', 'PNPM_HOME', '/t', 'REG_EXPAND_SZ', '/d', homeDir, '/f'])
    if (addResult.failed) {
      logger.push(`\t${addResult.stderr}`)
    } else {
      commitNeeded = true
      logger.push(`\t${addResult.stdout}`)
    }
  }

  if (pathValueMatch.length === 1) {
    const pathData = pathValueMatch[0].groups.data
    if (pathData == null || pathData.trim() === '') {
      logger.push('Current PATH is empty. No changes to this environment variable are applied')
    } else {
      const homeDirPath = path.parse(path.normalize(homeDir))

      if (pathData
        .split(path.delimiter)
        .map(p => path.normalize(p))
        .map(p => path.parse(p))
        .map(p => `${p.dir}${path.sep}${p.base}`.toUpperCase())
        .filter(p => p !== '')
        .includes(`${homeDirPath.dir}${path.sep}${homeDirPath.base}`.toUpperCase())) {
        logger.push('PATH already contains PNPM_HOME')
      } else {
        logger.push('Updating PATH')
        const addResult = await execa('reg', ['add', regKey, '/v', pathValueMatch[0].groups.name, '/t', 'REG_EXPAND_SZ', '/d', `${homeDir}${path.delimiter}${pathData}`, '/f'])
        if (addResult.failed) {
          logger.push(`\t${addResult.stderr}`)
        } else {
          commitNeeded = true
          logger.push(`\t${addResult.stdout}`)
        }
      }
    }
  } else {
    logger.push('Current PATH is not set. No changes to this environment variable are applied')
  }

  if (commitNeeded) {
    await execa('setx', ['PNPM_HOME', homeDir])
  }

  return logger.join('\n')
}


text:
from random import randint, uniform
from pygame.math import Vector2 as V2
from math import hypot, pi, sin, cos, sqrt

G = 0.5

Density = 0.1

COR = 1.0 # Coefficient of Restitution

# Set simulation hard clock speed (fps)
clock_speed = 144


text:
/*
 * $Author: yjung $
 * $Date: 2006/02/23 11:04:17 $
 * $Revision: 1.9 $
 * $Name: qfits-6_2_0 $
 */

#ifndef QFITS_IMAGE_H
#define QFITS_IMAGE_H

/*-----------------------------------------------------------------------------
                                   Includes
 -----------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/*-----------------------------------------------------------------------------
                                   Defines
 -----------------------------------------------------------------------------*/

/** Symbol to set returned pixel type to float */
#define PTYPE_FLOAT        0
/** Symbol to set returned pixel type to int */
#define PTYPE_INT        1
/** Symbol to set returned pixel type to double */
#define PTYPE_DOUBLE    2

/* FITS pixel depths */
/* FITS BITPIX=8 */
#define BPP_8_UNSIGNED        (8)
/* FITS BITPIX=16 */
#define BPP_16_SIGNED        (16)
/* FITS BITPIX=32 */
#define BPP_32_SIGNED        (32)
/* FITS BITPIX=-32 */
#define BPP_IEEE_FLOAT      (-32)
/* FITS BITPIX=-64 */
#define BPP_IEEE_DOUBLE     (-64)
/* Default BITPIX for output */
#define BPP_DEFAULT         BPP_IEEE_FLOAT

/*-----------------------------------------------------------------------------
                                   New types
 -----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------*/
/**
  @brief    Alias for unsigned char

  A 'byte' is just an alias for an unsigned char. It is only defined
  for readability.
 */
/*----------------------------------------------------------------------------*/
typedef unsigned char byte ;

/*----------------------------------------------------------------------------*/
/**
  @brief    qfits loader control object

  This structure serves two purposes: input and output for the qfits
  pixel loading facility. To request pixels from a FITS file, you
  need to allocate (statically or dynamically) such a structure and
  fill up the input fields (filename, xtension number, etc.) to specify
  the pixels you want from the file.

  Before performing the actual load, you must pass the initialized
  structure to qfitsloader_init() which will check whether the operation
  is feasible or not (check its returned value).

  If the operation was deemed feasible, you can proceed to load the pixels,
  passing the same structure to qfits_loadpix() which will fill up the
  output fields of the struct. Notice that a pixel buffer will have been
  allocated (through malloc or mmap) and placed into the structure. You
  need to call free() on this pointer when you are done with it,
  typically in the image or cube destructor.

  The qfitsloader_init() function is also useful to probe a FITS file
  for useful informations, like getting the size of images in the file,
  the pixel depth, or data offset.

  Example of a code that prints out various informations about
  a plane to load, without actually loading it:

  @code
int main(int argc, char * argv[])
{
    qfitsloader    ql ;

    ql.filename = argv[1] ;
    ql.xtnum    = 0 ;
    ql.pnum     = 0 ;

    if (qfitsloader_init(&ql)!=0) {
        printf("cannot read info about %s\n", argv[1]);
        return -1 ;
    }

    printf(    "file         : %s\n"
            "xtnum        : %d\n"
            "pnum         : %d\n"
            "# xtensions  : %d\n"
            "size X       : %d\n"
            "size Y       : %d\n"
            "planes       : %d\n"
            "bitpix       : %d\n"
            "datastart    : %d\n"
            "datasize     : %d\n"
            "bscale       : %g\n"
            "bzero        : %g\n",
            ql.filename,
            ql.xtnum,
            ql.pnum,
            ql.exts,
            ql.lx,
            ql.ly,
            ql.np,
            ql.bitpix,
            ql.seg_start,
            ql.seg_size,
            ql.bscale,
            ql.bzero);
    return 0 ;
}
  @endcode
 */
/*----------------------------------------------------------------------------*/
typedef struct qfitsloader {

    /** Private field to see if structure has been initialized */
    int            _init ;

    /** input: Name of the file you want to read pixels from */
    char    *    filename ;
    /** input: xtension number you want to read */
    int            xtnum ;
    /** input: Index of the plane you want, from 0 to np-1 */
    int            pnum ;
    /** input: Pixel type you want (PTYPE_FLOAT, PTYPE_INT or PTYPE_DOUBLE) */
    int            ptype ;
    /** input: Guarantee file copy or allow file mapping */
    int         map ;

    /** output: Total number of extensions found in file */
    int            exts ;
    /** output: Size in X of the requested plane */
    int            lx ;
    /** output: Size in Y of the requested plane */
    int            ly ;
    /** output: Number of planes present in this extension */
    int            np ;
    /** output: BITPIX for this extension */
    int            bitpix ;
    /** output: Start of the data segment (in bytes) for your request */
    int            seg_start ;
    /** output: Size of the data segment (in bytes) for your request */
    int         seg_size ;
    /** output: BSCALE found for this extension */
    double        bscale ;
    /** output: BZERO found for this extension */
    double        bzero ;

    /** output: Pointer to pixel buffer loaded as integer values */
    int        *    ibuf ;
    /** output: Pointer to pixel buffer loaded as float values */
    float    *    fbuf ;
    /** output: Pointer to pixel buffer loaded as double values */
    double    *    dbuf ;

} qfitsloader ;

/*----------------------------------------------------------------------------*/
/**
  @brief    qfits dumper control object

  This structure offers various control parameters to dump a pixel
  buffer to a FITS file. The buffer will be dumped as requested
  to the requested file in append mode. Of course, the requested file
  must be writeable for the operation to succeed.

  The following example demonstrates how to save a linear ramp sized
  100x100 to a FITS file with BITPIX=16. Notice that this code only
  dumps the pixel buffer, no header information is provided in this
  case.

  @code
    int   i, j ;
    int * ibuf ;
    qfitsdumper    qd ;

    // Fill a buffer with 100x100 int pixels
    ibuf = malloc(100 * 100 * sizeof(int));
    for (j=0 ; j<100 ; j++) {
        for (i=0 ; i<100 ; i++) {
            ibuf[i+j*100] = i+j ;
        }
    }

    qd.filename  = "out.fits" ;     // Output file name
    qd.npix      = 100 * 100 ;      // Number of pixels
    qd.ptype     = PTYPE_INT ;      // Input buffer type
    qd.ibuf      = ibuf ;           // Set buffer pointer
    qd.out_ptype = BPP_16_SIGNED ;  // Save with BITPIX=16

    // Dump buffer to file (error checking omitted for clarity)
    qfits_pixdump(&qd);

    free(ibuf);
  @endcode

  If the provided output file name is "STDOUT" (all capitals), the
  function will dump the pixels to the stdout steam (usually the console,
  could have been re-directed).
 */
/*----------------------------------------------------------------------------*/
typedef struct qfitsdumper {

    /** Name of the file to dump to, "STDOUT" to dump to stdout */
    char     *    filename ;
    /** Number of pixels in the buffer to dump */
    int            npix ;
    /** Buffer type: PTYPE_FLOAT, PTYPE_INT or PTYPE_DOUBLE */
    int            ptype ;

    /** Pointer to input integer pixel buffer */
    int        *    ibuf ;
    /** Pointer to input float pixel buffer */
    float    *    fbuf ;
    /** Pointer to input double pixel buffer */
    double    *    dbuf ;

    /** Requested BITPIX in output FITS file */
    int            out_ptype ;
} qfitsdumper ;

/*-----------------------------------------------------------------------------
                               Function prototypes
 -----------------------------------------------------------------------------*/

int qfitsloader_init(qfitsloader *) ;
int qfits_loadpix(qfitsloader *) ;
int qfits_loadpix_window(qfitsloader *, int, int, int, int) ;
int qfits_pixdump(qfitsdumper *) ;
double * qfits_pixin_double(byte *, int, int, double, double) ;
byte * qfits_pixdump_double(double *, int, int) ;
byte * qfits_pixdump_int(int *, int, int) ;
float * qfits_pixin_float(byte *, int, int, double, double) ;
int qfits_pixin_floatbuf(byte *, int, int, double, double, float *) ;
byte * qfits_pixdump_float(float *, int, int) ;

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="BuildJarProjectSettings">
    <option name="BUILD_JARS_ON_MAKE" value="false" />
  </component>
  <component name="CompilerConfiguration">
    <option name="DEFAULT_COMPILER" value="Javac" />
    <excludeFromCompile>
      <file url="file://$PROJECT_DIR$/jps/jps-builders/src/org/jetbrains/jps/incremental/java/OptimizedFileManager.java" />
      <file url="file://$PROJECT_DIR$/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java" />
      <file url="file://$PROJECT_DIR$/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager17.java" />
      <file url="file://$PROJECT_DIR$/java/java-tests/testSrc/com/intellij/index/IndexTestGenerator.scala" />
    </excludeFromCompile>
    <resourceExtensions>
      <entry name=".+\.(properties|gif|png|jpeg|jpg|xml|dtd|tld|xsd|ft|html|template)" />
    </resourceExtensions>
    <wildcardResourcePatterns>
      <entry name="!*.form" />
      <entry name="!*.java" />
      <entry name="!*.class" />
      <entry name="!*.groovy" />
      <entry name="!*.flex" />
      <entry name="!*.kt" />
      <entry name="!*.iml" />
      <entry name="!*.gant" />
    </wildcardResourcePatterns>
    <annotationProcessing>
      <profile default="true" name="Default" enabled="false">
        <processorPath useClasspath="true" />
      </profile>
    </annotationProcessing>
    <bytecodeTargetLevel target="1.6">
      <module name="annotations" target="1.5" />
      <module name="annotations-common" target="1.5" />
      <module name="annotations-java8" target="1.8" />
      <module name="community-tests" target="1.8" />
      <module name="gradle-jps-plugin" target="1.6" />
      <module name="groovy-rt-constants" target="1.5" />
      <module name="groovy_rt" target="1.5" />
      <module name="intellilang-jps-plugin" target="1.6" />
      <module name="IntelliLang-tests" target="1.8" />
      <module name="java-runtime" target="1.3" />
      <module name="java-tests" target="1.8" />
      <module name="javac2" target="1.5" />
      <module name="javaFX-jps-plugin" target="1.6" />
      <module name="jps-builders" target="1.6" />
      <module name="jps-launcher" target="1.6" />
      <module name="jps-model-api" target="1.6" />
      <module name="jps-model-impl" target="1.6" />
      <module name="jps-model-serialization" target="1.6" />
      <module name="jps-standalone-builder" target="1.6" />
      <module name="json-tests" target="1.8" />
      <module name="junit_rt" target="1.3" />
      <module name="maven-jps-plugin" target="1.6" />
      <module name="remote-servers-agent-rt" target="1.5" />
      <module name="svn4idea-tests" target="1.8" />
      <module name="tasks-tests" target="1.8" />
      <module name="testng_rt" target="1.5" />
      <module name="ui-designer-jps-plugin" target="1.6" />
      <module name="util-rt" target="1.6" />
    </bytecodeTargetLevel>
  </component>
  <component name="EclipseCompilerSettings">
    <option name="GENERATE_NO_WARNINGS" value="true" />
    <option name="DEPRECATION" value="false" />
  </component>
  <component name="EclipseEmbeddedCompilerSettings">
    <option name="GENERATE_NO_WARNINGS" value="true" />
    <option name="DEPRECATION" value="false" />
  </component>
  <component name="JavacSettings">
    <option name="MAXIMUM_HEAP_SIZE" value="400" />
  </component>
</project>