text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="movie_title_color">@android:color/white</color>
</resources>


text:
@implementation UIView (DBExtension)

//设置setter方法

-(void)setSize:(CGSize)size{

    CGRect frame=self.frame;
    frame.size=size;
    self.frame=frame;
}

-(void)setWidth:(CGFloat)width{

    CGRect frame=self.frame;
    frame.size.width=width;
    self.frame=frame;
}

-(void)setHeight:(CGFloat)height{

    CGRect frame=self.frame;
    frame.size.height=height;
    self.frame=frame;

}

-(void)setX:(CGFloat)x{

    CGRect frame=self.frame;
    frame.origin.x=x;
    self.frame=frame;

}

-(void)setY:(CGFloat)y{

    CGRect frame=self.frame;
    frame.origin.y=y;
    self.frame=frame;
}

-(void)setCenterX:(CGFloat)centerX{
    CGPoint center=self.center;
    center.x=centerX;
    self.center=center;
}

-(void)setCenterY:(CGFloat)centerY{

    CGPoint center=self.center;
    center.y=centerY;
    self.center=center;

}

//设置getter方法

-(CGSize)size{

    return self.frame.size;
}

-(CGFloat)width{

    return self.frame.size.width;
}

-(CGFloat)height{

    return self.frame.size.height;
}

-(CGFloat)x{

    return self.frame.origin.x;
}

-(CGFloat)y{

    return self.frame.origin.y;
}

-(CGFloat)centerX{
    return  self.center.x;

}
-(CGFloat)centerY{

    return self.center.y;
}

-(BOOL)db_isShowingOnKeyWindow{

    // 主窗口
    UIWindow *window=[UIApplication sharedApplication].keyWindow;

    // 以主窗口左上角为坐标原点, 计算self的矩形框
    CGRect newRect=[window  convertRect:self.frame fromView:self.superview];
    CGRect bounds=window.bounds;

     // 主窗口的bounds 和 self的矩形框 是否有重叠
    BOOL intersects=CGRectIntersectsRect(newRect, bounds);

    return !self.isHidden&&self.alpha>0.01&&self.window==window&&intersects;
}

@end

redpajama_set_name: RedPajamaGithub


text:
namespace policy {

const char kTestToken[] = "device_token_fetcher_test_auth_token";

using testing::_;
using testing::Mock;

class MockTokenAvailableObserver : public DeviceTokenFetcher::Observer {
 public:
  MockTokenAvailableObserver() {}
  virtual ~MockTokenAvailableObserver() {}

  MOCK_METHOD0(OnDeviceTokenAvailable, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockTokenAvailableObserver);
};

class DeviceTokenFetcherTest : public testing::Test {
 protected:
  DeviceTokenFetcherTest()
      : ui_thread_(BrowserThread::UI, &loop_),
        file_thread_(BrowserThread::FILE, &loop_) {
    EXPECT_TRUE(temp_user_data_dir_.CreateUniqueTempDir());
  }

  virtual void SetUp() {
    cache_.reset(new UserPolicyCache(
        temp_user_data_dir_.path().AppendASCII("DeviceTokenFetcherTest")));
    service_.set_backend(&backend_);
  }

  virtual void TearDown() {
    loop_.RunAllPending();
  }

  MessageLoop loop_;
  MockDeviceManagementBackend backend_;
  MockDeviceManagementService service_;
  scoped_ptr<CloudPolicyCacheBase> cache_;
  PolicyNotifier notifier_;
  ScopedTempDir temp_user_data_dir_;

 private:
  BrowserThread ui_thread_;
  BrowserThread file_thread_;
};

TEST_F(DeviceTokenFetcherTest, FetchToken) {
  testing::InSequence s;
  EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce(
      MockDeviceManagementBackendSucceedRegister());
  DeviceTokenFetcher fetcher(&service_, cache_.get(), &notifier_);
  MockTokenAvailableObserver observer;
  EXPECT_CALL(observer, OnDeviceTokenAvailable());
  fetcher.AddObserver(&observer);
  EXPECT_EQ("", fetcher.GetDeviceToken());
  fetcher.FetchToken("fake_auth_token", "fake_device_id",
                     em::DeviceRegisterRequest::USER,
                     "fake_machine_id", "fake_machine_model");
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  std::string token = fetcher.GetDeviceToken();
  EXPECT_NE("", token);

  // Calling FetchToken() again should result in a new token being fetched.
  EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce(
      MockDeviceManagementBackendSucceedRegister());
  EXPECT_CALL(observer, OnDeviceTokenAvailable());
  fetcher.FetchToken("fake_auth_token", "fake_device_id",
                     em::DeviceRegisterRequest::USER,
                     "fake_machine_id", "fake_machine_model");
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  std::string token2 = fetcher.GetDeviceToken();
  EXPECT_NE("", token2);
  EXPECT_NE(token, token2);
  fetcher.RemoveObserver(&observer);
}

TEST_F(DeviceTokenFetcherTest, RetryOnError) {
  testing::InSequence s;
  EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce(
      MockDeviceManagementBackendFailRegister(
          DeviceManagementBackend::kErrorRequestFailed)).WillOnce(
      MockDeviceManagementBackendSucceedRegister());
  DeviceTokenFetcher fetcher(&service_, cache_.get(), &notifier_, 0, 0, 0);
  MockTokenAvailableObserver observer;
  EXPECT_CALL(observer, OnDeviceTokenAvailable());
  fetcher.AddObserver(&observer);
  fetcher.FetchToken("fake_auth_token", "fake_device_id",
                     em::DeviceRegisterRequest::USER,
                     "fake_machine_id", "fake_machine_model");
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_NE("", fetcher.GetDeviceToken());
  fetcher.RemoveObserver(&observer);
}

TEST_F(DeviceTokenFetcherTest, UnmanagedDevice) {
  EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce(
      MockDeviceManagementBackendFailRegister(
          DeviceManagementBackend::kErrorServiceManagementNotSupported));
  EXPECT_FALSE(cache_->is_unmanaged());
  DeviceTokenFetcher fetcher(&service_, cache_.get(), &notifier_);
  MockTokenAvailableObserver observer;
  EXPECT_CALL(observer, OnDeviceTokenAvailable()).Times(0);
  fetcher.AddObserver(&observer);
  fetcher.FetchToken("fake_auth_token", "fake_device_id",
                     em::DeviceRegisterRequest::USER,
                     "fake_machine_id", "fake_machine_model");
  loop_.RunAllPending();
  Mock::VerifyAndClearExpectations(&observer);
  EXPECT_EQ("", fetcher.GetDeviceToken());
  EXPECT_TRUE(cache_->is_unmanaged());
  fetcher.RemoveObserver(&observer);
}

}  // namespace policy


text:
'use strict';

const Song = require('./songsModel');

module.exports = {
	getSongs: function(request, response){
		let data = request.query;
		Song.sync().then(function(){
			Song.findAll({
				where:{
					//to be filled in later
					played: data.played;
				},
				order:{
					['ordernumber','ASC']
				}
			}).then(function(songs){
				response.send(songs)
			});
		});
	},
	postSongs: function(request, response){
		Song.sync().then(function(){
			return Song.create(request.body)
		});
	}
};


text:
/*
 * $Id: DTDEntityDecl.cpp 568078 2007-08-21 11:43:25Z amassari $
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/DTD/DTDEntityDecl.hpp>

XERCES_CPP_NAMESPACE_BEGIN

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(DTDEntityDecl)

void DTDEntityDecl::serialize(XSerializeEngine& serEng)
{
    XMLEntityDecl::serialize(serEng);

    if (serEng.isStoring())
    {
        serEng<<fDeclaredInIntSubset;
        serEng<<fIsParameter;
        serEng<<fIsSpecialChar;
    }
    else
    {
        serEng>>fDeclaredInIntSubset;
        serEng>>fIsParameter;
        serEng>>fIsSpecialChar;
    }
}

XERCES_CPP_NAMESPACE_END


text:
package com.teamrune.symbology.blocks;

import com.teamrune.symbology.Symbology;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;

public class BlockRuneCrafter extends Block
{
    public BlockRuneCrafter()
    {
        super(Material.rock);
        setCreativeTab(Symbology.runesTab);
        setUnlocalizedName("runeenchanter");
        setHarvestLevel("pickaxe", 2);
        setHardness(10.0F);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;

namespace RestSample
{
    public class QiClient
    {
        private HttpClient _httpClient;
        private string _baseUrl;

        // VERY IMPORTANT: edit the following values to reflect the authorization items you were given

        static string _resource = "PLACEHOLDER_REPLACE_WITH_RESOURCE";
        static string _authority = "PLACEHOLDER_REPLACE_WITH_AUTHORITY";
        static string _appId = "PLACEHOLDER_REPLACE_WITH_USER_ID";
        static string _appKey = "PLACEHOLDER_REPLACE_WITH_USER_SECRET";

        // Azure AD authentication related
        private static AuthenticationContext _authContext = null;

        // REST API url strings
        private string _typesBase = @"Qi/Types";
        private string _streamsBase = @"Qi/Streams";
        private string _behaviorsBase = @"Qi/Behaviors";
        private string _insertSingle = @"/Data/InsertValue";
        private string _insertMultiple = @"/Data/InsertValues";
        private string _getTemplate = @"/Data/GetWindowValues?startIndex={0}&endIndex={1}";
        private string _getRangeTemplate = @"/Data/GetRangeValues?startIndex={0}&skip={1}&count={2}&reversed={3}&boundaryType={4}";
        private string _updateSingle = @"/Data/UpdateValue";
        private string _updateMultiple = @"/Data/UpdateValues";
        private string _removeSingleTemplate = @"/{0}/Data/RemoveValue?index={1}";
        private string _removeMultipleTemplate = @"/{0}/Data/RemoveWindowValues?startIndex={1}&endIndex={2}";

        // void error formats
        private string _createError = "Failed to create {0} with Id = {1}";
        private string _updateError = "Failed to update {0} with Id = {1}";
        private string _deleteError = "Failed to delete event from stream {0} with index = {1}";
        private string _deleteMultipleError = "Failed to delete events from stream {0} with indices {1}";

        public QiClient(string baseUrl)
        {
            _httpClient = new HttpClient();
            _baseUrl = baseUrl;
            if (_baseUrl.Substring(_baseUrl.Length - 1).CompareTo(@"/") != 0)
                _baseUrl = _baseUrl + "/";

            _httpClient.BaseAddress = new Uri(_baseUrl);
            _httpClient.Timeout = new TimeSpan(0, 0, 30);
            _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        }
        #region Metadata methods

        /// <summary>
        /// Create a stream on the target Qi Service
        /// </summary>
        /// <param name="streamDef">QiStream object with name, Id, type</param>
        /// <returns>void</returns>
        public async Task<string> CreateStream(QiStream streamDef)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase),
                Method = HttpMethod.Post,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            string content = JsonConvert.SerializeObject(streamDef);
            msg.Content = new StringContent(content, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await _httpClient.SendAsync(msg);
            if (!response.IsSuccessStatusCode)
            {
                throw new QiError(response.StatusCode, "Error creating Stream with id " + streamDef.Id);
            }
            else
            {
                return await response.Content.ReadAsStringAsync();
            }
        }

        public async Task UpdateStream(string streamId, QiStream streamDef)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId),
                Method = HttpMethod.Put,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            string content = JsonConvert.SerializeObject(streamDef);
            msg.Content = new StringContent(content, Encoding.UTF8, "application/json");

            await SendAndRespondVoid(msg, _updateError, "stream", streamId);
        }

        /// <summary>
        /// Deletes the stream whose Id is passed
        /// </summary>
        /// <param name="streamId">Id of the QiStream to be deleted</param>
        /// <returns>void</returns>
        public async Task DeleteStream(string streamId)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId),
                Method = HttpMethod.Delete,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            await SendAndRespondVoid(msg, _createError, "stream", streamId);
        }

        /// <summary>
        /// Creates a QiType in the remote Qi Service.  QiTypes are required by QiStreams and cannot be deleted while so referenced.
        /// </summary>
        /// <param name="typeDef">QiType object defining a user-defined type with properties</param>
        /// <returns>void</returns>
        public async Task<string> CreateType(QiType typeDef)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _typesBase),
                Method = HttpMethod.Post,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            string content = JsonConvert.SerializeObject(typeDef);
            msg.Content = new StringContent(content, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await _httpClient.SendAsync(msg);
            if (!response.IsSuccessStatusCode)
            {
                throw new QiError(response.StatusCode, "Error creating Type with id " + typeDef.Id);
            }
            else
            {
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// Deletes a QiType in the remote Qi Service
        /// </summary>
        /// <param name="typeId">Id of the QiType to delete</param>
        /// <returns>void</returns>
        public async Task DeleteType(string typeId)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _typesBase +@"/" + typeId),
                Method = HttpMethod.Delete,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

           await  SendAndRespondVoid(msg, _deleteError, "type", typeId);
        }

        public async Task<string> CreateBehavior(QiStreamBehavior behavior)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _behaviorsBase),
                Method = HttpMethod.Post,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            string content = JsonConvert.SerializeObject(behavior);
            msg.Content = new StringContent(content, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await _httpClient.SendAsync(msg);
            if (!response.IsSuccessStatusCode)
            {
                throw new QiError(response.StatusCode, "Error creating Type with id " + behavior.Id);
            }
            else
            {
                return await response.Content.ReadAsStringAsync();
            }
        }

        public async Task DeleteBehavior(string behaviorId)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _behaviorsBase + @"/" + behaviorId),
                Method = HttpMethod.Delete,
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            await SendAndRespondVoid(msg, _deleteError, "type", behaviorId);
        }

        #endregion

        #region Create Methods for Data (Insert)

        /// <summary>
        /// Creates a single instance of a measured event in the named Qi Stream provided the object conforms to the type of the stream
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="evt">JSON serialization of the object to store</param>
        /// <returns></returns>
        public async Task CreateEvent(string streamId, string evt)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId + _insertSingle),
                Method = HttpMethod.Post
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            msg.Content = new StringContent(evt, Encoding.UTF8, "application/json");
            await SendAndRespondVoid(msg, _createError, "data event", streamId);
        }

        /// <summary>
        /// Creates multiple events in the identified Qi Stream
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="evt">JSON serialization of an array of events</param>
        /// <returns>void</returns>
        public async Task CreateEvents(string streamId, string evt)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId + _insertMultiple),
                Method = HttpMethod.Post
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            msg.Content = new StringContent(evt, Encoding.UTF8, "application/json");
            await SendAndRespondVoid(msg, _createError, "data events", streamId);
        }

        #endregion

        #region Retrieve Methods for Data
        /// <summary>
        /// Gets all values in the range identified by the start and end indices
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="startIndex">string representation of a value related to the streams key; for a DateTime key, an ISO 8601 time reference</param>
        /// <param name="endIndex">string representaion of a value related to the stream's key denoting the end of the desired range</param>
        /// <returns>JSON serialized array of events</returns>
        public async Task<string> GetWindowValues(string streamId, string startIndex, string endIndex)
        {
            string getClause = string.Format(_getTemplate, startIndex, endIndex);
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId + getClause),
                Method = HttpMethod.Get
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            HttpResponseMessage response = await _httpClient.SendAsync(msg);
            if (response.IsSuccessStatusCode)
            {
                string jsonResults = await response.Content.ReadAsStringAsync();
                return jsonResults;
            }
            else
            {
                throw new QiError(response.StatusCode, "Error getting windows values: " + response.ReasonPhrase);
            }
        }

        public async Task<string> GetRangeValues(string streamId, string startIndex, int skip, int count, bool reverse, QiBoundaryType boundaryType)
        {
            string getClause = string.Format(_getRangeTemplate, startIndex, skip, count, reverse, boundaryType);
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId + getClause),
                Method = HttpMethod.Get
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            HttpResponseMessage response = await _httpClient.SendAsync(msg);
            if (response.IsSuccessStatusCode)
            {
                string jsonResults = await response.Content.ReadAsStringAsync();
                return jsonResults;
            }
            else
            {
                throw new QiError(response.StatusCode, "Error getting range values: " + response.ReasonPhrase);
            }
        }

        #endregion

        #region Update Methods for Data
        /// <summary>
        /// Updates a single event if found
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="evt">JSON serialization of the updated event</param>
        /// <returns></returns>
        public async Task UpdateValue(string streamId, string evt)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId + _updateSingle),
                Method = HttpMethod.Put
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            msg.Content = new StringContent(evt, Encoding.UTF8, "application/json");
            await SendAndRespondVoid(msg, _updateError, "data event", evt);
        }

        /// <summary>
        /// Updates an array of events in a stream (replaces an event with the same key value)
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="evts">JSON serialization of an array of updated events</param>
        /// <returns>void</returns>
        public async Task UpdateValues(string streamId, string evts)
        {
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(_baseUrl + _streamsBase + @"/" + streamId + _updateMultiple),
                Method = HttpMethod.Put
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            msg.Content = new StringContent(evts, Encoding.UTF8, "application/json");
            await SendAndRespondVoid(msg, _updateError, "data events", streamId);
        }

        #endregion

        /// <summary>
        /// removes a single value from the stream if the index is found
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="index">value of the key of the event to be deleted (for DateTime, ISO 8601 string)</param>
        /// <returns>void</returns>
        public async Task RemoveValue(string streamId, string index)
        {
            string uri = _baseUrl + _streamsBase + string.Format(_removeSingleTemplate, streamId, index);
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(uri),
                Method = HttpMethod.Delete
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            await SendAndRespondVoid(msg, _deleteError, streamId, index);
        }

        /// <summary>
        /// Removes all events within a range in a stream
        /// </summary>
        /// <param name="streamId">stream identifier</param>
        /// <param name="startIndex">start key value for the range</param>
        /// <param name="endIndex">end key value for the range</param>
        /// <returns>void</returns>
        public async Task RemoveWindowValues(string streamId, string startIndex, string endIndex)
        {
            string uri = _baseUrl + _streamsBase + string.Format(_removeMultipleTemplate, streamId, startIndex, endIndex);
            HttpRequestMessage msg = new HttpRequestMessage
            {
                RequestUri = new Uri(uri),
                Method = HttpMethod.Delete
            };

            string token = AcquireAuthToken();
            msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            await SendAndRespondVoid(msg, _deleteMultipleError, streamId, startIndex + ", " + endIndex);
        }

        private async Task SendAndRespondVoid(HttpRequestMessage msg, string template, string entity, string id)
        {
            HttpResponseMessage response = await _httpClient.SendAsync(msg);
            if (!response.IsSuccessStatusCode)
            {
                throw new QiError(response.StatusCode, string.Format(template, entity, id));
            }

        }

        static protected string AcquireAuthToken()
        {
            if (_authContext == null)
            {
                _authContext = new AuthenticationContext(_authority);
            }

            // tokens expire after a certain period of time
            // You can check this with the ExpiresOn property of AuthenticationResult, but it is not necessary.
            // ADAL maintains an in-memory cache of tokens and transparently refreshes them as needed
            try
            {
                ClientCredential userCred = new ClientCredential(_appId, _appKey);
                AuthenticationResult authResult = _authContext.AcquireToken(_resource, userCred);
                return authResult.AccessToken;
            }
            catch (AdalException)
            {
                return string.Empty;
            }

        }

    }
}


text:
@implementation NSString (KeyPathReplace)

- (NSString*)stringByReplacingKeyPathBindingsWithDictionaryValues:(NSDictionary*)dict {
    return [self stringByReplacingKeyPathBindingsWithDictionaryValues:dict defaultValues:nil];
}

- (NSString*)stringByReplacingKeyPathBindingsWithDictionaryValues:(NSDictionary*)dict defaultValues:(NSDictionary*)defaultValues {
    return [self stringByReplacingOccurrencesOfRegex:@"\\\\?\\{([^}:]+)(:([^}]+))?\\}" usingBlock:^NSString *(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        NSString *keyPath = nil;
        NSString *defaultValue = nil;
        if (captureCount>1) {
            keyPath = capturedStrings[1];
        }
        if (captureCount>3 && [capturedStrings[3] length]) {
            defaultValue = capturedStrings[3];
        }
        if (![defaultValue length] && defaultValues && [[defaultValues valueForKeyPath:keyPath] length]) {
            defaultValue = [defaultValues valueForKeyPath:keyPath];
        }
        NSString *val = @"";
        if ([capturedStrings[0] characterAtIndex:0] == '\\') {
            val = [capturedStrings[0] substringFromIndex:1];
        } else if (keyPath) {
            @try {
                val = [dict valueForKeyPath:keyPath];
            }
            @catch (NSException *exception) {
                val = nil;
            }
            if (!val || val == (id)[NSNull null]) {
                if (defaultValue) {
                    val = defaultValue;
                } else {
                    val = @"";
                }
            }
        }
        return val;
    }];

}

@end


text:
#ifndef WKVibration_h
#define WKVibration_h

#include <WebKit2/WKBase.h>

#ifdef __cplusplus
extern "C" {
#endif

// Provider.
typedef void (*WKVibrationProviderVibrateCallback)(WKVibrationRef vibrationRef, uint32_t vibrationTime, const void* clientInfo);
typedef void (*WKVibrationProviderCancelVibrationCallback)(WKVibrationRef vibrationRef, const void* clientInfo);

struct WKVibrationProvider {
    int                                                                 version;
    const void *                                                        clientInfo;
    WKVibrationProviderVibrateCallback                                  vibrate;
    WKVibrationProviderCancelVibrationCallback                          cancelVibration;
};
typedef struct WKVibrationProvider WKVibrationProvider;

enum { kWKVibrationProviderCurrentVersion = 0 };

WK_EXPORT WKTypeID WKVibrationGetTypeID();

WK_EXPORT void WKVibrationSetProvider(WKVibrationRef vibrationRef, const WKVibrationProvider* provider);

#ifdef __cplusplus
}
#endif

#endif // WKVibration_h


text:
Imports BVSoftware.Bvc5.Core
Imports System.Collections.ObjectModel

Partial Class BVModules_ContentBlocks_Html_Rotator_view
    Inherits Content.BVModule

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        LoadHtml()
    End Sub

    Private Sub LoadHtml()
        Dim myHtml As Collection(Of Content.ComponentSettingListItem) = SettingsManager.GetSettingList("Html")
        If myHtml IsNot Nothing Then
            If myHtml.Count > 0 Then
                Dim displayIndex As Integer = GetContentIndex(myHtml.Count - 1)
                Me.HtmlContent.Text = myHtml(displayIndex).Setting1
                Me.HtmlContent.Visible = True
            Else
                Me.HtmlContent.Visible = False
            End If
        End If
    End Sub

    Private Function GetContentIndex(ByVal maxIndex As Integer) As Integer
        Dim result As Integer = 0

        If SettingsManager.GetBooleanSetting("ShowInOrder") = True Then

            ' Find the next image index to show in sequence
            Dim nextIndex As String = Me.NextContentIndex

            ' Make sure index is a valid integer
            If nextIndex = String.Empty Then
                result = 0
            Else
                result = Integer.Parse(nextIndex, System.Globalization.CultureInfo.InvariantCulture)
            End If

            ' Make sure result is at least zero
            If result < 0 Then
                result = 0
            End If

            ' Make sure result is not greater than the maximum allowed size
            If result > maxIndex Then
                result = maxIndex
            End If

            ' We have a valid number now, save the next index for next time.
            Dim saveIndex As Integer = result + 1
            If saveIndex > maxIndex Then
                saveIndex = 0
            End If
            Me.NextContentIndex = saveIndex.ToString(System.Globalization.CultureInfo.InvariantCulture)

        Else
            ' Select Random Image
            result = BVSoftware.Web.RandomNumbers.RandomInteger(maxIndex, 0)
        End If

        Return result
    End Function

    Private Property NextContentIndex() As String
        Get
            If Session(Me.BlockId & "BVSoftware.HtmlRotator.NextContentIndex") Is Nothing Then
                Return String.Empty
            Else
                Return CType(Session(Me.BlockId & "BVSoftware.HtmlRotator.NextContentIndex"), String)
            End If
        End Get
        Set(ByVal value As String)
            Session(Me.BlockId & "BVSoftware.HtmlRotator.NextContentIndex") = value
        End Set
    End Property
End Class


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Phone.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Eve.Core.Helpers;

namespace Eve.Core.UI
{
    /// <summary>
    /// реализация, добавить
    /// анимация закрытия
    /// анимация открытия
    /// подпрыгивание при активации клавиатуры (вп)
    /// закрытие контрола при тапе вне основного контента
    ///
    /// </summary>

    public abstract class EveWindow : UserControl
    {
        /// <summary>
        /// set true if window contains a lot of input (textbox) fields
        /// </summary>
        public bool AttachToParentPage { get; set; }

        protected Popup ThisPopup { get; private set; }

        public EWindowCloseResult CloseResult { get; protected set; }

        public bool OperationResult { get; protected set; }

        private static bool _isOpen;
        private static object _locker;
        private static List<EveWindow> _listOfWindows;
        public static bool IsAnyOpen()
        {
            return _isOpen;
        }

        public static EveWindow GetTopOpenedWindow(Type ofType = null)
        {
            if (ofType == null)
            {
                return _listOfWindows.LastOrDefault();
            }

            return _listOfWindows.LastOrDefault(x => x.GetType() == ofType);
        }

        /// <summary>
        /// call this method before frame initialise
        /// </summary>
        public static void Register()
        {
#if WINDOWS_PHONE_APP
            HardwareButtons.BackPressed += HardwareButtonsOnBackPressed;
#endif
        }

#if WINDOWS_PHONE_APP
        private static void HardwareButtonsOnBackPressed(object sender, BackPressedEventArgs backPressedEventArgs)
        {
            if (IsAnyOpen())
            {
                var last = _listOfWindows.Last();

                var res = new EveWindowClosingArgs();

                last.OnBackButton(res);

                backPressedEventArgs.Handled = true;

                if (res.Cancel)
                {
                    return;
                }

                last.InnerClose(EWindowCloseResult.AutoOrUserCancel, null, false);
            }
        }
#endif

        static EveWindow()
        {
            _isOpen = false;
            _locker = new object();
            _listOfWindows = new List<EveWindow>(3);
        }

        private bool _alreadyAdded = false;

        protected TaskCompletionSource<object> _resultSource;

        protected EveWindow()
        {
            AttachToParentPage = false;
            ThisPopup = new Popup();
        }

        private void ThisPopupOnOpened(object sender, object o)
        {
            lock (_locker)
            {
                _listOfWindows.Add(this);
                _isOpen = true;

                _currentPage = PageHelper.GetCurrentPage();

                if (_currentPage != null)
                {
                    if (_currentPage.BottomAppBar != null)
                    {
                        _pageAppBarState = _currentPage.BottomAppBar;
                        _currentPage.BottomAppBar = null;
                    }
                }
            }

            OnUi.RunAsync(OnWindowShow);
        }

        protected virtual void OnWindowShow()
        {

        }

        protected virtual void OnWindowClose()
        {

        }

        protected virtual bool CancelPressedBackButton()
        {
            return false;
        }

        private void ThisPopupOnClosed(object sender, object o)
        {
            InnerClose(EWindowCloseResult.AutoOrUserCancel, null, false);

            //OnClosedUnsubscribe();
        }

        public Task<object> ShowAsync()
        {
            return ShowAsyncInner();
        }

        public virtual Task<object> ShowAsyncInner()
        {
            TryAddPopupOnParentPage();

            ThisPopup.Opened += ThisPopupOnOpened;
            ThisPopup.Closed += ThisPopupOnClosed;

            _resultSource = new TaskCompletionSource<object>();

            Width = Window.Current.CoreWindow.Bounds.Width;
            Height = Window.Current.CoreWindow.Bounds.Height;

            ThisPopup.Child = this;

            ThisPopup.IsOpen = true;

            return _resultSource.Task;
        }

        private void OnBackButton(EveWindowClosingArgs args)
        {
            if (CancelPressedBackButton())
            {
                args.Cancel = true;
                return;
            }

            RaiseOnClosing(this, args);
        }

        private AppBar _pageAppBarState;
        private Page _currentPage;

        private void InnerClose(EWindowCloseResult closeKind, object result, bool operationResultIsSuccess)
        {
            if (_currentPage != null)
            {
                if (_pageAppBarState != null)
                {
                    _currentPage.BottomAppBar = _pageAppBarState;
                }
            }

            OnWindowClose();

            OnClosedUnsubscribe();

            if (ThisPopup.IsOpen)
            {
                ThisPopup.IsOpen = false;
            }

            if (_resultSource != null)
            {
                OperationResult = operationResultIsSuccess;
                CloseResult = closeKind;
                _resultSource.SetResult(result);
                _resultSource = null;
            }

        }

        protected void CloseWithResult(object result, bool operationResultIsSuccess)
        {
            InnerClose(EWindowCloseResult.ByUserAction, result, operationResultIsSuccess);
        }

        public void CloseAsCancel()
        {
            InnerClose(EWindowCloseResult.AutoOrUserCancel, null, false);
        }

        public delegate void WindowClosing(object o, EveWindowClosingArgs args);

        public event WindowClosing OnClosing;

        protected virtual void RaiseOnClosing(object o, EveWindowClosingArgs args)
        {
            WindowClosing handler = OnClosing;
            if (handler != null) handler(o, args);
        }

        private void OnClosedUnsubscribe()
        {
            lock (_locker)
            {
                _listOfWindows.Remove(this);
                if (!_listOfWindows.Any())
                {
                    _isOpen = false;

                }

                ThisPopup.Opened -= ThisPopupOnOpened;
                ThisPopup.Closed -= ThisPopupOnClosed;
            }
        }

        private void TryAddPopupOnParentPage()
        {
            if (AttachToParentPage)
            {
                if (_alreadyAdded) return;

                //return;

                var currentPage = PageHelper.GetCurrentPage();

                var pageGrid = currentPage.Content as Grid;

                if (pageGrid != null)
                {
                    pageGrid.Children.Add(ThisPopup);
                    _alreadyAdded = true;
                }
            }
        }
    }

    public enum EWindowCloseResult
    {
        None,
        ByUserAction,
        AutoOrUserCancel
    }

    public class EveWindowClosingArgs : EventArgs
    {
        public bool Cancel { get; set; }
    }
}


text:
require 'spec_helper'

describe Fuzzytime do

  it "should display midnight correctly" do
    t = Time.local(2012,1,1,0,0)
    Fuzzytime.fuzzy_time(t).should include "midnight"
  end

  it "should display noon correctly" do
    t = Time.local(2012,1,1,12,0)
    Fuzzytime.fuzzy_time(t).should include "noon"
  end

  it "should display 5 past correctly" do
    t = Time.local(2012,1,1,2,5)
    Fuzzytime.fuzzy_time(t).should include "5 past"
  end

  it "should display 10 past correctly" do
    t = Time.local(2012,1,1,12,10)
    Fuzzytime.fuzzy_time(t).should include "10 past"
  end

  it "should display 15 past correctly" do
    t = Time.local(2012,1,1,12,15)
    Fuzzytime.fuzzy_time(t).should include "quarter"
    Fuzzytime.fuzzy_time(t).should include "past"
  end

  it "should display 20 past correctly" do
    t = Time.local(2012,1,1,2,20)
    Fuzzytime.fuzzy_time(t).should include "20 past"
  end

  it "should display 25 past correctly" do
    t = Time.local(2012,1,1,2,25)
    Fuzzytime.fuzzy_time(t).should include "25 past"
  end

  it "should display 30 past correctly" do
    t = Time.local(2012,1,1,2,30)
    Fuzzytime.fuzzy_time(t).should include("half past")
  end

  it "should display 35 past correctly" do
    t = Time.local(2012,1,1,2,35)
    Fuzzytime.fuzzy_time(t).should include("25")
    Fuzzytime.fuzzy_time(t).should include("til")
  end

  it "should display 40 past correctly" do
    t = Time.local(2012,1,1,1,40)
    Fuzzytime.fuzzy_time(t).should include("20")
    Fuzzytime.fuzzy_time(t).should include("til")
  end

  it "should display 45 past correctly" do
    t = Time.local(2012,1,1,1,45)
    Fuzzytime.fuzzy_time(t).should include("quarter")
    Fuzzytime.fuzzy_time(t).should include("til")
  end

  it "should display 50 past correctly" do
    t = Time.local(2012,1,1,1,50)
    Fuzzytime.fuzzy_time(t).should include("10")
    Fuzzytime.fuzzy_time(t).should include("til")
  end

  it "should display 55 past correctly" do
    t = Time.local(2012,1,1,1,55)
    Fuzzytime.fuzzy_time(t).should include("5")
    Fuzzytime.fuzzy_time(t).should include("til")
  end

  it "should read 10PM correctly" do
    t = Time.local(2012,1,1,22,00)
    Fuzzytime.fuzzy_time(t).should == "10 o'clock"
  end

  it "should display 11:45am correctly" do
    t = Time.local(2012,1,1,11,45)
    Fuzzytime.fuzzy_time(t).should == "quarter til noon"
  end

  it "should display 11:45pm correctly" do
    t = Time.local(2012,1,1,23,45)
    Fuzzytime.fuzzy_time(t).should == "quarter til midnight"
  end

  it "should display 12:15am correctly" do
    t1 = Time.local(2012,1,1,0,15)
    Fuzzytime.fuzzy_time(t1).should == "quarter past midnight"
  end

  it "should display 12:15pm correctly" do
    t1 = Time.local(2012,1,1,12,15)
    Fuzzytime.fuzzy_time(t1).should == "quarter past noon"
  end

  it "should display 5:15am and 5:15pm correctly" do
    t1 = Time.local(2012,1,1,5,15)
    t2 = Time.local(2012,1,1,17,15)
    Fuzzytime.fuzzy_time(t1).should == "quarter past 5"
    Fuzzytime.fuzzy_time(t2).should == "quarter past 5"
  end

  it "should display 4:17pm correctly" do
    t1 = Time.local(2012,1,1,16,17)
    Fuzzytime.fuzzy_time(t1).should == "17 past 4"
  end

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta charset="UTF-8"/>
<title>Oryol Samples</title>
<link href='http://fonts.googleapis.com/css?family=Racing+Sans+One' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="style.css"/>
<link rel="icon" type="image/png" href="favicon.png"/>

ORYOL 2000©

readme

github

twitter

blog

more

    ${samples}


text:
package com.github.jochenw.afw.core.inject;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import com.github.jochenw.afw.di.api.IOnTheFlyBinder;

/** This annotation can be used to request the injection of loggers.
 * The request is satisfied by using an {@link IOnTheFlyBinder}.
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface LogInject {
	/** Returns the loggers id. Defaults to the fully qualified name of the
	 * class, which declares the loggers field.
	 * @return The loggers id. Defaults to the fully qualified name of the
	 * class, which declares the loggers field.
	 */
	String id() default "";
	/** If an {@link com.github.jochenw.afw.core.log.IMLog} is being injected: Declares the method name.
	 * Otherwise, this is being ignored.
	 * @return The method name, if an {@link com.github.jochenw.afw.core.log.IMLog}
	 *   is being injected. Otherwise, this is being ignored.
	 */
	String mName() default "";
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#D1EEEE</color>
    <color name="colorPrimaryDark">#BFEFFF</color>
    <color name="colorAccent">#CAE1FF</color>
</resources>


text:
<!--
  ~ JBoss, Home of Professional Open Source.
  ~ Copyright 2010, Red Hat, Inc., and individual contributors
  ~ as indicated by the @author tags. See the copyright.txt file in the
  ~ distribution for a full listing of individual contributors.
  ~
  ~ This is free software; you can redistribute it and/or modify it
  ~ under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  ~
  ~ This software is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  ~ Lesser General Public License for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public
  ~ License along with this software; if not, write to the Free
  ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  -->

<project name="module-repository-lib">

    <property name="src.dir" value="src"/>
    <property name="module.repo.src.dir" value="${src.dir}/main/resources/modules"/>
    <property name="output.dir" value="target"/>
    <property name="module.repo.output.dir" value="${output.dir}/modules"/>
    <property name="module.xml" value="module.xml"/>

    <taskdef name="jandex" classname="org.jboss.jandex.JandexAntTask" />

    <macrodef name="module-def">
        <attribute name="name"/>
        <attribute name="slot" default="main"/>
        <element name="resources" implicit="yes" optional="yes"/>

        <sequential>
            <echo message="Initializing module -> @{name}"/>
            <!-- Figure out the correct module path -->
            <define-module-dir name="@{name}" slot="@{slot}"/>

            <!-- Make the module output director -->
            <mkdir dir="${module.repo.output.dir}/${current.module.path}"/>

            <!-- Copy the module.xml and other stuff to the output director -->
            <copy todir="${module.repo.output.dir}/${current.module.path}">
                <fileset dir="${module.repo.src.dir}/${current.module.path}">
                    <include name="**"/>
                </fileset>
            </copy>

            <!-- Process the resource -->
            <resources/>

            <!-- Some final cleanup -->
            <replace file="${module.repo.output.dir}/${current.module.path}/${module.xml}">
                <replacetoken>
                    <![CDATA[
        <!-- Insert resources here -->]]></replacetoken>
                <replacevalue>
                </replacevalue>
            </replace>

        </sequential>
    </macrodef>

    <scriptdef name="define-module-dir" language="javascript">
        <attribute name="name"/>
        <attribute name="slot"/>
        <![CDATA[
            name = attributes.get("name");
            name = name.replaceAll("\\.", "/");
            project.setProperty("current.module.path", name + "/" + attributes.get("slot"));
        ]]>
    </scriptdef>

    <macrodef name="maven-resource" >
        <attribute name="group"/>
        <attribute name="artifact"/>
        <attribute name="jandex" default="false" />

        <sequential>
            <!-- Copy the jar to the module dir -->
            <copy todir="${module.repo.output.dir}/${current.module.path}" failonerror="true">
                <fileset file="${@{group}:@{artifact}:jar}"/>
                <mapper type="flatten" />
            </copy>

            <basename file="${@{group}:@{artifact}:jar}" property="resourcename.@{group}.@{artifact}"/>
            <!-- Generate the Jandex Index -->
            <jandex run="@{jandex}" newJar="true" >
                <fileset dir="${module.repo.output.dir}/${current.module.path}" />
            </jandex>
            <!-- Update the resource entry in module.xml -->
            <define-resource-root path="${resourcename.@{group}.@{artifact}}" jandex="@{jandex}"/>
            <replace file="${module.repo.output.dir}/${current.module.path}/${module.xml}">
                <replacefilter token="<!-- Insert resources here -->" value="${current.resource.root}
        <!-- Insert resources here -->"/>
            </replace>
        </sequential>
    </macrodef>

    <macrodef name="maven-resource-with-classifier" >
        <attribute name="group"/>
        <attribute name="artifact"/>
        <attribute name="classifier"/>
        <attribute name="jandex" default="false" />

        <sequential>
            <!-- Copy the jar to the module dir -->
            <copy todir="${module.repo.output.dir}/${current.module.path}" failonerror="true">
                <fileset file="${@{group}:@{artifact}:jar:@{classifier}}"/>
                <!-- http://jira.codehaus.org/browse/MANTRUN-159 -->
                <mapper type="flatten" />
            </copy>

            <basename file="${@{group}:@{artifact}:jar:@{classifier}}" property="resourcename.@{group}.@{artifact}.@{classifier}"/>

            <!-- Update the resource entry in module.xml -->
            <define-resource-root path="${resourcename.@{group}.@{artifact}.@{classifier}}"/>
            <replace file="${module.repo.output.dir}/${current.module.path}/${module.xml}">
                <replacefilter token="<!-- Insert resources here -->" value="${current.resource.root}
        <!-- Insert resources here -->"/>
            </replace>
        </sequential>
    </macrodef>

    <scriptdef name="define-resource-root" language="javascript">
        <attribute name="path"/>
        <attribute name="jandex"/>
        <![CDATA[
            path = attributes.get("path");
            root = "<resource-root path=\"" + path + "\"/>";
            if(path.indexOf('${') != -1) {
                throw "Module resource root not found, make sure it is listed in build/pom.xml" + path;
            }
            if(attributes.get("jandex") == "true" ) {
                root = root + "\n\t<resource-root path=\"" + path.replace(".jar","-jandex.jar") + "\"/>";
            }
            project.setProperty("current.resource.root", root);
        ]]>
    </scriptdef>

</project>


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var matkonSchema = new Schema({
	user_id: String,
	title: String,
	ingredients: [{title: String, quantity: Number, measureUnit: String}],
	created_at: {type: Date, default: Date.now},
    proccess: String,
    files: [{path: String, base64Prefix: String}]
});

var Matkon = mongoose.model('Matkon', matkonSchema);


text:
package im.actor.sdk.controllers.conversation.view;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * Created by ex3ndr on 02.04.15.
 */
public class ChatRecyclerView extends RecyclerView {

    private int oldHeight;

    public ChatRecyclerView(Context context) {
        super(context);
    }

    public ChatRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ChatRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        int delta = (b - t) - oldHeight;
        oldHeight = b - t;
        if (delta < 0) {
            scrollBy(0, -delta);
        }
    }
}


text:
// (c) 2014-2015 Don Coleman
//
// 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.

/* global mainPage, deviceList, refreshButton */
/* global detailPage, buttonState, ledButton, disconnectButton */
/* global ble, cordova  */
/* jshint browser: true , devel: true*/
'use strict';

var arrayBufferToInt = function (ab) {
    var a = new Uint8Array(ab);
    return a[0];
};

var rfduino = {
    serviceUUID: "2220",
    receiveCharacteristic: "2221",
    sendCharacteristic: "2222",
    disconnectCharacteristic: "2223"
};

// returns advertising data as hashmap of byte arrays keyed by type
// advertising data is length, type, data
// https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile
function parseAdvertisingData(bytes) {
    var length, type, data, i = 0, advertisementData = {};

    while (length !== 0) {

        length = bytes[i] & 0xFF;
        i++;

        type = bytes[i] & 0xFF;
        i++;

        data = bytes.slice(i, i + length - 1); // length includes type byte, but not length byte
        i += length - 2;  // move to end of data
        i++;

        advertisementData[type] = data;
    }

    return advertisementData;
}

// RFduino advertises the sketch its running in the Manufacturer field 0xFF
// RFduino provides a UART-like service so all sketchs look the same (0x2220)
// This RFduino "service" name is used to different functions on the boards
var getRFduinoService = function(scanRecord) {
    var mfgData;

    if (cordova.platformId === 'ios') {
        mfgData = arrayBufferToIntArray(scanRecord.kCBAdvDataManufacturerData);
    } else { // android
        var ad = parseAdvertisingData(arrayBufferToIntArray(scanRecord));
        mfgData = ad[0xFF];
    }

    if (mfgData) {
      // ignore 1st 2 bytes of mfg data
      return bytesToString(mfgData.slice(2));
    } else {
      return "";
    }
};

// Convert ArrayBuffer to int[] for easier processing.
// If Uint8Array.slice worked, this would be unnecessary
var arrayBufferToIntArray = function(buffer) {
    var result;

    if (buffer) {
        var typedArray = new Uint8Array(buffer);
        result = [];
        for (var i = 0; i < typedArray.length; i++) {
            result[i] = typedArray[i];
        }
    }

    return result;
};

var bytesToString = function (bytes) {
    var bytesAsString = "";
    for (var i = 0; i < bytes.length; i++) {
        bytesAsString += String.fromCharCode(bytes[i]);
    }
    return bytesAsString;
};

var app = {
    initialize: function() {
        this.bindEvents();
        detailPage.hidden = true;
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        refreshButton.addEventListener('touchstart', this.refreshDeviceList, false);
        ledButton.addEventListener('touchstart', this.sendData, false);
        ledButton.addEventListener('touchend', this.sendData, false);
        disconnectButton.addEventListener('touchstart', this.disconnect, false);
        deviceList.addEventListener('touchstart', this.connect, false); // assume not scrolling
    },
    onDeviceReady: function() {
        app.refreshDeviceList();
    },
    refreshDeviceList: function() {
        deviceList.innerHTML = ''; // empties the list
        ble.scan([rfduino.serviceUUID], 5, app.onDiscoverDevice, app.onError);
    },
    onDiscoverDevice: function(device) {
        var listItem = document.createElement('li'),
            html = '' + device.name + '
' +
                'RSSI: ' + device.rssi + ' | ' +
                'Advertising: ' + getRFduinoService(device.advertising) + '
' +
                device.id;

        listItem.dataset.deviceId = device.id;
        listItem.innerHTML = html;
        deviceList.appendChild(listItem);
    },
    connect: function(e) {
        var deviceId = e.target.dataset.deviceId,
            onConnect = function() {
                // subscribe for incoming data
                ble.notify(deviceId, rfduino.serviceUUID, rfduino.receiveCharacteristic, app.onData, app.onError);
                disconnectButton.dataset.deviceId = deviceId;
                ledButton.dataset.deviceId = deviceId;
                app.showDetailPage();
            };

        ble.connect(deviceId, onConnect, app.onError);
    },
    onData: function(data) { // data received from rfduino
        console.log(data);
        var buttonValue = arrayBufferToInt(data);
        if (buttonValue === 1) {
            buttonState.innerHTML = "Button Pressed";
        } else {
            buttonState.innerHTML = "Button Released";
        }
    },
    sendData: function(event) { // send data to rfduino

        var success = function() {
            console.log("success");
        };

        var failure = function() {
            alert("Failed writing data to the rfduino");
        };

        var data = new Uint8Array(1);
        data[0] = event.type === 'touchstart' ? 0x1 : 0x0;
        var deviceId = event.target.dataset.deviceId;

        ble.writeWithoutResponse(deviceId, rfduino.serviceUUID, rfduino.sendCharacteristic, data.buffer, success, failure);

    },
    disconnect: function(event) {
        var deviceId = event.target.dataset.deviceId;
        ble.disconnect(deviceId, app.showMainPage, app.onError);
    },
    showMainPage: function() {
        mainPage.hidden = false;
        detailPage.hidden = true;
    },
    showDetailPage: function() {
        mainPage.hidden = true;
        detailPage.hidden = false;
    },
    onError: function(reason) {
        alert("ERROR: " + reason); // real apps should use notification.alert
    }
};


text:
namespace logging {

Log log;

Log::Log() : current_level_(error) {}

void Log::set(verbosity_level lvl) {
  current_level_ = lvl;

#ifdef USE_LIEF
  if(lvl != info) {
    lief_logging_disable();
  } else {
    lief_logging_enable();
  }
#endif

}

static std::ostream cnull(0);

std::ostream &Log::operator()(verbosity_level lvl) {
  if (lvl > current_level_)
    return cnull;
  else {
    switch(lvl) {
      case error:
        return std::clog << "[ERROR] ";
      case warning:
        return std::clog << "[WARN] ";
      case info:
        return std::clog << "[INFO] ";
    }
  }
}
}


text:
QUnit.test('String.fromCodePoint', assert => {
  const { fromCodePoint } = String;
  assert.isFunction(fromCodePoint);
  assert.arity(fromCodePoint, 1);
  assert.name(fromCodePoint, 'fromCodePoint');
  assert.looksNative(fromCodePoint);
  assert.nonEnumerable(String, 'fromCodePoint');
  assert.same(fromCodePoint(''), '\0');
  assert.same(fromCodePoint(), '');
  assert.same(fromCodePoint(-0), '\0');
  assert.same(fromCodePoint(0), '\0');
  assert.same(fromCodePoint(0x1D306), '\uD834\uDF06');
  assert.same(fromCodePoint(0x1D306, 0x61, 0x1D307), '\uD834\uDF06a\uD834\uDF07');
  assert.same(fromCodePoint(0x61, 0x62, 0x1D307), 'ab\uD834\uDF07');
  assert.same(fromCodePoint(false), '\0');
  assert.same(fromCodePoint(null), '\0');
  assert.throws(() => fromCodePoint('_'), RangeError);
  assert.throws(() => fromCodePoint('+Infinity'), RangeError);
  assert.throws(() => fromCodePoint('-Infinity'), RangeError);
  assert.throws(() => fromCodePoint(-1), RangeError);
  assert.throws(() => fromCodePoint(0x10FFFF + 1), RangeError);
  assert.throws(() => fromCodePoint(3.14), RangeError);
  assert.throws(() => fromCodePoint(3e-2), RangeError);
  assert.throws(() => fromCodePoint(-Infinity), RangeError);
  assert.throws(() => fromCodePoint(Infinity), RangeError);
  assert.throws(() => fromCodePoint(NaN), RangeError);
  assert.throws(() => fromCodePoint(undefined), RangeError);
  assert.throws(() => fromCodePoint({}), RangeError);
  assert.throws(() => fromCodePoint(/./), RangeError);
  let number = 0x60;
  assert.same(fromCodePoint({
    valueOf() {
      return ++number;
    },
  }), 'a');
  assert.same(number, 0x61);
  // one code unit per symbol
  let counter = 2 ** 15 * 3 / 2;
  let result = [];
  while (--counter >= 0) result.push(0);
  // should not throw
  fromCodePoint.apply(null, result);
  counter = 2 ** 15 * 3 / 2;
  result = [];
  while (--counter >= 0) result.push(0xFFFF + 1);
  // should not throw
  fromCodePoint.apply(null, result);
});


text:
package org.apache.flink.connector.file.table;

import org.apache.flink.annotation.Experimental;

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

/** Time extractor to extract time from partition values. */
@Experimental
public interface PartitionTimeExtractor extends Serializable {

    String DEFAULT = "default";
    String CUSTOM = "custom";

    /** Extract time from partition keys and values. */
    LocalDateTime extract(List<String> partitionKeys, List<String> partitionValues);

    static PartitionTimeExtractor create(
            ClassLoader userClassLoader,
            String extractorKind,
            String extractorClass,
            String extractorPattern,
            String formatterPattern) {
        switch (extractorKind) {
            case DEFAULT:
                return new DefaultPartTimeExtractor(extractorPattern, formatterPattern);
            case CUSTOM:
                try {
                    return (PartitionTimeExtractor)
                            userClassLoader.loadClass(extractorClass).newInstance();
                } catch (ClassNotFoundException
                        | IllegalAccessException
                        | InstantiationException e) {
                    throw new RuntimeException(
                            "Can not new instance for custom class from " + extractorClass, e);
                }
            default:
                throw new UnsupportedOperationException(
                        "Unsupported extractor kind: " + extractorKind);
        }
    }
}


text:
class CreateSubscriptionSets < ActiveRecord::Migration
  def change
    create_table :subscription_sets do |t|
      t.integer :user_id, null: false
      t.string :name
      t.timestamps null: false
    end

    create_table :subscription_sets_projects do |t|
      t.belongs_to :subscription_set, index: true
      t.belongs_to :project, index: true
    end
  end
end


text:
frappe.provide("frappe.form.formatters");

frappe.form.link_formatters = {};

frappe.form.formatters = {
	_right: function(value, options) {
		if(options && (options.inline || options.only_value)) {
			return value;
		} else {
			return "
" + value + "
";
		}
	},
	Data: function(value, df) {
		if (df && df.options == "URL") {
			return `<a href="${value}" title="Open Link" target="_blank">${value}</a>`;
		}
		return value==null ? "" : value;
	},
	Autocomplete: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Select: function(value) {
		return __(frappe.form.formatters["Data"](value));
	},
	Float: function(value, docfield, options, doc) {
		// don't allow 0 precision for Floats, hence or'ing with null
		var precision = docfield.precision
			|| cint(frappe.boot.sysdefaults && frappe.boot.sysdefaults.float_precision)
			|| null;
		if (docfield.options && docfield.options.trim()) {
			// options points to a currency field, but expects precision of float!
			docfield.precision = precision;
			return frappe.form.formatters.Currency(value, docfield, options, doc);

		} else {
			// show 1.000000 as 1
			if (!(options || {}).always_show_decimals && !is_null(value)) {
				var temp = cstr(value).split(".");
				if (temp[1]==undefined || cint(temp[1])===0) {
					precision = 0;
				}
			}

			return frappe.form.formatters._right(
				((value==null || value==="")
					? ""
					: format_number(value, null, precision)), options);
		}
	},
	Int: function(value, docfield, options) {
		return frappe.form.formatters._right(value==null ? "" : cint(value), options)
	},
	Percent: function(value, docfield, options) {
		const precision = (
			docfield.precision
			|| cint(
				frappe.boot.sysdefaults
				&& frappe.boot.sysdefaults.float_precision
			)
			|| 2
		);
		return frappe.form.formatters._right(flt(value, precision) + "%", options);
	},
	Rating: function(value, docfield) {
		let rating_html = '';
		let number_of_stars = docfield.options || 5;
		value = value * number_of_stars;
		Array.from({length: cint(number_of_stars)}, (_, i) => i + 1).forEach(i => {
			rating_html += `<svg class="icon icon-md" data-rating=${i} viewBox="0 0 24 24" fill="none">
				<path class="right-half ${i <= (value || 0) ? "star-click": "" }" d="M11.9987 3.00011C12.177 3.00011 12.3554 3.09303 12.4471 3.27888L14.8213 8.09112C14.8941 8.23872 15.0349 8.34102 15.1978 8.3647L20.5069 9.13641C20.917 9.19602 21.0807 9.69992 20.7841 9.9892L16.9421 13.7354C16.8243 13.8503 16.7706 14.0157 16.7984 14.1779L17.7053 19.4674C17.7753 19.8759 17.3466 20.1874 16.9798 19.9945L12.2314 17.4973C12.1586 17.459 12.0786 17.4398 11.9987 17.4398V3.00011Z" fill="var(--star-fill)" stroke="var(--star-fill)"/>
				<path class="left-half ${i <= (value || 0) || (i - 0.5) == value ? "star-click": "" }" d="M11.9987 3.00011C11.8207 3.00011 11.6428 3.09261 11.5509 3.27762L9.15562 8.09836C9.08253 8.24546 8.94185 8.34728 8.77927 8.37075L3.42887 9.14298C3.01771 9.20233 2.85405 9.70811 3.1525 9.99707L7.01978 13.7414C7.13858 13.8564 7.19283 14.0228 7.16469 14.1857L6.25116 19.4762C6.18071 19.8842 6.6083 20.1961 6.97531 20.0045L11.7672 17.5022C11.8397 17.4643 11.9192 17.4454 11.9987 17.4454V3.00011Z" fill="var(--star-fill)" stroke="var(--star-fill)"/>
			</svg>`;
		});
		return `

			${rating_html}

`;
	},
	Currency: function (value, docfield, options, doc) {
		var currency  = frappe.meta.get_field_currency(docfield, doc);
		var precision = docfield.precision || cint(frappe.boot.sysdefaults.currency_precision) || 2;

		// If you change anything below, it's going to hurt a company in UAE, a bit.
		if (precision > 2) {
			var parts	 = cstr(value).split("."); // should be minimum 2, comes from the DB
			var decimals = parts.length > 1 ? parts[1] : ""; // parts.length == 2 ???

			if ( decimals.length < 3 || decimals.length < precision ) {
				const fraction = frappe.model.get_value(":Currency", currency, "fraction_units") || 100; // if not set, minimum 2.

				if (decimals.length < cstr(fraction).length) {
					precision = cstr(fraction).length - 1;
				}
			}
		}

		value = (value == null || value === "") ? "" : format_currency(value, currency, precision);

		if ( options && options.only_value ) {
			return value;
		} else {
			return frappe.form.formatters._right(value, options);
		}
	},
	Check: function(value) {
		return `<input type="checkbox" disabled
			class="disabled-${value ? "selected" : "deselected"}">`;
	},
	Link: function(value, docfield, options, doc) {
		var doctype = docfield._options || docfield.options;
		var original_value = value;
		let link_title = frappe.utils.get_link_title(doctype, value);

		if(value && value.match && value.match(/^['"].*['"]$/)) {
			value.replace(/^.(.*).$/, "$1");
		}

		if(options && (options.for_print || options.only_value)) {
			return link_title || value;
		}

		if(frappe.form.link_formatters[doctype]) {
			// don't apply formatters in case of composite (parent field of same type)
			if (doc && doctype !== doc.doctype) {
				value = frappe.form.link_formatters[doctype](value, doc, docfield);
			}
		}

		if(!value) {
			return "";
		}
		if(value[0] == "'" && value[value.length -1] == "'") {
			return value.substring(1, value.length - 1);
		}
		if(docfield && docfield.link_onclick) {
			return repl('%(value)s',
				{onclick: docfield.link_onclick.replace(/"/g, '"'), value:value});
		} else if(docfield && doctype) {
			if (frappe.model.can_read(doctype)) {
				return `
					${__(options && options.label || link_title || value)}`;
			} else {
				return link_title || value;
			}
		} else {
			return link_title || value;
		}
	},
	Date: function(value) {
		if (!frappe.datetime.str_to_user) {
			return value;
		}
		if (value) {
			value = frappe.datetime.str_to_user(value);
			// handle invalid date
			if (value==="Invalid date") {
				value = null;
			}
		}

		return value || "";
	},
	DateRange: function(value) {
		if (Array.isArray(value)) {
			return __("{0} to {1}", [frappe.datetime.str_to_user(value[0]), frappe.datetime.str_to_user(value[1])]);
		} else {
			return value || "";
		}
	},
	Datetime: function(value) {
		if(value) {
			return moment(frappe.datetime.convert_to_user_tz(value))
				.format(frappe.boot.sysdefaults.date_format.toUpperCase() + ' ' + frappe.boot.sysdefaults.time_format || 'HH:mm:ss');
		} else {
			return "";
		}
	},
	Text: function(value) {
		if(value) {
			var tags = ["<p", "<div", "<br", "<table"];
			var match = false;

			for(var i=0; i<tags.length; i++) {
				if(value.match(tags[i])) {
					match = true;
					break;
				}
			}

			if(!match) {
				value = frappe.utils.replace_newlines(value);
			}
		}

		return frappe.form.formatters.Data(value);
	},
	Time: function(value) {
		if (value) {
			value = frappe.datetime.str_to_user(value, true);
		}

		return value || "";
	},
	Duration: function(value, docfield) {
		if (value) {
			let duration_options = frappe.utils.get_duration_options(docfield);
			value = frappe.utils.get_formatted_duration(value, duration_options);
		}

		return value || "";
	},
	LikedBy: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= frappe.avatar(v);
		});
		return html;
	},
	Tag: function(value) {
		var html = "";
		$.each((value || "").split(","), function(i, v) {
			if (v) html += `

					${v}
				`;
		});
		return html;
	},
	Comment: function(value) {
		return value;
	},
	Assign: function(value) {
		var html = "";
		$.each(JSON.parse(value || "[]"), function(i, v) {
			if(v) html+= ''+v+'';
		});
		return html;
	},
	SmallText: function(value) {
		return frappe.form.formatters.Text(value);
	},
	TextEditor: function(value) {
		let formatted_value = frappe.form.formatters.Text(value);
		// to use ql-editor styles
		try {
			if (!$(formatted_value).find('.ql-editor').length) {
				formatted_value = `<div class="ql-editor read-mode">${formatted_value}</div>`;
			}
		} catch(e) {
			formatted_value = `<div class="ql-editor read-mode">${formatted_value}</div>`;
		}

		return formatted_value;
	},
	Code: function(value) {
		return "
" + (value==null ? "" : $("
").text(value).html()) + "
"
	},
	WorkflowState: function(value) {
		var workflow_state = frappe.get_doc("Workflow State", value);
		if(workflow_state) {
			return repl("\
				 %(value)s", {
					value: value,
					style: workflow_state.style.toLowerCase(),
					icon: workflow_state.icon
				});
		} else {
			return "" + value + "";
		}
	},
	Email: function(value) {
		return $("

").text(value).html();
	},
	FileSize: function(value) {
		if(value > 1048576) {
			value = flt(flt(value) / 1048576, 1) + "M";
		} else if (value > 1024) {
			value = flt(flt(value) / 1024, 1) + "K";
		}
		return value;
	},
	TableMultiSelect: function(rows, df, options) {
		rows = rows || [];
		const meta = frappe.get_meta(df.options);
		const link_field = meta.fields.find(df => df.fieldtype === 'Link');
		const formatted_values = rows.map(row => {
			const value = row[link_field.fieldname];
			return frappe.format(value, link_field, options, row);
		});
		return formatted_values.join(', ');
	},
	Color: (value) => {
		return value ? `

			${value}

` : '';
	},
	Icon: (value) => {
		return value ? `

${frappe.utils.icon(value, "md")}

			${value}

` : '';
	}
};

frappe.form.get_formatter = function(fieldtype) {
	if(!fieldtype)
		fieldtype = "Data";
	return frappe.form.formatters[fieldtype.replace(/ /g, "")] || frappe.form.formatters.Data;
}

frappe.format = function(value, df, options, doc) {
	if(!df) df = {"fieldtype":"Data"};
	if (df.fieldname == '_user_tags') df.fieldtype = 'Tag';
	var fieldtype = df.fieldtype || "Data";

	// format Dynamic Link as a Link
	if(fieldtype==="Dynamic Link") {
		fieldtype = "Link";
		df._options = doc ? doc[df.options] : null;
	}

	var formatter = df.formatter || frappe.form.get_formatter(fieldtype);

	var formatted = formatter(value, df, options, doc);

	if (typeof formatted == "string")
		formatted = frappe.dom.remove_script_and_style(formatted);

	return formatted;
};

frappe.get_format_helper = function(doc) {
	var helper = {
		get_formatted: function(fieldname) {
			var df = frappe.meta.get_docfield(doc.doctype, fieldname);
			if(!df) { console.log("fieldname not found: " + fieldname); }
			return frappe.format(doc[fieldname], df, {inline:1}, doc);
		}
	};
	$.extend(helper, doc);
	return helper;
};

frappe.form.link_formatters['User'] = function(value, doc, docfield) {
	let full_name = doc && (doc.full_name || (docfield && doc[`${docfield.fieldname}_full_name`]));
	return full_name || value;
};


text:
<?php
// Copyright 2014 OCLC
//
// 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.

/**
 *
 * @author Karen Coombs
 *
 * This takes three options:
 * type - the type of mocks to create. Valid values are all, bibFind, bibSearch, database, offers, viaf, authority
 * environment - what environment to generates mocks from. The default is from the production environment
 * filter - the specific mock to filter the create to.
 *
 * Example usage
 * php getMock.php --type all
 * php getMock.php --type bibSearch --filter="bibSearchSortDate"
 */
namespace WorldCat\Discovery;

use Guzzle\Http\StaticClient;
use Symfony\Component\Yaml\Yaml;
use OCLC\Auth\WSKey;
use OCLC\Auth\AccessToken;
use WorldCat\Discovery\Bib;
use WorldCat\Discovery\Offer;
use WorldCat\Discovery\Person;
use WorldCat\Discovery\Organization;
use WorldCat\Discovery\Place;

global $environment, $mockFolder, $retrievedToken, $mockValue;

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

$shortopts  = "";
$shortopts .= "t:";
$shortopts .= "e::";
$shortopts .= "f::";

$longopts  = array(
    "type:",
    "environment::",
    "filter::"
);

$scriptOptions = getopt($shortopts, $longopts);

if (!class_exists('Guzzle')) {
    \Guzzle\Http\StaticClient::mount();
}

\VCR\VCR::turnOn();

$type = $scriptOptions['type'];

if ($type == 'all' && isset($scriptOptions['filter'])){
    Throw new \Exception('You must specific a type other than all in order to filter. Valid types are bibFind, bibSearch, database, offers, viaf, authority.');
}
$filter = isset($scriptOptions['filter']) ? $scriptOptions['filter'] : null ;

if (isset($scriptOptions['environment'])){
    $cassettePath = 'mocks/' . $scriptOptions['environment'];
} else {
    $cassettePath = 'mocks';
}
\VCR\VCR::configure()->setCassettePath($cassettePath);

\VCR\VCR::insertCassette('accessToken');

$mockFolder = __DIR__ . "/mocks/";

// load the YAML for mocks
$mockBuilder = Yaml::parse(__DIR__ . '/mockBuilder.yml');

    // load the YAML for config
    $config = Yaml::parse(__DIR__ . '/config.yml');
    if (empty($config['institution'])) {
    	Throw new \Exception('No valid config file present');
    }
    if (isset($scriptOptions['environment'])){
        $mockFolder .= $scriptOptions['environment'] . '/';
        $environment = $scriptOptions['environment'];
        AccessToken::$authorizationServer = $config[$environment]['authorizationServiceUrl'];
        WSKey::$testServer = TRUE;
        Bib::$serviceUrl = $config[$environment]['discoveryUrl'];
        Bib::$testServer = TRUE;
        Database::$serviceUrl = $config[$environment]['discoveryUrl'];
        Database::$testServer = TRUE;
        Offer::$serviceUrl = $config[$environment]['discoveryUrl'];
        Offer::$testServer = TRUE;
        Person::$viafServiceUrl = $config[$environment]['viafUrl'];
        Organization::$viafServiceUrl = $config[$environment]['viafUrl'];
        Place::$viafServiceUrl = $config[$environment]['viafUrl'];
    } else {
        $environment = 'prod';
    }

// Go get an accessToken
$options =  array(
    'services' => array('WorldCatDiscoveryAPI')
);
$wskey = new WSKey($config[$environment]['wskey'], $config[$environment]['secret'], $options);

$retrievedToken = $wskey->getAccessTokenWithClientCredentials($config['institution'], $config['institution']);
\VCR\VCR::eject();

if ($type == 'all'  || $type == 'bibFind'){

    if (isset($filter)){
        createMock($filter, $mockBuilder['bibFind'][$filter]);
    } else{
        //BibFind mocks
        foreach ($mockBuilder['bibFind'] as $mock => $mockValues) {
            createMock($mock, $mockValues);
        }
    }
}

if ($type == 'all'  || $type == 'bibSearch'){
    if (isset($filter)){
        createMock($filter, $mockBuilder['bibSearch'][$filter]);
    } else{
        //bibSearch mocks
        foreach ($mockBuilder['bibSearch'] as $mock => $mockValues) {
            createMock($mock, $mockValues);
        }
    }
}

if ($type == 'all'  || $type == 'database'){
    if (isset($filter)){
        if ($filter == 'databaseListSuccess') {
            createMock($filter);
        } else {
            createMock($filter, $mockBuilder['databaseFind'][$filter]);
        }
    } else{
        //database mocks
        foreach ($mockBuilder['databaseFind'] as $mock => $mockValues) {
            createMock($mock, $mockValues);
        }
        $mock = 'databaseListSuccess';
        createMock($mock);
    }
}

if ($type == 'all'  || $type == 'offers'){

    if (isset($filter)){
        createMock($filter, $mockBuilder['offers'][$filter]);
    } else {
        //offer mocks
        foreach ($mockBuilder['offers'] as $mock => $mockValues) {
            createMock($mock, $mockValues);
        }
    }
}

if ($type == 'all'  || $type == 'viaf'){
    if (isset($filter)){
        createMock($filter, $mockBuilder['viaf'][$filter]);
    } else {
        foreach ($mockBuilder['viaf'] as $mock => $mockValues) {
            createMock($mock, $mockValues);
        }
    }
}

if ($type == 'all'  || $type == 'authority'){
    if (file_exists($mockFolder . 'authoritySuccess')){
        unlink($mockFolder . 'authoritySuccess');
    }
    foreach ($mockBuilder['authority'] as $mock => $mockValue) {
        createMock($mock, $mockValue, true);
    }
}

// delete the accessToken file
unlink($mockFolder . 'accessToken');

function createMock($mock, $mockValues = null, $authority = FALSE){
    global $environment, $mockFolder, $retrievedToken, $mockValue;

    if (file_exists($mockFolder . $mock)){
        unlink($mockFolder . $mock);
    }
    if ($authority == true){
        $mockFile = 'authoritySuccess';
    } else {
        $mockFile = $mock;
    }
    \VCR\VCR::insertCassette($mockFile);
    printf("Mock created for '%s'.\n", $mock);
    if (isset($mockValues['accessToken'])){
        $accessToken = new AccessToken('client_credentials', array('accessTokenString' => $mockValues['accessToken'], 'expiresAt' => '2018-08-30 18:25:29Z'));
    } else {
        $accessToken = $retrievedToken;
    }

    // call the appropriate function
    if (isset($mockValues['oclcNumber'])){
        $results = Bib::find($mockValues['oclcNumber'], $accessToken);
    } elseif (isset($mockValues['query'])) {
        $options = array();
        if (isset($mockValues['facetFields'])){
            $options['facetFields'] = $mockValues['facetFields'];
        }

        if (isset($mockValues['facetQueries'])){
            $options['facetQueries'] = $mockValues['facetQueries'];
        }

        if (isset($mockValues['startIndex'])) {
            $options['startIndex'] = $mockValues['startIndex'];
        }

        if (isset($mockValues['itemsPerPage'])) {
            $options['itemsPerPage'] = $mockValues['itemsPerPage'];
        }

        if (isset($mockValues['dbIds'])) {
            $options['dbIds'] = $mockValues['dbIds'];
        }

        if (isset($mockValues['sortBy'])){
            $options['sortBy'] = $mockValues['sortBy'];
        }
        $results = Bib::search($mockValues['query'], $accessToken, $options);
    }elseif ($mock == 'databaseSuccess'){
        Database::find($mockValues['id'], $accessToken);
    }elseif ($mock == 'databaseListSuccess'){
        Database::getList($accessToken);
    }elseif (isset($mockValues['id'])){
        $options = $mockValues['options'];
        $results = Offer::findByOclcNumber($mockValues['id'], $accessToken, $options);
    } elseif (strpos($mock, 'VIAF')) {
        $response = Thing::findByURI($mockValues[$environment]);
        file_put_contents($mockFolder . $mock, str_replace('/rdf.xml', '', file_get_contents($mockFolder . $mock)));
        if ($environment != 'prod'){
            file_put_contents($mockFolder . $mock, str_replace('http://viaf.org', 'http://test.viaf.org', file_get_contents($mockFolder . $mock)));
        }
        file_put_contents($mockFolder . $mock, str_replace('rdap02pxdu.dev.oclc.org:8080', 'test.viaf.org', file_get_contents($mockFolder . $mock)));
    } else {
        $options = [
            'Accept' => 'text/turtle'
        ];
        $authority = Authority::findByURI($mockValue, $options);
        file_put_contents($mockFolder . $mockFile, str_replace($mockValue, rtrim($mockValue, '.nt'), file_get_contents($mockFolder . $mockFile)));
    }
    \VCR\VCR::eject();
    file_put_contents($mockFolder . $mockFile, str_replace("Bearer " . $accessToken->getValue(), "Bearer tk_12345", file_get_contents($mockFolder . $mockFile)));
}

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:tools="http://schemas.android.com/tools"
                    android:initialKeyguardLayout="@layout/widget_recent_notes"
                    android:initialLayout="@layout/widget_recent_notes"
                    android:minHeight="@dimen/widget_recent_notes_default_height"
                    android:minResizeHeight="@dimen/widget_recent_notes_min_resize_height"
                    android:minResizeWidth="@dimen/widget_recent_notes_min_resize_width"
                    android:minWidth="@dimen/widget_recent_notes_default_width"
                    android:previewImage="@drawable/widget_preview_resent_notes"
                    android:resizeMode="horizontal|vertical"
                    android:updatePeriodMillis="0"
                    android:widgetCategory="home_screen|keyguard"
                    />


text:
package com.thomas.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * Created by Yougeshwar on 08/03/2017.
 */
public class JsonEnumSerializer<T extends Enum<T>> extends JsonSerializer<T>
{
    @Override
    public void serialize(T value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException
    {
        gen.writeNumber(value.ordinal());
    }
}


text:
import json
import uuid

from tests.functional.transport.pecan import base

class ErrorHookTest(base.FunctionalTest):

    def setUp(self):
        super(ErrorHookTest, self).setUp()

        self.headers = {'X-Auth-Token': str(uuid.uuid4())}

    def test_404_error(self):
        self.headers['X-Project-Id'] = '000001'
        # use try except to actually catch the response body in
        # exception part
        service_id = str(uuid.uuid4())
        response = self.app.get(
            '/v1.0/services/' + service_id,
            headers=self.headers,
            status=404)

        self.assertEqual(404, response.status_code)
        self.assertEqual('application/json', response.content_type)
        response_json = json.loads(response.body.decode('utf-8'))
        self.assertTrue('message' in response_json)
        self.assertEqual('service {0} could not be found'.format(service_id),
                         response_json['message'])


text:
namespace NUnit.ConsoleRunner
{
	using System;
    using System.Collections;
	using System.Collections.Specialized;
	using System.IO;
	using System.Reflection;
	using System.Xml;
	using System.Resources;
	using System.Text;
	using System.Text.RegularExpressions;
	using System.Diagnostics;
	using System.Runtime.InteropServices;
	using NUnit.Core;
	using NUnit.Core.Filters;
	using NUnit.Util;

	/// <summary>
	/// Summary description for ConsoleUi.
	/// </summary>
	public class ConsoleUi
	{
		[STAThread]
		public static int Main(string[] args)
		{
			ConsoleOptions options = new ConsoleOptions(args);

			if(!options.nologo)
				WriteCopyright();

			if(options.help)
			{
				options.Help();
				return 0;
			}

			if(options.NoArgs)
			{
				Console.Error.WriteLine("fatal error: no inputs specified");
				options.Help();
				return 0;
			}

			if(!options.Validate())
			{
				Console.Error.WriteLine("fatal error: invalid arguments");
				options.Help();
				return 2;
			}

			// Add Standard Services to ServiceManager
			ServiceManager.Services.AddService( new SettingsService() );
			ServiceManager.Services.AddService( new DomainManager() );
			//ServiceManager.Services.AddService( new RecentFilesService() );
			//ServiceManager.Services.AddService( new TestLoader() );
			ServiceManager.Services.AddService( new AddinRegistry() );
			ServiceManager.Services.AddService( new AddinManager() );

			// Initialize Services
			ServiceManager.Services.InitializeServices();

			try
			{
				ConsoleUi consoleUi = new ConsoleUi();
				return consoleUi.Execute( options );
			}
			catch( FileNotFoundException ex )
			{
				Console.WriteLine( ex.Message );
				return 2;
			}
			catch( BadImageFormatException ex )
			{
				Console.WriteLine( ex.Message );
				return 2;
			}
			catch( Exception ex )
			{
				Console.WriteLine( "Unhandled Exception:\n{0}", ex.ToString() );
				return 2;
			}
			finally
			{
				if(options.wait)
				{
					Console.Out.WriteLine("\nHit <enter> key to continue");
					Console.ReadLine();
				}
			}
		}

		private static XmlTextReader GetTransformReader(ConsoleOptions parser)
		{
			XmlTextReader reader = null;
			if(!parser.IsTransform)
			{
				Assembly assembly = Assembly.GetAssembly(typeof(XmlResultVisitor));
				ResourceManager resourceManager = new ResourceManager("NUnit.Util.Transform",assembly);
				string xmlData = (string)resourceManager.GetObject("Summary.xslt");

				reader = new XmlTextReader(new StringReader(xmlData));
			}
			else
			{
				FileInfo xsltInfo = new FileInfo(parser.transform);
				if(!xsltInfo.Exists)
				{
					Console.Error.WriteLine("Transform file: {0} does not exist", xsltInfo.FullName);
					reader = null;
				}
				else
				{
					reader = new XmlTextReader(xsltInfo.FullName);
				}
			}

			return reader;
		}

		private static void WriteCopyright()
		{
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			System.Version version = executingAssembly.GetName().Version;

			object[] objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);
			AssemblyProductAttribute productAttr = (AssemblyProductAttribute)objectAttrs[0];

			objectAttrs = executingAssembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
			AssemblyCopyrightAttribute copyrightAttr = (AssemblyCopyrightAttribute)objectAttrs[0];

			Console.WriteLine(String.Format("{0} version {1}", productAttr.Product, version.ToString(3)));
			Console.WriteLine(copyrightAttr.Copyright);
			Console.WriteLine();

			Console.WriteLine( "Runtime Environment - " );
			RuntimeFramework framework = RuntimeFramework.CurrentFramework;
			Console.WriteLine( string.Format("   OS Version: {0}", Environment.OSVersion ) );
			Console.WriteLine( string.Format("  CLR Version: {0} ( {1} )",
				Environment.Version,  framework.GetDisplayName() ) );

			Console.WriteLine();
		}

		private static TestRunner MakeRunnerFromCommandLine( ConsoleOptions options )
		{
			ConsoleOptions.DomainUsage domainUsage = options.domain;
			if ( domainUsage == ConsoleOptions.DomainUsage.Default )
				domainUsage = options.ParameterCount == 1
					? ConsoleOptions.DomainUsage.Single
					: ConsoleOptions.DomainUsage.Multiple;

            TestRunner testRunner = null;

			switch( domainUsage )
			{
				case ConsoleOptions.DomainUsage.None:
					testRunner = new NUnit.Core.RemoteTestRunner();
					// Make sure that addins are available
					CoreExtensions.Host.AddinRegistry = Services.AddinRegistry;
					break;

				case ConsoleOptions.DomainUsage.Single:
					testRunner = new TestDomain();
					break;

				case ConsoleOptions.DomainUsage.Multiple:
					testRunner = new MultipleTestDomainRunner();
					break;
			}

			TestPackage package;
			if ( options.IsTestProject )
			{
				NUnitProject project = NUnitProject.LoadProject( (string)options.Parameters[0] );
				string configName = options.config;
				if ( configName != null )
					project.SetActiveConfig( configName );

				package = project.MakeTestPackage();
				if ( options.IsFixture )
					package.TestName = options.fixture;
			}
			else if ( options.Parameters.Count == 1 )
			{
				package = new TestPackage( (string)options.Parameters[0] );
			}
			else
			{
				package = new TestPackage( "UNNAMED", options.Parameters );
			}

			if ( options.IsFixture )
				package.TestName = options.fixture;
			package.Settings["ShadowCopyFiles"] = !options.noshadow;
			package.Settings["UseThreadedRunner"] = !options.nothread;
			testRunner.Load( package );

			return testRunner;
		}

		public ConsoleUi()
		{
		}

		public int Execute( ConsoleOptions options )
		{
			XmlTextReader transformReader = GetTransformReader(options);
			if(transformReader == null) return 3;

			TextWriter outWriter = Console.Out;
			if ( options.isOut )
			{
				StreamWriter outStreamWriter = new StreamWriter( options.output );
				outStreamWriter.AutoFlush = true;
				outWriter = outStreamWriter;
			}

			TextWriter errorWriter = Console.Error;
			if ( options.isErr )
			{
				StreamWriter errorStreamWriter = new StreamWriter( options.err );
				errorStreamWriter.AutoFlush = true;
				errorWriter = errorStreamWriter;
			}

			TestRunner testRunner = MakeRunnerFromCommandLine( options );

			try
			{
				if (testRunner.Test == null)
				{
					testRunner.Unload();
					Console.Error.WriteLine("Unable to locate fixture {0}", options.fixture);
					return 2;
				}

				EventCollector collector = new EventCollector( options, outWriter, errorWriter );

				TestFilter catFilter = TestFilter.Empty;

				if (options.HasInclude)
				{
					Console.WriteLine( "Included categories: " + options.include );
					catFilter = new CategoryFilter( options.IncludedCategories );
				}

				if ( options.HasExclude )
				{
					Console.WriteLine( "Excluded categories: " + options.exclude );
					TestFilter excludeFilter = new NotFilter( new CategoryFilter( options.ExcludedCategories ) );
					if ( catFilter.IsEmpty )
						catFilter = excludeFilter;
					else
						catFilter = new AndFilter( catFilter, excludeFilter );
				}

				TestResult result = null;
				string savedDirectory = Environment.CurrentDirectory;
				TextWriter savedOut = Console.Out;
				TextWriter savedError = Console.Error;

				try
				{
					result = testRunner.Run( collector, catFilter );
				}
				finally
				{
					outWriter.Flush();
					errorWriter.Flush();

					if ( options.isOut )
						outWriter.Close();
					if ( options.isErr )
						errorWriter.Close();

					Environment.CurrentDirectory = savedDirectory;
					Console.SetOut( savedOut );
					Console.SetError( savedError );
				}

				Console.WriteLine();

				string xmlOutput = CreateXmlOutput( result );

				if (options.xmlConsole)
				{
					Console.WriteLine(xmlOutput);
				}
				else
				{
					try
					{
						//CreateSummaryDocument(xmlOutput, transformReader );
						XmlResultTransform xform = new XmlResultTransform( transformReader );
						xform.Transform( new StringReader( xmlOutput ), Console.Out );
					}
					catch( Exception ex )
					{
						Console.WriteLine( "Error: {0}", ex.Message );
						return 3;
					}
				}

				// Write xml output here
				string xmlResultFile = options.IsXml ? options.xml : "TestResult.xml";

				using ( StreamWriter writer = new StreamWriter( xmlResultFile ) )
				{
					writer.Write(xmlOutput);
				}

				//if ( testRunner != null )
				//    testRunner.Unload();

				if ( collector.HasExceptions )
				{
					collector.WriteExceptions();
					return 2;
				}

				return result.IsFailure ? 1 : 0;
			}
			finally
			{
				testRunner.Unload();
			}
		}

		private string CreateXmlOutput( TestResult result )
		{
			StringBuilder builder = new StringBuilder();
			XmlResultVisitor resultVisitor = new XmlResultVisitor(new StringWriter( builder ), result);
			result.Accept(resultVisitor);
			resultVisitor.Write();

			return builder.ToString();
		}

		#region Nested Class to Handle Events

		private class EventCollector : MarshalByRefObject, EventListener
		{
			private int testRunCount;
			private int testIgnoreCount;
			private int failureCount;
			private int level;

			private ConsoleOptions options;
			private TextWriter outWriter;
			private TextWriter errorWriter;

			StringCollection messages;

			private bool progress = false;
			private string currentTestName;

            private ArrayList unhandledExceptions = new ArrayList();

			public EventCollector( ConsoleOptions options, TextWriter outWriter, TextWriter errorWriter )
			{
				level = 0;
				this.options = options;
				this.outWriter = outWriter;
				this.errorWriter = errorWriter;
				this.currentTestName = string.Empty;
				this.progress = !options.xmlConsole && !options.labels && !options.nodots;

                AppDomain.CurrentDomain.UnhandledException +=
                    new UnhandledExceptionEventHandler(OnUnhandledException);
			}

            public bool HasExceptions
            {
                get { return unhandledExceptions.Count > 0; }
            }

            public void WriteExceptions()
            {
                Console.WriteLine();
                Console.WriteLine("Unhandled exceptions:");
                int index = 1;
                foreach( string msg in unhandledExceptions )
                    Console.WriteLine( "{0}) {1}", index++, msg );
            }

			public void RunStarted(string name, int testCount)
			{
			}

			public void RunFinished(TestResult result)
			{
			}

			public void RunFinished(Exception exception)
			{
			}

			public void TestFinished(TestCaseResult testResult)
			{
				if(testResult.Executed)
				{
					testRunCount++;

					if(testResult.IsFailure)
					{
						failureCount++;

						if ( progress )
							Console.Write("F");

						messages.Add( string.Format( "{0}) {1} :", failureCount, testResult.Test.TestName.FullName ) );
						messages.Add( testResult.Message.Trim( Environment.NewLine.ToCharArray() ) );

						string stackTrace = StackTraceFilter.Filter( testResult.StackTrace );
						if ( stackTrace != null && stackTrace != string.Empty )
						{
							string[] trace = stackTrace.Split( System.Environment.NewLine.ToCharArray() );
							foreach( string s in trace )
							{
								if ( s != string.Empty )
								{
									string link = Regex.Replace( s.Trim(), @".* in (.*):line (.*)", "$1($2)");
									messages.Add( string.Format( "at\n{0}", link ) );
								}
							}
						}
					}
				}
				else
				{
					testIgnoreCount++;

					if ( progress )
						Console.Write("N");
				}

				currentTestName = string.Empty;
			}

			public void TestStarted(TestName testName)
			{
				currentTestName = testName.FullName;

				if ( options.labels )
					outWriter.WriteLine("***** {0}", currentTestName );

				if ( progress )
					Console.Write(".");
			}

			public void SuiteStarted(TestName testName)
			{
				if ( level++ == 0 )
				{
					messages = new StringCollection();
					testRunCount = 0;
					testIgnoreCount = 0;
					failureCount = 0;
					Trace.WriteLine( "################################ UNIT TESTS ################################" );
					Trace.WriteLine( "Running tests in '" + testName.FullName + "'..." );
				}
			}

			public void SuiteFinished(TestSuiteResult suiteResult)
			{
				if ( --level == 0)
				{
					Trace.WriteLine( "############################################################################" );

					if (messages.Count == 0)
					{
						Trace.WriteLine( "##############                 S U C C E S S               #################" );
					}
					else
					{
						Trace.WriteLine( "##############                F A I L U R E S              #################" );

						foreach ( string s in messages )
						{
							Trace.WriteLine(s);
						}
					}

					Trace.WriteLine( "############################################################################" );
					Trace.WriteLine( "Executed tests       : " + testRunCount );
					Trace.WriteLine( "Ignored tests        : " + testIgnoreCount );
					Trace.WriteLine( "Failed tests         : " + failureCount );
                    Trace.WriteLine( "Unhandled exceptions : " + unhandledExceptions.Count);
					Trace.WriteLine( "Total time           : " + suiteResult.Time + " seconds" );
					Trace.WriteLine( "############################################################################");
				}
			}

            private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
            {
                if (e.ExceptionObject.GetType() != typeof(System.Threading.ThreadAbortException))
                {
                    this.UnhandledException((Exception)e.ExceptionObject);
                }
            }

			public void UnhandledException( Exception exception )
			{
                // If we do labels, we already have a newline
                unhandledExceptions.Add(currentTestName + " : " + exception.ToString());
                //if (!options.labels) outWriter.WriteLine();
                string msg = string.Format("##### Unhandled Exception while running {0}", currentTestName);
                //outWriter.WriteLine(msg);
                //outWriter.WriteLine(exception.ToString());

                Trace.WriteLine(msg);
                Trace.WriteLine(exception.ToString());
			}

			public void TestOutput( TestOutput output)
			{
				switch ( output.Type )
				{
					case TestOutputType.Out:
						outWriter.Write( output.Text );
						break;
					case TestOutputType.Error:
						errorWriter.Write( output.Text );
						break;
				}
			}

            public override object InitializeLifetimeService()
            {
                return null;
            }
		}

		#endregion
	}
}