text:
"""
    The following operators are understood:

        ~q          Request
        ~s          Response

    Headers:

        Patterns are matched against "name: value" strings. Field names are
        all-lowercase.

        ~a          Asset content-type in response. Asset content types are:
                        text/javascript
                        application/x-javascript
                        application/javascript
                        text/css
                        image/*
                        application/x-shockwave-flash
        ~h rex      Header line in either request or response
        ~hq rex     Header in request
        ~hs rex     Header in response

        ~b rex      Expression in the body of either request or response
        ~bq rex     Expression in the body of request
        ~bq rex     Expression in the body of response
        ~t rex      Shortcut for content-type header.

        ~d rex      Request domain
        ~m rex      Method
        ~u rex      URL
        ~c CODE     Response code.
        rex         Equivalent to ~u rex
"""
from __future__ import absolute_import
import re
import sys
import pyparsing as pp
from .protocol.http import decoded

class _Token:
    def dump(self, indent=0, fp=sys.stdout):
        print >> fp, "\t" * indent, self.__class__.__name__,
        if hasattr(self, "expr"):
            print >> fp, "(%s)" % self.expr,
        print >> fp

class _Action(_Token):
    @classmethod
    def make(klass, s, loc, toks):
        return klass(*toks[1:])

class FErr(_Action):
    code = "e"
    help = "Match error"

    def __call__(self, f):
        return True if f.error else False

class FReq(_Action):
    code = "q"
    help = "Match request with no response"

    def __call__(self, f):
        if not f.response:
            return True

class FResp(_Action):
    code = "s"
    help = "Match response"

    def __call__(self, f):
        return True if f.response else False

class _Rex(_Action):
    def __init__(self, expr):
        self.expr = expr
        try:
            self.re = re.compile(self.expr)
        except:
            raise ValueError("Cannot compile expression.")

def _check_content_type(expr, o):
    val = o.headers["content-type"]
    if val and re.search(expr, val[0]):
        return True
    return False

class FAsset(_Action):
    code = "a"
    help = "Match asset in response: CSS, Javascript, Flash, images."
    ASSET_TYPES = [
        "text/javascript",
        "application/x-javascript",
        "application/javascript",
        "text/css",
        "image/.*",
        "application/x-shockwave-flash"
    ]

    def __call__(self, f):
        if f.response:
            for i in self.ASSET_TYPES:
                if _check_content_type(i, f.response):
                    return True
        return False

class FContentType(_Rex):
    code = "t"
    help = "Content-type header"

    def __call__(self, f):
        if _check_content_type(self.expr, f.request):
            return True
        elif f.response and _check_content_type(self.expr, f.response):
            return True
        return False

class FRequestContentType(_Rex):
    code = "tq"
    help = "Request Content-Type header"

    def __call__(self, f):
        return _check_content_type(self.expr, f.request)

class FResponseContentType(_Rex):
    code = "ts"
    help = "Response Content-Type header"

    def __call__(self, f):
        if f.response:
            return _check_content_type(self.expr, f.response)
        return False

class FHead(_Rex):
    code = "h"
    help = "Header"

    def __call__(self, f):
        if f.request.headers.match_re(self.expr):
            return True
        elif f.response and f.response.headers.match_re(self.expr):
            return True
        return False

class FHeadRequest(_Rex):
    code = "hq"
    help = "Request header"

    def __call__(self, f):
        if f.request.headers.match_re(self.expr):
            return True

class FHeadResponse(_Rex):
    code = "hs"
    help = "Response header"

    def __call__(self, f):
        if f.response and f.response.headers.match_re(self.expr):
            return True

class FBod(_Rex):
    code = "b"
    help = "Body"

    def __call__(self, f):
        if f.request and f.request.content:
            with decoded(f.request):
                if re.search(self.expr, f.request.content):
                    return True
        if f.response and f.response.content:
            with decoded(f.response):
                if re.search(self.expr, f.response.content):
                    return True
        return False

class FBodRequest(_Rex):
    code = "bq"
    help = "Request body"

    def __call__(self, f):
        if f.request and f.request.content:
            with decoded(f.request):
                if re.search(self.expr, f.request.content):
                    return True

class FBodResponse(_Rex):
    code = "bs"
    help = "Response body"

    def __call__(self, f):
        if f.response and f.response.content:
            with decoded(f.response):
                if re.search(self.expr, f.response.content):
                    return True

class FMethod(_Rex):
    code = "m"
    help = "Method"

    def __call__(self, f):
        return bool(re.search(self.expr, f.request.method, re.IGNORECASE))

class FDomain(_Rex):
    code = "d"
    help = "Domain"

    def __call__(self, f):
        return bool(re.search(self.expr, f.request.host, re.IGNORECASE))

class FUrl(_Rex):
    code = "u"
    help = "URL"
    # FUrl is special, because it can be "naked".

    @classmethod
    def make(klass, s, loc, toks):
        if len(toks) > 1:
            toks = toks[1:]
        return klass(*toks)

    def __call__(self, f):
        return re.search(self.expr, f.request.url)

class _Int(_Action):
    def __init__(self, num):
        self.num = int(num)

class FCode(_Int):
    code = "c"
    help = "HTTP response code"

    def __call__(self, f):
        if f.response and f.response.code == self.num:
            return True

class FAnd(_Token):
    def __init__(self, lst):
        self.lst = lst

    def dump(self, indent=0, fp=sys.stdout):
        print >> fp, "\t" * indent, self.__class__.__name__
        for i in self.lst:
            i.dump(indent + 1, fp)

    def __call__(self, f):
        return all(i(f) for i in self.lst)

class FOr(_Token):
    def __init__(self, lst):
        self.lst = lst

    def dump(self, indent=0, fp=sys.stdout):
        print >> fp, "\t" * indent, self.__class__.__name__
        for i in self.lst:
            i.dump(indent + 1, fp)

    def __call__(self, f):
        return any(i(f) for i in self.lst)

class FNot(_Token):
    def __init__(self, itm):
        self.itm = itm[0]

    def dump(self, indent=0, fp=sys.stdout):
        print >> fp, "\t" * indent, self.__class__.__name__
        self.itm.dump(indent + 1, fp)

    def __call__(self, f):
        return not self.itm(f)

filt_unary = [
    FReq,
    FResp,
    FAsset,
    FErr
]
filt_rex = [
    FHeadRequest,
    FHeadResponse,
    FHead,
    FBodRequest,
    FBodResponse,
    FBod,
    FMethod,
    FDomain,
    FUrl,
    FRequestContentType,
    FResponseContentType,
    FContentType,
]
filt_int = [
    FCode
]

def _make():
    # Order is important - multi-char expressions need to come before narrow
    # ones.
    parts = []
    for klass in filt_unary:
        f = pp.Literal("~%s" % klass.code)
        f.setParseAction(klass.make)
        parts.append(f)

    simplerex = "".join(c for c in pp.printables if c not in "()~'\"")
    rex = pp.Word(simplerex) |\
        pp.QuotedString("\"", escChar='\\') |\
        pp.QuotedString("'", escChar='\\')
    for klass in filt_rex:
        f = pp.Literal("~%s" % klass.code) + rex.copy()
        f.setParseAction(klass.make)
        parts.append(f)

    for klass in filt_int:
        f = pp.Literal("~%s" % klass.code) + pp.Word(pp.nums)
        f.setParseAction(klass.make)
        parts.append(f)

    # A naked rex is a URL rex:
    f = rex.copy()
    f.setParseAction(FUrl.make)
    parts.append(f)

    atom = pp.MatchFirst(parts)
    expr = pp.operatorPrecedence(atom,
                                 [(pp.Literal("!").suppress(),
                                   1,
                                   pp.opAssoc.RIGHT,
                                   lambda x: FNot(*x)),
                                     (pp.Literal("&").suppress(),
                                      2,
                                      pp.opAssoc.LEFT,
                                      lambda x: FAnd(*x)),
                                     (pp.Literal("|").suppress(),
                                      2,
                                      pp.opAssoc.LEFT,
                                      lambda x: FOr(*x)),
                                  ])
    expr = pp.OneOrMore(expr)
    return expr.setParseAction(lambda x: FAnd(x) if len(x) != 1 else x)
bnf = _make()

def parse(s):
    try:
        filt = bnf.parseString(s, parseAll=True)[0]
        filt.pattern = s
        return filt
    except pp.ParseException:
        return None
    except ValueError:
        return None

help = []
for i in filt_unary:
    help.append(
        ("~%s" % i.code, i.help)
    )
for i in filt_rex:
    help.append(
        ("~%s regex" % i.code, i.help)
    )
for i in filt_int:
    help.append(
        ("~%s int" % i.code, i.help)
    )
help.sort()
help.extend(
    [
        ("!", "unary not"),
        ("&", "and"),
        ("|", "or"),
        ("(...)", "grouping"),
    ]
)


text:
//
//  ASRViewController.m
//  CallMeIflyTest
//
//  Created by ZengChanghuan on 16/5/27.
//  Copyright © 2016年 ZengChanghuan. All rights reserved.
//

#import "ASRViewController.h"
#import "iflyMSC/iflyMSC.h"
#import "Masonry.h"
#import "UIView+Masonry_LJC.h"
#import "XZTextView.h"
#import "IATConfig.h"
#import "PopupView.h"
#import "ISRDataHelper.h"
#import "HttpManager.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "Calendar.h"
#import "ASRDetailViewController.h"
@interface ASRViewController ()<IFlySpeechRecognizerDelegate,IFlyRecognizerViewDelegate>
{
    //不带界面的识别对象
    IFlySpeechRecognizer *_iFlySpeechRecognizer;
    XZTextView *_textView;
    PopupView *_popUpView;
    IFlyRecognizerView *_iflyRecognizerView;//带界面的识别对象
    UIButton *startBtn;
    UIButton *stopBtn;
    UIButton *cancelBtn;

}
@property (nonatomic, assign) BOOL isCanceled;
@property (nonatomic, copy) NSString *result;
@property (nonatomic, strong) CABasicAnimation *animation;
@property (nonatomic, strong) UIView *animationView;
@end

@implementation ASRViewController

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(self.view.center.x-40, self.view.center.y+200, 80, 80);
    btn.backgroundColor = [UIColor redColor];
    btn.layer.cornerRadius = btn.frame.size.height/2;
    btn.layer.masksToBounds = YES;
    [btn addTarget:self action:@selector(target) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

/*
    UIView *animationView = [UIView new];
    animationView.frame = CGRectMake(0, 0, 100, 100);
    animationView.center = self.view.center;
    animationView.backgroundColor = [UIColor grayColor];
    animationView.layer.cornerRadius = CGRectGetWidth(animationView.frame) * 0.5;
    [self.view addSubview:animationView];

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration = 1.0;
    animation.repeatCount = 9999;
    animation.autoreverses = YES;
    animation.fromValue = @(1.0);
    animation.toValue = @(2.0);

    [animationView.layer addAnimation:animation forKey:@"animationView.scale"];

*/
     /*
    NSString *tmp = @"今天下午两点在金苑大厦会议室开会";
    NSString *stringUrl = [NSString stringWithFormat:@"http://192.168.0.198:8080/cube/nlp/normal?c=%@",tmp];
    stringUrl = [stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSLog(@"stringUrl = %@",stringUrl);
    NSURL *url = [NSURL URLWithString:stringUrl];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    [NSURLConnection sendAsynchronousRequest:req queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//        NSLog(@"jsonString = %@",jsonString);

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        Calendar *calendar = [Calendar mj_objectWithKeyValues:dataDic];
        NSLog(@"content = %@",calendar.content);
        NSLog(@"calendar.year = %@",calendar.year);

        for (Segment *segment in calendar.segments) {
            NSString *nature = segment.nature;
            NSString *word = segment.word;
            NSNumber *offset = segment.offset;
            MJExtensionLog(@"nature=%@, word=%@, offset=%@", nature, word, offset);

        }

    }];

    */
   /*
    [self creartBtn];
    [self createTextView];
    CGFloat posY = _textView.frame.origin.y+_textView.frame.size.height/6;

    _popUpView = [[PopupView alloc] initWithFrame:CGRectMake(100, posY, 0, 0) withParentView:self.view];

     */
}
- (void)target
{
    ASRDetailViewController *detailVC = [ASRDetailViewController new];
    [self.navigationController pushViewController:detailVC animated:YES];
//    [self.navigationController presentViewController:detailVC animated:YES completion:nil];
}
- (void)touchUI{
    //声音小放小倍数,时间长,就会缓
    _animation.duration = arc4random_uniform(100) / 100.0 + 0.1;
    _animation.toValue = @(arc4random_uniform(6) * 1.0 + 2.0);
    [_animationView.layer addAnimation:_animation forKey:@"animationView.scale"];
}
- (void)run
{

}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self initRecognizer];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}
- (void)creartBtn
{
    UIView *controlView = [UIView new];
    controlView.backgroundColor = [UIColor whiteColor];
    [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(10);
        make.size.mas_equalTo(CGSizeMake([UIScreen mainScreen].bounds.size.width-20, 80));
    }];
    [self.view addSubview:controlView];

    startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [startBtn addTarget:self action:@selector(startRecoed) forControlEvents:UIControlEventTouchUpInside];
    [startBtn setTitle:@"开始识别" forState:UIControlStateNormal];
    [controlView addSubview:startBtn];
    startBtn.backgroundColor = [UIColor purpleColor];
    [startBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 50));
        make.top.mas_equalTo(15);
        make.left.mas_equalTo(10);
    }];

    stopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [stopBtn addTarget:self action:@selector(stopRecoed) forControlEvents:UIControlEventTouchUpInside];
    [stopBtn setTitle:@"停止识别" forState:UIControlStateNormal];
    [controlView addSubview:stopBtn];
    stopBtn.backgroundColor = [UIColor purpleColor];
    [stopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 50));
        make.left.mas_equalTo(startBtn.frame.size.width + 100);
        make.top.mas_equalTo(15);

    }];

    cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn addTarget:self action:@selector(cancelRecoed) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.backgroundColor = [UIColor purpleColor];
    [controlView addSubview:cancelBtn];
     [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
         make.size.mas_equalTo(CGSizeMake(80, 50));
         make.top.mas_equalTo(15);
         make.left.mas_equalTo(cancelBtn.frame.origin.x + 190);
     }];

}
- (void)createTextView
{
    _textView = [[XZTextView alloc] init];
    _textView.frame = CGRectMake(20, 100, [UIScreen mainScreen].bounds.size.width-40, 120);

    _textView.backgroundColor = [UIColor grayColor];
    _textView.placeholder = @"准备识别中";

    _textView.placeholderColor = [UIColor purpleColor];
    [self.view addSubview:_textView];

}
#pragma mark -Button Method
- (void)startRecoed
{
    /*
    _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    _iFlySpeechRecognizer.delegate = self;

    //设置听写模式
    [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];

    //asr_audio_path是录音文件名,设置value为nil或者为空取消保存,默认保存目录在 Library/cache下。
    [_iFlySpeechRecognizer setParameter:@"asrview.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];

    //启动识别服务
    [_iFlySpeechRecognizer startListening];

    */
    if ([IATConfig sharedInstance].haveView == NO) {//无界面

        [_textView setText:@""];
        [_textView resignFirstResponder];
        self.isCanceled = NO;

        if(_iFlySpeechRecognizer == nil)
        {
            [self initRecognizer];
        }

        [_iFlySpeechRecognizer cancel];

        //设置音频来源为麦克风
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];

        //设置听写结果格式为json
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];

        //保存录音文件,保存在sdk工作路径中,如未设置工作路径,则默认保存在library/cache下
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];

        [_iFlySpeechRecognizer setDelegate:self];

        BOOL ret = [_iFlySpeechRecognizer startListening];

        if (ret) {
//            [_audioStreamBtn setEnabled:NO];
//            [_upWordListBtn setEnabled:NO];
//            [_upContactBtn setEnabled:NO];
        }else{
            [_popUpView showText: @"启动识别服务失败,请稍后重试"];//可能是上次请求未结束,暂不支持多路并发
        }
    }else {

        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }

        [_textView setText:@""];
        [_textView resignFirstResponder];

        //设置音频来源为麦克风
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];

        //设置听写结果格式为json
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];

        //保存录音文件,保存在sdk工作路径中,如未设置工作路径,则默认保存在library/cache下
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];

        [_iflyRecognizerView start];
    }

}

/**
 *  停止录音
 */
- (void)stopRecoed
{
    [_iFlySpeechRecognizer stopListening];
    [_textView resignFirstResponder];
}

- (void)cancelRecoed
{
    self.isCanceled = YES;
    [_iFlySpeechRecognizer cancel];
    [_popUpView removeFromSuperview];
    [_textView resignFirstResponder];
}
#pragma mark -IFlyRecognizerViewDelegate
/*!
 *  回调返回识别结果
 *
 *  @param resultArray 识别结果,NSArray的第一个元素为NSDictionary,NSDictionary的key为识别结果,sc为识别结果的置信度
 *  @param isLast      -[out] 是否最后一个结果
 */

- (void)onResult:(NSArray *)resultArray isLast:(BOOL) isLast
{

    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];

    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    _textView.text = [NSString stringWithFormat:@"%@ %@",_textView.text, result];
}
#pragma mark -IFlySpeechRecognizerDelegate
/**
 *  识别结果返回代理
 *
 *  @param results 识别结果
 *  @param isLast  表示是否最后一次结果
 */
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSLog(@"%s[IN]",__func__);

    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }

    _result = [NSString stringWithFormat:@"%@%@",_textView.text,resultString];
    NSString *resultFromJson = [ISRDataHelper stringFromJson:resultString];
    _textView.text = [NSString stringWithFormat:@"%@%@",_textView.text,resultFromJson];

    if (isLast) {
        NSLog(@"听写结果(json):%@测试",  _result);

    }

}
/*!
 *  识别结束回调
 *
 *  @param error 识别结束错误码 0表示正常结束 非0表示发生错误
 */
- (void)onError: (IFlySpeechError *) error
{
    NSLog(@"%s[IN]",__func__);

    if ([IATConfig sharedInstance].haveView == NO) {
        NSString *text = @"";

        if (self.isCanceled) {
            text = @"识别取消";
        } else if (error.errorCode == 0) {
            if (_result.length == 0) {
                text = @"无识别结果";
            } else {
                text = @"识别成功";
            }
        }else {
            text = [NSString stringWithFormat:@"发生错误:%d %@",error.errorCode,error.errorDesc];
            NSLog(@"%@",text);
        }
        [_popUpView showText:text];
    } else {
        [_popUpView showText:@"识别结束"];
        NSLog(@"errorCode:%d",[error errorCode]);
    }

    startBtn.enabled = YES;

}

/**
 *  开如识别回调
 */
- (void) onBeginOfSpeech{
    NSLog(@"%s[IN]",__func__);
    [_popUpView showText:@"正在录音"];
}
/**
 *  停止录音回调
 */
- (void) onEndOfSpeech{
    NSLog(@"%s[IN]",__func__);
    [_popUpView showText:@"停止录音"];

}

/**
 *  在录音过程中,回调音频的音量
 *
 *  @param volume  -[out] 音量,范围从0-30
 */
- (void) onVolumeChanged: (int)volume
{
    NSLog(@"%s[IN]",__func__);
    if (self.isCanceled) {
        [_popUpView removeFromSuperview];
        return;

    }
    NSString *vol = [NSString stringWithFormat:@"音量 %d",volume];
    [_popUpView showText:vol];

}

/**
 *  取消识别回调
 */
- (void) onCancel
{
    NSLog(@"%s[IN]",__func__);

}

/**
 *  返回音频Key
 *
 *  @param key 音频Key
 */
- (void) getAudioKey:(NSString *)key{
    NSLog(@"%s[IN]",__func__);

}

/**
 *  扩展事件回调
 *  根据事件类型返回额外的数据
 *
 *  @param eventType 事件类型,具体参见IFlySpeechEventType的IFlySpeechEventTypeVoiceChangeResult枚举。
 *  @param arg0      arg0
 *  @param arg1      arg1
 *  @param eventData 事件数据
 */
- (void) onEvent:(int)eventType arg0:(int)arg0 arg1:(int)arg1 data:(NSData *)eventData{

}

#pragma mark -设置识别参数
/**
 设置识别参数
 ****/
-(void)initRecognizer
{
    NSLog(@"%s",__func__);

    if ([IATConfig sharedInstance].haveView == NO) {//无界面

        //单例模式,无UI的实例
        if (_iFlySpeechRecognizer == nil) {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];

            [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];

            //设置听写模式
            [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        }
        _iFlySpeechRecognizer.delegate = self;

        if (_iFlySpeechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];

            //设置最长录音时间
            [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //设置后端点
            [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //设置前端点
            [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //网络等待时间
            [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];

            //设置采样率,推荐使用16K
            [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];

            if ([instance.language isEqualToString:[IATConfig chinese]]) {
                //设置语言
                [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
                //设置方言
                [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            }else if ([instance.language isEqualToString:[IATConfig english]]) {
                [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            }
            //设置是否返回标点符号
            [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];

        }
    }else  {//有界面

        //单例模式,UI的实例
        if (_iflyRecognizerView == nil) {
            //UI显示剧中
            _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];

            [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];

            //设置听写模式
            [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];

        }
        _iflyRecognizerView.delegate = self;

        if (_iflyRecognizerView != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            //设置最长录音时间
            [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //设置后端点
            [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //设置前端点
            [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //网络等待时间
            [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];

            //设置采样率,推荐使用16K
            [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            if ([instance.language isEqualToString:[IATConfig chinese]]) {
                //设置语言
                [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
                //设置方言
                [_iflyRecognizerView setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            }else if ([instance.language isEqualToString:[IATConfig english]]) {
                //设置语言
                [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            }
            //设置是否返回标点符号
            [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];

        }
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Kerox\Messenger\Tests\TestCase\Model\ProfileSettings;

use Kerox\Messenger\Exception\MessengerException;
use Kerox\Messenger\Model\ProfileSettings\TargetAudience;
use PHPUnit\Framework\TestCase;

class TargetAudienceTest extends TestCase
{
    public function testInvalidTargetAudienceType(): void
    {
        $this->expectException(MessengerException::class);
        $this->expectExceptionMessage('audienceType must be either "all, custom, none".');
        TargetAudience::create('partial');
    }
}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * LoginController Class
 *
 * @category	Controller
 * @author		Carlos Luis Rivero
 * @link		https://github.com/riveroreyes
 */
class LoginController extends CI_Controller{

	//------------------------------------------------------------------------
	/**
	 * Index
	 *
	 * Valida el ingreso del usuario.
	 *
	 * @return void
	 */
	public function index()
	{
		$email 		= $this->input->post('lg_username');
		$password 	= $this->input->post('lg_password');

		$email 		= str_replace("'", "", $email);
		$password 	= str_replace("'", "", $password);

		$email 		= str_replace("\"", "", $email);
		$password 	= str_replace("\"", "", $password);

		$this->load->model('users');

		if( ($fila = $this->users->getUser($email)) != null){
			if($fila->password == $password){
				$data = array(
					'email'	=> $email,
					'id'	=> $fila->id,
					'name'	=> $fila->name,
					'type'	=> $fila->type,
					'login'	=> TRUE
					);
				$this->session->set_userdata($data);
				redirect("WelcomeController");
			}else{
				redirect("WelcomeController"); //...Usuario correcto, password incorrecto
			}
		}else{
			redirect("WelcomeController"); //...Usuario no existe
		}

	}

	//------------------------------------------------------------------------

	/**
	 * CerrarSession
	 *
	 * Cierra la session del usuario
	 *
	 * @return void
	 */
	public function cerrarSession(){
		$this->session->sess_destroy();
		redirect("WelcomeController"); //...Usuario no existe
	}

	//------------------------------------------------------------------------

	/**
	 * Registro
	 *
	 * Ingresa los datos del usuario para una nueva cuenta. Los datos son
	 * validados desde config/form_validation.php
	 *
	 * @return void
	 */
	public function registro()
	{

		if ($this->form_validation->run() == FALSE) {

			$str = form_error('reg_username'); 			if($str!=""){echo $str; return;}
			$str = form_error('reg_password'); 			if($str!=""){echo $str; return;}
			$str = form_error('reg_password_confirm'); 	if($str!=""){echo $str; return;}
			$str = form_error('reg_email'); 			if($str!=""){echo $str; return;}
			$str = form_error('reg_fullname'); 			if($str!=""){echo $str; return;}
			$str = form_error('reg_gender'); 			if($str!=""){echo $str; return;}
			$str = form_error('reg_agree'); 			if($str!=""){echo $str; return;}

		}else{

			$this->load->model('users');

			$data = array(
				'name' 			=> $this->input->post('reg_username'),
				'fullname' 		=> $this->input->post('reg_fullname'),
				'email' 		=> $this->input->post('reg_email'),
				'password' 		=> $this->input->post('reg_password'),
				'type' 			=> 'member',
				'genero' 		=> $this->input->post('reg_gender'),
				'created_at' 	=> strftime( "%Y-%m-%d %H:%M:%S", time() )
				);

			if($this->users->insertar($data) == true){

				 echo
				'

			  	<button type="button" class="close" data-dismiss="alert" aria-label="Close">
			  	×
				</button>

Usuario creado exitosamente!

'
				 ;

			}else{
				echo "error al insertar los datos.";
			}
		}

	}

	//------------------------------------------------------------------------

	/**
	 * RecuperarPassWord
	 *
	 * Envia un correo al usuario indicandole la contraseña.
	 *
	 * @return boolean
	 */
	public function recuperarPassWord(){

		$this->load->library('email');

		$this->email->from('soporte@msa.com.ve', 'Departamento de Ventas');
		$this->email->to('riveroreyes@hotmail.com');
		//$this->email->cc('msa.com.ve@gmail.com');

		$this->email->subject('Aplicación Agenda: Recuperación de Contraseña');
		$this->email->message('
			Estimado usuario esta recibiendo este correo porque solicito la recuperación de
			su contraseña desde nuestra aplicación de prueba en www.msa.com.ve/agenda.
			Su contraseña es: xxxxxx

			Esta cuenta no es monitoreada. Por favor no responda este mensaje.
			');

		if($this->email->send()){
			echo "Envío exitoso!
";
			echo $this->email->print_debugger();
			return true;
		}else{
			echo "Envío fallido!
";
			echo $this->email->print_debugger();
			return false;
		}

	}
}

?>


text:
<?php

class Google_Service_Genomics_UndeleteDatasetRequest extends Google_Model
{
}


text:
<?php
namespace JeeraAPI;

use ZF\Apigility\Provider\ApigilityProviderInterface;

class Module implements ApigilityProviderInterface
{
    public function getConfig()
    {
        return include __DIR__ . '/../../config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'ZF\Apigility\Autoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__,
                ),
            ),
        );
    }

    public function getServiceConfig()
    {
	 return array(
	    'factories' => array(
	      'JeeraAPI\V1\Rest\Sathish\SathishMapper' =>  function ($sm) {
		$adapter = $sm->get('Zend\Db\Adapter\Adapter');
		return new \JeeraAPI\V1\Rest\Sathish\SathishMapper($adapter);
	      },
	    ),
	 );
   }

}


text: ${data}


text:
- Use recursion
- Check if there are any overlapping subproblems whose results can be cached


text:
published: false
title: We Have A Winner!
date: '2007-05-01T20:09:00.000-04:00'
author: Lori
tags:
modified_datetime: '2007-05-01T20:13:23.264-04:00'
blogger_id: tag:blogger.com,1999:blog-5767374071871443859.post-2245197065498604745
blogger_orig_url: https://brooklinebooksmith.blogspot.com/2007/05/we-have-winner.html
---
I almost forgot—Alexis, come on by and pick up _Free Food for Millionaires_ whenever you want!

_The Secret History of the American Empire_ is still up for grabs. I know there has to be someone out there interested in hijacking, assassinations, bribery, extortion, and profiteering. I was going to make a political joke there, but, well, you were all already thinking it anyways.


text:
package gamepad

import (
	"time"
	"unsafe"

	"golang.org/x/sys/windows"

	"github.com/hajimehoshi/ebiten/v2/internal/gamepaddb"
)

func standardButtonToGamepadInputGamepadButton(b gamepaddb.StandardButton) (_GameInputGamepadButtons, bool) {
	switch b {
	case gamepaddb.StandardButtonRightBottom:
		return _GameInputGamepadA, true
	case gamepaddb.StandardButtonRightRight:
		return _GameInputGamepadB, true
	case gamepaddb.StandardButtonRightLeft:
		return _GameInputGamepadX, true
	case gamepaddb.StandardButtonRightTop:
		return _GameInputGamepadY, true
	case gamepaddb.StandardButtonFrontTopLeft:
		return _GameInputGamepadLeftShoulder, true
	case gamepaddb.StandardButtonFrontTopRight:
		return _GameInputGamepadRightShoulder, true
	case gamepaddb.StandardButtonFrontBottomLeft:
		return 0, false // Use leftTrigger instead.
	case gamepaddb.StandardButtonFrontBottomRight:
		return 0, false // Use rightTrigger instead.
	case gamepaddb.StandardButtonCenterLeft:
		return _GameInputGamepadView, true
	case gamepaddb.StandardButtonCenterRight:
		return _GameInputGamepadMenu, true
	case gamepaddb.StandardButtonLeftStick:
		return _GameInputGamepadLeftThumbstick, true
	case gamepaddb.StandardButtonRightStick:
		return _GameInputGamepadRightThumbstick, true
	case gamepaddb.StandardButtonLeftTop:
		return _GameInputGamepadDPadUp, true
	case gamepaddb.StandardButtonLeftBottom:
		return _GameInputGamepadDPadDown, true
	case gamepaddb.StandardButtonLeftLeft:
		return _GameInputGamepadDPadLeft, true
	case gamepaddb.StandardButtonLeftRight:
		return _GameInputGamepadDPadRight, true
	case gamepaddb.StandardButtonCenterCenter:
		return 0, false
	}
	return 0, false
}

type nativeGamepadsXbox struct {
	gameInput         *_IGameInput
	deviceCallbackPtr uintptr
	token             _GameInputCallbackToken
}

func (n *nativeGamepadsXbox) init(gamepads *gamepads) error {
	g, err := _GameInputCreate()
	if err != nil {
		return err
	}

	n.gameInput = g
	n.deviceCallbackPtr = windows.NewCallbackCDecl(n.deviceCallback)

	if err := n.gameInput.RegisterDeviceCallback(
		nil,
		_GameInputKindGamepad,
		_GameInputDeviceConnected,
		_GameInputBlockingEnumeration,
		unsafe.Pointer(gamepads),
		n.deviceCallbackPtr,
		&n.token,
	); err != nil {
		return err
	}
	return nil
}

func (n *nativeGamepadsXbox) update(gamepads *gamepads) error {
	return nil
}

func (n *nativeGamepadsXbox) deviceCallback(callbackToken _GameInputCallbackToken, context unsafe.Pointer, device *_IGameInputDevice, timestamp uint64, currentStatus _GameInputDeviceStatus, previousStatus _GameInputDeviceStatus) uintptr {
	gps := (*gamepads)(context)

	// Connected.
	if currentStatus&_GameInputDeviceConnected != 0 {
		// TODO: Give a good name and a SDL ID.
		gp := gps.add("", "00000000000000000000000000000000")
		gp.native = &nativeGamepadXbox{
			gameInputDevice: device,
		}
		return 0
	}

	// Disconnected.
	gps.remove(func(gamepad *Gamepad) bool {
		return gamepad.native.(*nativeGamepadXbox).gameInputDevice == device
	})

	return 0
}

type nativeGamepadXbox struct {
	gameInputDevice *_IGameInputDevice
	state           _GameInputGamepadState

	vib    bool
	vibEnd time.Time
}

func (n *nativeGamepadXbox) update(gamepads *gamepads) error {
	gameInput := gamepads.native.(*nativeGamepadsXbox).gameInput
	r, err := gameInput.GetCurrentReading(_GameInputKindGamepad, n.gameInputDevice)
	if err != nil {
		return err
	}
	defer r.Release()

	state, ok := r.GetGamepadState()
	if !ok {
		n.state = _GameInputGamepadState{}
		return nil
	}
	n.state = state

	if n.vib && time.Now().Sub(n.vibEnd) >= 0 {
		n.gameInputDevice.SetRumbleState(&_GameInputRumbleParams{
			lowFrequency:  0,
			highFrequency: 0,
		}, 0)
		n.vib = false
	}

	return nil
}

func (n *nativeGamepadXbox) hasOwnStandardLayoutMapping() bool {
	return true
}

func (n *nativeGamepadXbox) isStandardAxisAvailableInOwnMapping(axis gamepaddb.StandardAxis) bool {
	switch axis {
	case gamepaddb.StandardAxisLeftStickHorizontal,
		gamepaddb.StandardAxisLeftStickVertical,
		gamepaddb.StandardAxisRightStickHorizontal,
		gamepaddb.StandardAxisRightStickVertical:
		return true
	}
	return false
}

func (n *nativeGamepadXbox) isStandardButtonAvailableInOwnMapping(button gamepaddb.StandardButton) bool {
	switch button {
	case gamepaddb.StandardButtonFrontBottomLeft,
		gamepaddb.StandardButtonFrontBottomRight:
		return true
	}
	_, ok := standardButtonToGamepadInputGamepadButton(button)
	return ok
}

func (n *nativeGamepadXbox) axisCount() int {
	return int(gamepaddb.StandardAxisMax) + 1
}

func (n *nativeGamepadXbox) buttonCount() int {
	return int(gamepaddb.StandardButtonMax) + 1
}

func (n *nativeGamepadXbox) hatCount() int {
	return 0
}

func (n *nativeGamepadXbox) axisValue(axis int) float64 {
	switch gamepaddb.StandardAxis(axis) {
	case gamepaddb.StandardAxisLeftStickHorizontal:
		return float64(n.state.leftThumbstickX)
	case gamepaddb.StandardAxisLeftStickVertical:
		return -float64(n.state.leftThumbstickY)
	case gamepaddb.StandardAxisRightStickHorizontal:
		return float64(n.state.rightThumbstickX)
	case gamepaddb.StandardAxisRightStickVertical:
		return -float64(n.state.rightThumbstickY)
	}
	return 0
}

func (n *nativeGamepadXbox) buttonValue(button int) float64 {
	switch gamepaddb.StandardButton(button) {
	case gamepaddb.StandardButtonFrontBottomLeft:
		return float64(n.state.leftTrigger)
	case gamepaddb.StandardButtonFrontBottomRight:
		return float64(n.state.rightTrigger)
	}
	b, ok := standardButtonToGamepadInputGamepadButton(gamepaddb.StandardButton(button))
	if !ok {
		return 0
	}
	if n.state.buttons&b != 0 {
		return 1
	}
	return 0
}

func (n *nativeGamepadXbox) isButtonPressed(button int) bool {
	// Use XInput's trigger dead zone.
	// See https://source.chromium.org/chromium/chromium/src/+/main:device/gamepad/public/cpp/gamepad.h;l=22-23;drc=6997f8a177359bb99598988ed5e900841984d242
	// TODO: Integrate this value with the same one in the package gamepaddb.
	const threshold = 30.0 / 255.0
	switch gamepaddb.StandardButton(button) {
	case gamepaddb.StandardButtonFrontBottomLeft:
		return n.state.leftTrigger >= threshold
	case gamepaddb.StandardButtonFrontBottomRight:
		return n.state.rightTrigger >= threshold
	}

	b, ok := standardButtonToGamepadInputGamepadButton(gamepaddb.StandardButton(button))
	if !ok {
		return false
	}
	if n.state.buttons&b != 0 {
		return true
	}
	return false
}

func (n *nativeGamepadXbox) hatState(hat int) int {
	return 0
}

func (n *nativeGamepadXbox) vibrate(duration time.Duration, strongMagnitude float64, weakMagnitude float64) {
	if strongMagnitude <= 0 && weakMagnitude <= 0 {
		n.vib = false
		n.gameInputDevice.SetRumbleState(&_GameInputRumbleParams{
			lowFrequency:  0,
			highFrequency: 0,
		}, 0)
		return
	}
	n.vib = true
	n.vibEnd = time.Now().Add(duration)
	n.gameInputDevice.SetRumbleState(&_GameInputRumbleParams{
		lowFrequency:  float32(strongMagnitude),
		highFrequency: float32(weakMagnitude),
	}, 0)
}


text:
```js
function _(el){return document.getElementById(el);}
function _q(el){return document.querySelector(el);}
function _a(el){return document.querySelectorAll(el);}
function _cr(el){return document.createElement(''+el+'');}
function _rm(el){el.parentNode.removeChild(el);}
function _ap(el,dest){dest.appendChild(el);}
// function _pp(el,dest){dest.insertBefore(el,dest.firstChild);}
function _i(el,html){el.innerHTML=html;}
function _e(el){el.innerHTML='';}
function _sa(el,at,v){el.setAttribute(at,v);}
```
### request
```js
function _r(u, c, xml)
{
    if (xml === undefined) {
        xml = false;
    }
    var x = new XMLHttpRequest();
    x.open("GET", u, true);
    x.onreadystatechange = function ()
    {
        if (x.readyState == 4) {
            if (xml) {
                c.call(x.responseXML);
            }
            else {
                c.call(x.response);
            }
        }
    };
    x.send(null);
}
```

### request min
```js
function _r(u,c,xml){if(xml===undefined){xml=false;}var x=new XMLHttpRequest();x.open("GET",u,true);x.onreadystatechange=function(){if(x.readyState==4){if(xml){c.call(x.responseXML);}else{c.call(x.response);}}};x.send(null);}
```
usage:
```js
_r('test.json', function() {
  console.log(JSON.parse(this))
});

_r('test.xml', function() {
    console.log(this);
},true);
```

### if
```if (i>0) ? i-- : i ;``` to samo ```if (i>0) { i--;} else { i ; }```

### if not null
```js
if (!!val) { notNULL } else { isNULL }
```

### between
```js
String.prototype.between = function(prefix, suffix) {
  s = this;
  var i = s.indexOf(prefix);
  if (i >= 0) {
    s = s.substring(i + prefix.length);
  }
  else {
    return '';
  }
  if (suffix) {
    i = s.indexOf(suffix);
    if (i >= 0) {
      s = s.substring(0, i);
    }
    else {
      return '';
    }
  }
  return s;
}

var dupa = '#80349__jaks-tekst'.between('#','__');
alert(dupa);
```

### color rows
```js
  var myTR = document.getElementsByTagName('tr'); /* To use with lists, just change 'tr' to 'li' */
  for (var i=0;i<myTR.length;i++) {
    if (i%2) {
      myTR[i].className = 'rowTint';
    }
  }
```

### escapeHtml
```js
function escapeHtml(s) {
  s = s.replace(/&/g, '&');
  s = s.replace(/</g, '<');
  s = s.replace(/>/g, '>');
  s = s.replace(/"/g, '"');
  s = s.replace(/'/g, ''');
  return s;
}
```

### toggle element by css selector
```js
function toggle(css) {
  el = document.querySelector(css);
  if (typeof window.getComputedStyle != "undefined") { styleObj = window.getComputedStyle(el, null); } else if (el.currentStyle != "undefined") { styleObj = el.currentStyle; }
  if(styleObj.display == "none" || styleObj.display == '') { el.style.display = "block"; } else { el.style.display = "none"; }
}
```

### getSelection
```js
function getSel() {
    var txt = '';
    var foundIn = '';
    if (window.getSelection) {
        txt = window.getSelection();
        foundIn = 'window.getSelection()';
    }
    else if (document.getSelection) {
        txt = document.getSelection();
        foundIn = 'document.getSelection()';
    }
    else if (document.selection) {
    txt = document.selection.createRange().text;
    foundIn = 'document.selection.createRange()';
    }
    else return;
document.forms[0].selectedtext.value = 'Found in: ' foundIn '\n' txt;
}
```
### each
```js
[].forEach.call(
    document.querySelectorAll('selector'),
    function(el){
        el.doSomething // el item
    }
);
```

### How to build a Shadow DOM
```html
<div id="host"></div>
```
```js
var host = document.querySelector('#host');
var root = host.createShadowRoot(); // Create a Shadow Root
// var root = host.attachShadow({mode: 'open'});
// var root = host.attachShadow({mode: 'closed'});
var div = document.createElement('div');
div.textContent = 'This is Shadow DOM';
root.appendChild(div); // Append elements to the Shadow Root
```


text:
using testing::AllOf;
using testing::Eq;
using testing::Mock;
using testing::Property;
using testing::Sequence;

namespace policy {

namespace {

void RunUntilIdle() {
  base::RunLoop run_loop;
  run_loop.RunUntilIdle();
}

class UserCloudPolicyStoreTest : public testing::Test {
 public:
  UserCloudPolicyStoreTest() : loop_(base::MessageLoop::TYPE_UI) {}

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());
    store_.reset(
        new UserCloudPolicyStore(policy_file(), loop_.message_loop_proxy()));
    external_data_manager_.reset(new MockCloudExternalDataManager);
    external_data_manager_->SetPolicyStore(store_.get());
    store_->SetSigninUsername(PolicyBuilder::kFakeUsername);
    store_->AddObserver(&observer_);

    policy_.payload().mutable_passwordmanagerenabled()->set_value(true);
    policy_.payload().mutable_urlblacklist()->mutable_value()->add_entries(
        "chromium.org");

    policy_.Build();
  }

  virtual void TearDown() OVERRIDE {
    store_->RemoveObserver(&observer_);
    external_data_manager_.reset();
    store_.reset();
    RunUntilIdle();
  }

  base::FilePath policy_file() {
    return tmp_dir_.path().AppendASCII("policy");
  }

  // Verifies that store_->policy_map() has the appropriate entries.
  void VerifyPolicyMap(CloudPolicyStore* store) {
    EXPECT_EQ(2U, store->policy_map().size());
    const PolicyMap::Entry* entry =
        store->policy_map().Get(key::kPasswordManagerEnabled);
    ASSERT_TRUE(entry);
    EXPECT_TRUE(base::FundamentalValue(true).Equals(entry->value));
    ASSERT_TRUE(store->policy_map().Get(key::kURLBlacklist));
  }

  // Install an expectation on |observer_| for an error code.
  void ExpectError(CloudPolicyStore* store, CloudPolicyStore::Status error) {
    EXPECT_CALL(observer_,
                OnStoreError(AllOf(Eq(store),
                                   Property(&CloudPolicyStore::status,
                                            Eq(error)))));
  }

  UserPolicyBuilder policy_;
  MockCloudPolicyStoreObserver observer_;
  scoped_ptr<UserCloudPolicyStore> store_;
  scoped_ptr<MockCloudExternalDataManager> external_data_manager_;

  // CloudPolicyValidator() requires a FILE thread so declare one here. Both
  // |ui_thread_| and |file_thread_| share the same MessageLoop |loop_| so
  // callers can use RunLoop to manage both virtual threads.
  base::MessageLoop loop_;

  base::ScopedTempDir tmp_dir_;

  DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyStoreTest);
};

TEST_F(UserCloudPolicyStoreTest, LoadWithNoFile) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  Sequence s;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s);
  store_->Load();
  RunUntilIdle();

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
}

TEST_F(UserCloudPolicyStoreTest, LoadWithInvalidFile) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  // Create a bogus file.
  ASSERT_TRUE(file_util::CreateDirectory(policy_file().DirName()));
  std::string bogus_data = "bogus_data";
  int size = bogus_data.size();
  ASSERT_EQ(size, file_util::WriteFile(policy_file(),
                                       bogus_data.c_str(),
                                       bogus_data.size()));

  ExpectError(store_.get(), CloudPolicyStore::STATUS_LOAD_ERROR);
  store_->Load();
  RunUntilIdle();

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
}

TEST_F(UserCloudPolicyStoreTest, LoadImmediatelyWithNoFile) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  Sequence s;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s);
  store_->LoadImmediately();  // Should load without running the message loop.

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
}

TEST_F(UserCloudPolicyStoreTest, LoadImmediatelyWithInvalidFile) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  // Create a bogus file.
  ASSERT_TRUE(file_util::CreateDirectory(policy_file().DirName()));
  std::string bogus_data = "bogus_data";
  int size = bogus_data.size();
  ASSERT_EQ(size, file_util::WriteFile(policy_file(),
                                       bogus_data.c_str(),
                                       bogus_data.size()));

  ExpectError(store_.get(), CloudPolicyStore::STATUS_LOAD_ERROR);
  store_->LoadImmediately();  // Should load without running the message loop.

  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
}

TEST_F(UserCloudPolicyStoreTest, Store) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  // Store a simple policy and make sure it ends up as the currently active
  // policy.
  Sequence s;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s);
  store_->Store(policy_.policy());
  RunUntilIdle();

  // Policy should be decoded and stored.
  ASSERT_TRUE(store_->policy());
  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
            store_->policy()->SerializeAsString());
  VerifyPolicyMap(store_.get());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
}

TEST_F(UserCloudPolicyStoreTest, StoreThenClear) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  // Store a simple policy and make sure the file exists.
  // policy.
  Sequence s1;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s1);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s1);
  store_->Store(policy_.policy());
  RunUntilIdle();

  EXPECT_TRUE(store_->policy());
  EXPECT_FALSE(store_->policy_map().empty());

  Mock::VerifyAndClearExpectations(external_data_manager_.get());
  Mock::VerifyAndClearExpectations(&observer_);

  // Policy file should exist.
  ASSERT_TRUE(base::PathExists(policy_file()));

  Sequence s2;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s2);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s2);
  store_->Clear();
  RunUntilIdle();

  // Policy file should not exist.
  ASSERT_TRUE(!base::PathExists(policy_file()));

  // Policy should be gone.
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
}

TEST_F(UserCloudPolicyStoreTest, StoreTwoTimes) {
  EXPECT_FALSE(store_->policy());
  EXPECT_TRUE(store_->policy_map().empty());

  // Store a simple policy then store a second policy before the first one
  // finishes validating, and make sure the second policy ends up as the active
  // policy.
  Sequence s1;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s1);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s1);

  UserPolicyBuilder first_policy;
  first_policy.payload().mutable_passwordmanagerenabled()->set_value(false);
  first_policy.Build();
  store_->Store(first_policy.policy());
  RunUntilIdle();

  Mock::VerifyAndClearExpectations(external_data_manager_.get());
  Mock::VerifyAndClearExpectations(&observer_);

  Sequence s2;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s2);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s2);

  store_->Store(policy_.policy());
  RunUntilIdle();

  // Policy should be decoded and stored.
  ASSERT_TRUE(store_->policy());
  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
            store_->policy()->SerializeAsString());
  VerifyPolicyMap(store_.get());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store_->status());
}

TEST_F(UserCloudPolicyStoreTest, StoreThenLoad) {
  // Store a simple policy and make sure it can be read back in.
  // policy.
  Sequence s;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s);
  store_->Store(policy_.policy());
  RunUntilIdle();

  // Now, make sure the policy can be read back in from a second store.
  scoped_ptr<UserCloudPolicyStore> store2(
      new UserCloudPolicyStore(policy_file(), loop_.message_loop_proxy()));
  store2->SetSigninUsername(PolicyBuilder::kFakeUsername);
  store2->AddObserver(&observer_);
  EXPECT_CALL(observer_, OnStoreLoaded(store2.get()));
  store2->Load();
  RunUntilIdle();

  ASSERT_TRUE(store2->policy());
  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
            store2->policy()->SerializeAsString());
  VerifyPolicyMap(store2.get());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store2->status());
  store2->RemoveObserver(&observer_);
}

TEST_F(UserCloudPolicyStoreTest, StoreThenLoadImmediately) {
  // Store a simple policy and make sure it can be read back in.
  // policy.
  Sequence s;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s);
  store_->Store(policy_.policy());
  RunUntilIdle();

  // Now, make sure the policy can be read back in from a second store.
  scoped_ptr<UserCloudPolicyStore> store2(
      new UserCloudPolicyStore(policy_file(), loop_.message_loop_proxy()));
  store2->SetSigninUsername(PolicyBuilder::kFakeUsername);
  store2->AddObserver(&observer_);
  EXPECT_CALL(observer_, OnStoreLoaded(store2.get()));
  store2->LoadImmediately();  // Should load without running the message loop.

  ASSERT_TRUE(store2->policy());
  EXPECT_EQ(policy_.policy_data().SerializeAsString(),
            store2->policy()->SerializeAsString());
  VerifyPolicyMap(store2.get());
  EXPECT_EQ(CloudPolicyStore::STATUS_OK, store2->status());
  store2->RemoveObserver(&observer_);
}

TEST_F(UserCloudPolicyStoreTest, StoreValidationError) {
  // Create an invalid policy (no policy type).
  policy_.policy_data().clear_policy_type();
  policy_.Build();

  // Store policy.
  ExpectError(store_.get(), CloudPolicyStore::STATUS_VALIDATION_ERROR);
  store_->Store(policy_.policy());
  RunUntilIdle();
  ASSERT_FALSE(store_->policy());
}

TEST_F(UserCloudPolicyStoreTest, LoadValidationError) {
  // Force a validation error by changing the username after policy is stored.
  Sequence s;
  EXPECT_CALL(*external_data_manager_, OnPolicyStoreLoaded()).InSequence(s);
  EXPECT_CALL(observer_, OnStoreLoaded(store_.get())).InSequence(s);
  store_->Store(policy_.policy());
  RunUntilIdle();

  // Sign out, and sign back in as a different user, and try to load the profile
  // data (should fail due to mismatched username).
  scoped_ptr<UserCloudPolicyStore> store2(
      new UserCloudPolicyStore(policy_file(), loop_.message_loop_proxy()));
  store2->SetSigninUsername("foobar@foobar.com");
  store2->AddObserver(&observer_);
  ExpectError(store2.get(), CloudPolicyStore::STATUS_VALIDATION_ERROR);
  store2->Load();
  RunUntilIdle();

  ASSERT_FALSE(store2->policy());
  store2->RemoveObserver(&observer_);

  // Sign out - we should be able to load the policy (don't check usernames
  // when signed out).
  scoped_ptr<UserCloudPolicyStore> store3(
      new UserCloudPolicyStore(policy_file(), loop_.message_loop_proxy()));
  store3->AddObserver(&observer_);
  EXPECT_CALL(observer_, OnStoreLoaded(store3.get()));
  store3->Load();
  RunUntilIdle();

  ASSERT_TRUE(store3->policy());
  store3->RemoveObserver(&observer_);

  // Now start a signin as a different user - this should fail validation.
  scoped_ptr<UserCloudPolicyStore> store4(
      new UserCloudPolicyStore(policy_file(), loop_.message_loop_proxy()));
  store4->SetSigninUsername("foobar@foobar.com");
  store4->AddObserver(&observer_);
  ExpectError(store4.get(), CloudPolicyStore::STATUS_VALIDATION_ERROR);
  store4->Load();
  RunUntilIdle();

  ASSERT_FALSE(store4->policy());
  store4->RemoveObserver(&observer_);
}

}  // namespace

}  // namespace policy


text:
Profile

<?php echo $data['contact_title']; ?>

        ZIP : <?php echo $data['contact_zip']; ?> | Email <?php echo $data['contact_email']; ?> | <?php echo $data['contact_phone']; ?>

          <img src="<?= $base_dir; ?>libs/img/<?= $data['contact_img'] ?>" alt="<?= $data['contact_img'] ?>" style="width: 80%;">

            <?php echo $data['contact_description']; ?>
            <?php echo $data['contact_contribute']; ?>


text:
package de.dakror.gamesetup.ui;

/**
 * @author Dakror
 */
public interface ClickEvent {
	public void trigger();
}


text:
package gcmService;

import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONException;
import serverConnection.Post;

import com.google.android.gms.common.*;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.util.Log;

public class GCM
{
	//------------Variables-----------------------
	private static Activity _context;
	private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
	//-----------------------------------

	/**
	 *
	 * @param context
	 */
	public void setContext(Activity context)
	{
		_context = context;
	}

	/**
	 *
	 * @param context
	 * @return
	 */
	public static boolean checkPlayServices(Activity context)
	{
		_context = context;

	    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable( _context );
	    if ( resultCode != ConnectionResult.SUCCESS )
	    {
	        if ( GooglePlayServicesUtil.isUserRecoverableError( resultCode ) )
	        {
	            GooglePlayServicesUtil.getErrorDialog( resultCode, _context,
	            		PLAY_SERVICES_RESOLUTION_REQUEST ).show();
	        }
	        else
	        {
	            Log.i("GCM", "Dispositivo no soportado.");
	        }
	        return false;
	    }
	    return true;
	}

	/**
	 *
	 * @param context
	 * @return
	 * @throws JSONException
	 */
	public static String getRegistrationId( Activity context ) throws JSONException
	{
		_context = context;

		SharedPreferences _pref = _context.getSharedPreferences("LOG",Context.MODE_PRIVATE);
		String registrationId = _pref.getString("ID", "");

	    if (registrationId.length() == 0)
	    {
	        Log.d("GCM", "Registro GCM no encontrado.");
	        return "";
	    }
	    return registrationId;
	}

	/**
	 * GCM registration for new user.
	 *
	 */
	public static class TaskRegisterGCM extends AsyncTask<String,Integer,String>
	{
		//------------Variables-----------------------
		//Project Number: 701857172243
		private String SENDER_ID = "701857172243";
		private GoogleCloudMessaging _gcm;
		private Context _context;
		//-----------------------------------

		public TaskRegisterGCM( Context context )
		{
			_context = context;
		}

	    @Override
	    protected String doInBackground( String... params )
	    {
	            String msg = "";
	            try
	            {
	                if ( _gcm == null )
	                {
	                    _gcm = GoogleCloudMessaging.getInstance( _context );
	                }

	                //Registration into servers GCM
	                String _regid = _gcm.register( SENDER_ID );

	                SharedPreferences _pref = _context.getSharedPreferences( "LOG", Context.MODE_PRIVATE );
	                Editor _editor=_pref.edit();
			        _editor.putString( "ID", _regid );
			        _editor.commit();

	                ArrayList<String> _parametros = new ArrayList<String>();
	                _parametros.add( "command" );
					_parametros.add( "login3" );
					_parametros.add( "username" );
					_parametros.add( _pref.getString( "USER", "" ) );
					_parametros.add( "password" );
					_parametros.add( _pref.getString( "PASSWORD", "" ) );
					_parametros.add( "regid" );
					_parametros.add( _regid );
					_parametros.add( "os" );
					_parametros.add( "Android" );

					 _editor.putString( "ID", _regid );

					Post.getServerData( _parametros, "http://5.231.69.226/EHControlConnect/index.php" );//"http://192.168.2.147/EHControlConnect/index.php");

	            }
	            catch (IOException ex)
	            {
	                ex.printStackTrace();
	            }

	            return msg;
	        }
	}

}


text:
    <title>Groovy - An extensible multi-paradigm language for the JVM Platform</title>

Groovy - An extensible multi-paradigm language for the JVM Platform
(GroovyDoc for Groovy and Java classes)

    Groovy...

is an extensible and multi-paradigm language for the Java Virtual Machine

makes modern programming features available to Java developers with almost-zero learning curve

has a dynamic nature like Python and Ruby, which means that it is very powerful, easy to learn, and productive

optionally has static typing like Java and Kotlin, which makes it fast and provides extra type checking when desired

has first-class functional, stream processing and immutability support, meaning that it offers features similar to Scala and can offer many advantages when working in parallel processing or clustered environments

supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain

makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL

increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications

simplifies testing by supporting unit testing and mocking out-of-the-box

compiles straight to Java bytecode so you can use it anywhere you can use Java; it seamlessly integrates with all existing Java objects and libraries


text:
class CommandBackground : public ICommand {
	public:
		CommandBackground();
		virtual bool isMultiLine();
		virtual ICommand *create();
		virtual QString name();
		virtual void setParams(QStringList list);
		virtual bool check();
		virtual bool check(QString &strResult);
		virtual QString code();
		virtual void appendCode(QString);
		virtual void run(ICore *pCore);
	private:
		QString m_strName;
		bool m_bCheck;
		QString m_sCheck;
		int m_nColor;
		QStringList m_listParams;
};

#endif // COMMAND_BACKGROUND_H


text:
NOTE - No longer maintained and the website is no longer live.

## Technologies

- HTML: Page layouts
- CSS: Styling
- JavaScript: Customisation, client-side scripting
- [Bootstrap]: To help make it responsive, it scales correctly for screen sizes from mobile phones up to large desktops. I love writing websites using [Bootstrap].
- [Paper]: A Bootstrap theme to give elements Material design styling.
- [Bower]: For managing my dependency packages really easily.
- [jQuery]: Needs no introduction.
- [jQuery-Easing]: A jQuery plugin to provide smooth scrolling techniques when you click a link
- [Font-Awesome]: For really cool icons.
- [GitHub Pages]: For hosting the new version of my website, thanks GitHub!

## Author

Andrew Lord [@lordcodes](https://twitter.com/@lordcodes)

[Bootstrap]: https://github.com/twbs/bootstrap
[Paper]: http://bootswatch.com/paper/
[Bower]: https://github.com/bower/bower
[jQuery]: https://github.com/jquery/jquery
[jQuery-Easing]: https://github.com/gdsmith/jquery.easing
[Font-Awesome]: https://github.com/FortAwesome/Font-Awesome
[GitHub Pages]: https://pages.github.com/


text:
Angular app for MailChimp subscriptions with animations using an altered version of [angular-mailchimp](https://github.com/keithio/angular-mailchimp).

## Getting Started

To get you started you can simply clone the angular-mailchimp-form repository and install the dependencies:

### Prerequisites

You need git to clone the angular-mailchimp-form repository. You can get it from
[http://git-scm.com/](http://git-scm.com/).

We also use a number of node.js tools to initialize and test angular-mailchimp-form. You must have node.js and
its package manager (npm) installed.  You can get them from [http://nodejs.org/](http://nodejs.org/).

### Clone angular-mailchimp-form

Clone the angular-mailchimp-form repository using [git][git]:

```
git clone https://github.com/kickdrop/angular-mailchimp-form.git
cd angular-mailchimp-form
```

### Install Dependencies

We have two kinds of dependencies in this project: tools and angular framework code.  The tools help
us manage and test the application.

* We get the tools we depend upon via `npm`, the [node package manager][npm].
* We get the angular code via `bower`, a [client-side code package manager][bower].

We have preconfigured `npm` to automatically run `bower` so we can simply do:

```
npm install
```

Behind the scenes this will also call `bower install`.  You should find that you have two new
folders in your project.

* `node_modules` - contains the npm packages for the tools we need
* `app/bower_components` - contains the angular framework files

*Note that the `bower_components` folder would normally be installed in the root folder but
we changed this location through the `.bowerrc` file.  Putting it in the app folder makes
it easier to serve the files by a webserver.*

### Run the Application

We have preconfigured the project with a simple development web server.  The simplest way to start
this server is:

```
npm start
```

Now browse to the app at `http://localhost:8000/app/index.html`.

## Directory Layout

    app/                --> all of the files to be used in production
      css/              --> css files
        app.css         --> default stylesheet
        animations.css  --> stylesheet for custom animations
      index.html        --> app layout file (the main html template file of the app)
      js/               --> javascript files
        app.js          --> application
        controllers.js  --> application controllers
        directives.js   --> application directives
        filters.js      --> custom angular filters
        services.js     --> custom angular services

    test/               --> test config and source files
      protractor-conf.js    --> config file for running e2e tests with Protractor
      e2e/                  --> end-to-end specs
        scenarios.js
      karma.conf.js         --> config file for running unit tests with Karma
      unit/                 --> unit level specs/tests
        controllersSpec.js      --> specs for controllers
        directivessSpec.js      --> specs for directives
        filtersSpec.js          --> specs for filters
        servicesSpec.js         --> specs for services

## Testing

There are two kinds of tests in the angular-mailchimp-form application: Unit tests and End to End tests.

### Running Unit Tests

The angular-mailchimp-form app comes preconfigured with unit tests. These are written in
[Jasmine][jasmine], which we run with the [Karma Test Runner][karma]. We provide a Karma
configuration file to run them.

* the configuration is found at `test/karma.conf.js`
* the unit tests are found in `test/unit/`.

The easiest way to run the unit tests is to use the supplied npm script:

```
npm test
```

This script will start the Karma test runner to execute the unit tests. Moreover, Karma will sit and
watch the source and test files for changes and then re-run the tests whenever any of them change.
This is the recommended strategy; if your unit tests are being run every time you save a file then
you receive instant feedback on any changes that break the expected code functionality.

You can also ask Karma to do a single run of the tests and then exit.  This is useful if you want to
check that a particular version of the code is operating as expected.  The project contains a
predefined script to do this:

```
npm run test-single-run
```

### End to end testing

The angular-mailchimp-form app comes with end-to-end tests, again written in [Jasmine][jasmine]. These tests
are run with the [Protractor][protractor] End-to-End test runner.  It uses native events and has
special features for Angular applications.

* the configuration is found at `test/protractor-conf.js`
* the end-to-end tests are found in `test/e2e/`

Protractor simulates interaction with our web app and verifies that the application responds
correctly. Therefore, our web server needs to be serving up the application, so that Protractor
can interact with it.

```
npm start
```

In addition, since Protractor is built upon WebDriver we need to install this.  The angular-mailchimp-form
project comes with a predefined script to do this:

```
npm run update-webdriver
```

This will download and install the latest version of the stand-alone WebDriver tool.

Once you have ensured that the development web server hosting our application is up and running
and WebDriver is updated, you can run the end-to-end tests using the supplied npm script:

```
npm run protractor
```

This script will execute the end-to-end tests against the application being hosted on the
development server.

## Updating Angular

You can update the tool dependencies by running:

```
npm update
```

This will find the latest versions that match the version ranges specified in the `package.json` file.

You can update the Angular dependencies by running:

```
bower update
```

This will find the latest versions that match the version ranges specified in the `bower.json` file.

## Serving the Application Files

### Running the App during Development

The angular-mailchimp-form project comes preconfigured with a local development webserver.  It is a node.js
tool called [http-server][http-server].  You can start this webserver with `npm start` but you may choose to
install the tool globally:

```
sudo npm install -g http-server
```

Then you can start your own development web server to serve static files from a folder by
running:

```
http-server
```

Alternatively, you can choose to configure your own webserver, such as apache or nginx. Just
configure your server to serve the files under the `app/` directory.

### Running the App in Production

This really depends on how complex is your app and the overall infrastructure of your system, but
the general rule is that all you need in production are all the files under the `app/` directory.
Everything else should be omitted.

Angular apps are really just a bunch of static html, css and js files that just need to be hosted
somewhere they can be accessed by browsers.

If your Angular app is talking to the backend server via xhr or other means, you need to figure
out what is the best way to host the static files to comply with the same origin policy if
applicable. Usually this is done by hosting the files by the backend server or through
reverse-proxying the backend server(s) and webserver(s).

## Contact

For more information on AngularJS please check out http://angularjs.org/

[git]: http://git-scm.com/
[bower]: http://bower.io
[npm]: https://www.npmjs.org/
[node]: http://nodejs.org
[protractor]: https://github.com/angular/protractor
[jasmine]: http://pivotal.github.com/jasmine/
[karma]: http://karma-runner.github.io
[travis]: https://travis-ci.org/
[http-server]: https://github.com/nodeapps/http-server


text:
class LatteAccount < ApplicationRecord

  validates :name, :user_id, presence: true
  belongs_to :user
  # attr_encrypted :password, key: :encryption_key
  # def encryption_key
  #     SecureRandom.base64(32)
  # end

end


text:
namespace clang {
namespace tidy {
namespace fuchsia {

/// Constructing global, non-trivial objects with static storage is
/// disallowed, unless the object is statically initialized with a constexpr
/// constructor or has no explicit constructor.
///
/// For the user-facing documentation see:
/// http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-statically-constructed-objects.html
class StaticallyConstructedObjectsCheck : public ClangTidyCheck {
public:
  StaticallyConstructedObjectsCheck(StringRef Name, ClangTidyContext *Context)
      : ClangTidyCheck(Name, Context) {}
  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
};

} // namespace fuchsia
} // namespace tidy
} // namespace clang

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_STATICALLY_CONSTRUCTED_OBJECTS_H


text:
//
// Matlab MEX interface for KD-tree C++ functions
//
// Written by Alex Ihler and Mike Mandel
// Copyright (C) 2003 Alexander Ihler; distributable under GPL -- see README.txt
//

#define MEX
#include "mex.h"
#include "cpp/BallTreeDensity.h"

void gibbs1(unsigned int _Ndens, const BallTreeDensity* _trees,
            unsigned long Np, unsigned int Niter,
            double *_pts, BallTree::index *_ind,
            double *_randU, double* _randN);
void gibbs2(unsigned int _Ndens, const BallTreeDensity* _trees,
            unsigned long Np, unsigned int Niter,
            double *_pts, BallTree::index *_ind,
            double *_randU, double* _randN);

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  mxArray **analyticFnParam;
  mxArray *aRandVec, *aRandVecN;
  mxArray *aRandParam;
  double *pRandParam, *randU, *randN;

  mxArray *pointsM, *weightsM, *indicesM;
  double *points, *weights;
  BallTree::index* indices;

  unsigned int i;
  unsigned int Niter,Ndens,Ndim,Np;

  /*********************************************************************
  ** Verify arguments and initialize variables
  *********************************************************************/

  if (nrhs < 3)
    mexErrMsgTxt("Takes 3-5 input arguments");
  if (nlhs != 2)
    mexErrMsgTxt("Outputs 2 results");

  Ndens = mxGetN(prhs[0]);               // get # of densities

  /*********************************************************************
  ** Transform Matlab cell arrays into struct NPD representation
  *********************************************************************/

  BallTreeDensity *trees = new BallTreeDensity[Ndens];
  bool allGaussians = true;
  for (i=0; i < Ndens; i++) {
    trees[i] = BallTreeDensity( mxGetCell(prhs[0],i) );
    if (trees[i].getType() != BallTreeDensity::Gaussian) allGaussians = false;
  }
  if (!allGaussians)
    mexErrMsgTxt("Sorry -- only Gaussian kernels supported");

  Ndim  = trees[0].Ndim();          //  # of dimensions
  Np    = (unsigned long) mxGetScalar(prhs[1]);     //  # of points to sample
  Niter = (unsigned int)  mxGetScalar(prhs[2]);     //  # of gibbs iterations

  if ((nrhs < 5) || (mxGetN(prhs[3]) == 0)) {   // load analytic function
    analyticFnParam = NULL;                     //   params if required
  }
  else {
    analyticFnParam = (mxArray**) mxMalloc(3*sizeof(mxArray*));
    analyticFnParam[0] = (mxArray*) prhs[3];
    analyticFnParam[1] = (mxArray*) prhs[4];
  }

  pointsM = plhs[0] = mxCreateDoubleMatrix(Ndim, Np, mxREAL);   // set up matlab output
  points  = (double*) mxGetData(plhs[0]);
//  plhs[1] = mxCreateDoubleMatrix(1, Np, mxREAL);
//  weights = (double*) mxGetData(plhs[1]);
  plhs[1] = mxCreateNumericMatrix(Ndens, Np, mxUINT32_CLASS, mxREAL);
  indices = (BallTree::index*) mxGetData(plhs[1]);

  unsigned long maxNp = Np;             // largest # of particles we deal with
  for (unsigned int j=0; j<Ndens; j++)  // compute Max Np over all densities
    if (maxNp < trees[j].Npts()) maxNp = trees[j].Npts();
  unsigned int Nlevels = (unsigned int) (log(maxNp)/log(2))+1;  // how many levels to a balanced binary tree?

  // Generate enough random numbers to get us through the rest of this
  aRandParam = mxCreateDoubleMatrix(1, 2, mxREAL);
  pRandParam = mxGetPr(aRandParam);
  pRandParam[0] = 1;  pRandParam[1] = Np*Ndens*(Niter+1)*Nlevels;
  mexCallMATLAB(1, &aRandVec, 1, &aRandParam, "rand");   randU = mxGetPr(aRandVec);
  pRandParam[0] = 1;  pRandParam[1] = Ndim*Np*(Niter+1)*Nlevels;
  mexCallMATLAB(1, &aRandVecN, 1, &aRandParam, "randn"); randN = mxGetPr(aRandVecN);
  mxDestroyArray(aRandParam);

  // Params:  Ndens, trees, points, weights, indices, randomU, randomN
  gibbs2(Ndens,trees,Np,Niter,points,indices, randU,randN);

  delete[] trees;

  if (analyticFnParam != NULL)
    mxFree(analyticFnParam);

  mxDestroyArray(aRandVec);
  mxDestroyArray(aRandVecN);
}


text:
import time
import wiringpi2 as wiringpi
wiringpi.wiringPiSetup()

# Setup the LedBorg GPIO pins
PIN_RED = 0
PIN_GREEN = 2
PIN_BLUE = 3
wiringpi.pinMode(PIN_RED, wiringpi.GPIO.OUTPUT)
wiringpi.pinMode(PIN_GREEN, wiringpi.GPIO.OUTPUT)
wiringpi.pinMode(PIN_BLUE, wiringpi.GPIO.OUTPUT)

# Set the colour channels (1 is on, 0 is off) and the time delay in seconds
red = 0
green = 0
blue = 1
delay = 5

# Turn the LedBorg off
wiringpi.digitalWrite(PIN_RED, 0)
wiringpi.digitalWrite(PIN_GREEN, 0)
wiringpi.digitalWrite(PIN_BLUE, 0)
print 'LedBorg off'


text:
{% extends 'base.html' %}
{% load staticfiles %}
{% load custom_tags %}

{% comment %}

   Copyright 2018, Institute for Systems Biology

   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.

{% endcomment %}

{% block header %}
{% endblock %}
{% block link_page_name %}cohort-details{% endblock %}
{% block page_name %}cohort-details{% endblock %}

{% block page_header %}
    <link type="text/css" rel="stylesheet" href="{% static 'css/token-typeahead.css' %}"/>

        {% if workbook %}

Your Dashboard

Saved Workbooks

{{ workbook.name }}

        {% else %}

Your Dashboard

Cohorts

        {% endif %}

Create Cohort - Barcodes

{% endblock %}

{% block content %}

                        <button type="button" class="close" data-hide="alert">×Close</button>
                        You have selected too many filters. The current counts shown will not be accurate until one or
                        more filter options are removed.

Upload

Enter

Upload a GDC Data Portal Case Manifest or a CSV/TSV file of barcodes and
                                    programs

Files must be in GDC Data Portal case manifest format,
                                        or in comma/tab-delimited case/sample/program format.
                                        After selecting the file and uploading it, the entries will be validated. Any
                                        entries which are found to be invalid will be listed, and you can choose to omit
                                        them and continue with cohort creation, or select a new file for verification
                                        and upload.

CSV/TSV Barcode Files

All entries must be either a valid case barcode or
                                        sample barcode. When a case barcode is provided, all
                                        samples from that case will be included in the cohort. For the following programs,
                                        You must add the program prefix listed below before the barcode provided to ensure
                                        we can identify these barcodes:

                                            BEATAML1.0	BEATAML1.0-

                                            MMRF	MMRF-

                                            Family Medicine	FM-

                                            Georgetown PRP	GPRP-

                                            OHSU	OHSU-

Barcode sets may be in tab-, comma-, or newline-separated format. Values may be
                                        placed in single or double quotes, and can be on a single line or on multiple
                                        lines.

Tab- or comma-delimited files must have an extension of .txt, .csv, or .tsv. Please do not include any column headers.

Example Barcode File Contents

TCGA-N9-A4Q4,TCGA-N7-A4Y8-01A,'Saos-2','Hs 863.T'

"TCGA-N7-A4Y8-01A"
'Hs 863.T', TARGET-51-PAJMFS

LAMA-84
LC-1F
LCLC-103H
TARGET-10-CAAABC-60.3A
TARGET-10-CAAABD-60.2A
TARGET-10-CAAABF-60.11C

GDC Data Portal Case Manifest Files

GDC Data Portal case manifests can be obtained on the 'Cases'
                                        tab of the Exploration section of the data portal.

JSON case manifests must have a .json extension, and will be validated against
                                        the GDC's JSON schema. The minimum required properties for each entry in the
                                        JSON file are the project object and the submitter_id field. The project object must include the project_id
                                        property. All other properties will be ignored.

TSV case manifests must have a .tsv extension, and must contain the Case ID and
                                        Project columns. Any other columns will be ignored. Do not remove the
                                            header row of the TSV case manifest. Please note that currently, TSV
                                        case manifests will only contain the current page of the 'Cases' Exploration
                                        tab.

Because the GDC Data Portal case manifest entries are cases, all samples from a
                                        case will be included in the cohort.

                                    <button class="btn btn-link nocap" id="file-upload-btn">
                                         Upload barcode list or case manifest
                                    </button>
                                    <input type="file" name="upload" aria-label="File Upload" id="file-upload-field"
                                           style="display: none">

                                         Verifying barcodes...

Valid Entries

                                                    Program
                                                    Case
                                                    Sample

Resulting Cohort Counts

                                                    Program
                                                    Case
                                                    Sample

Note: Invalid entries will not be included if
                                        you choose to create this cohort.

                                        {% if workbook %}
                                            <button class="btn btn-primary" data-toggle="modal"
                                                    data-target="#create-cohort-modal">Apply to Worksheet
                                            </button>
                                        {% elif create_workbook %}
                                            <button class="btn btn-primary" data-toggle="modal"
                                                    data-target="#create-cohort-modal">Apply to new Worksheet
                                            </button>
                                        {% else %}
                                            <button class="btn btn-primary" data-toggle="modal"
                                                    data-target="#create-cohort-modal">Save As New Cohort
                                            </button>
                                        {% endif %}

Invalid Entries

                                                    Program
                                                    Case
                                                    Sample

Information regarding the invalid entries

Paste a set of barcodes and programs

There is a maximum length of 10000 character for the text box. Please use the
                                        file upload option if you need to upload more barcodes than will fit in that
                                        space.

All entries must be either a valid case barcode or
                                        sample barcode. When a case barcode is provided, all
                                        samples from that case will be included in the cohort. Make a separate entry per
                                        sample if only specific samples from a case should be added to the cohort. For
                                        the following programs, prepend program prefix listed below to the barcode
                                        provided to ensure we can identify these barcodes:

                                                BEATAML1.0	BEATAML1.0-

                                                MMRF	MMRF-

                                                Family Medicine	FM-

                                                Georgetown PRP	GPRP-

                                                OHSU	OHSU-

Barcode sets must be in tab-, comma-, or newline-separated format, and there
                                        should be no headers. Values may be placed in single or double quotes, and can
                                        be in a single or multiple lines.

Example Barcode Sets

TCGA-N9-A4Q4,TCGA-N7-A4Y8-01A,'Saos-2','Hs 863.T'

"TCGA-N7-A4Y8-01A"
'Hs 863.T', TARGET-51-PAJMFS

LAMA-84
LC-1F
LCLC-103H
TARGET-10-CAAABC-60.3A
TARGET-10-CAAABD-60.2A
TARGET-10-CAAABF-60.11C

"TARGET-51-PAJLIV", Saos-2

Click the 'Verify' button to validate your entries. Any entries which are found
                                        to be invalid will be listed. You can choose to omit them and continue with
                                        cohort creation, or re-enter the set.

Barcode Entries
 (Maximum length: 10000 characters)
                                <textarea id="pasted-barcodes" aria-label="Barcode Entries"
                                          maxlength="10000"></textarea>

                                    <button class="btn btn-primary verify" title="Verify the barcode set">Verify
                                    </button>

                                         Verifying barcodes...

Valid Entries

                                                    Program
                                                    Case
                                                    Sample

Resulting Cohort Counts

                                                    Program
                                                    Case
                                                    Sample

Note: Invalid entries will not be saved if you
                                        choose to create this cohort.

                                        {% if workbook %}
                                            <button class="btn btn-primary" data-toggle="modal"
                                                    data-target="#create-cohort-modal">Apply to Worksheet
                                            </button>
                                        {% elif create_workbook %}
                                            <button class="btn btn-primary" data-toggle="modal"
                                                    data-target="#create-cohort-modal">Apply to new Worksheet
                                            </button>
                                        {% else %}
                                            <button class="btn btn-primary" data-toggle="modal"
                                                    data-target="#create-cohort-modal">Save Cohort
                                            </button>
                                        {% endif %}

Invalid Entries

                                                    Program
                                                    Cases
                                                    Sample

Information regarding the invalid entries

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Create Cohort

                    {% if workbook and worksheet %}
                        <form id="create-cohort-form" method="POST"
                              action="{% url 'save_cohort_for_existing_workbook' %}">
                        <input type="hidden" value="{{ worksheet.id }}" name="worksheet_id"/>
                        <input type="hidden" value="{{ workbook.id }}" name="workbook_id"/>
                    {% elif create_workbook %}
                        <form id="create-cohort-form" method="POST" action="{% url 'save_cohort_for_new_workbook' %}">
                    {% else %}
                        <form id="create-cohort-form" method="POST" action="{% url 'save_cohort' %}">
                    {% endif %}

                            <button type="button" class="close" data-hide="alert">×Close</button>
                            Your cohort's name contains invalid characters ().
                            Please choose another name.

                            Name:
                            <input class="form-control" type="text" id="create-cohort-name" name="name" required/>

Barcode Counts:

                                    Program
                                    Cases
                                    Samples

                        {% csrf_token %}
                        <input type="submit" value="Create Cohort" class="btn btn-primary"/>

                             Saving Cohort...

                    </form>

{% endblock %}

{% block js_file %}
    {{ block.super }}

{% endblock %}


text: require 'rgss3_spec/rgss3_spec'


text:
package com.googlecode.cqengine.resultset.stored;

import com.googlecode.cqengine.resultset.ResultSet;

/**
 * An abstract ResultSet implemented by subclass ResultSets which are stored directly in indexes.
 *

 * Extends {@link ResultSet}, adding additional methods to add and remove objects.
 *

 * This implementation is abstract.
 *
 * @author Niall Gallagher
 */
public abstract class StoredResultSet<O> extends ResultSet<O> {

    public abstract boolean add(O o);

    public abstract boolean remove(O o);

    public abstract void clear();

    public abstract boolean isEmpty();

    public abstract boolean isNotEmpty();
}


text:
<!DOCTYPE html>

  <title>Checkin</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Audio/Visual Services

Equipment Checkin

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>

Home

Checkout

Checkin

Reports

Database Administration

Checkin

			<form action="*****">

					Barcode: <input type="text" size="25" placeholder="Scan/Type Barcode" autofocus>

					Item Name: <input type="text" size="25" readonly>

					Due Date: <input type="text" size="25" readonly>

					Late? <input type="text" size="25" readonly>

					<input class="sub" type="submit" value="Submit">   <input type="reset" value="Reset Checkout Form">

			</form>

Checkin Procedure

Inspect item for damage.

Make sure all pieces are accounted for.

Scan or type in barcode information.

Take appropriate action if item is late.

Click submit button to finalize item checkin process.


text:
///
///@class LinAlg
///@brief Tuned linear algebra routines
///
///@author
///       Steven G. Parker
///       Department of Computer Science
///       University of Utah
///
///@date  November 1995
///

#ifndef Math_LinAlg_h
#define Math_LinAlg_h 1

#include <Core/Math/share.h>

#ifdef __cplusplus
extern "C" {
#endif
    SCISHARE double linalg_norm2(int n, const double* data);
    SCISHARE void linalg_mult(int n, double* result, double* a, double* b);
    SCISHARE void linalg_sub(int n, double* result, double* a, double* b);
    SCISHARE void linalg_add(int n, double* result, double* a, double* b);
    SCISHARE double linalg_dot(int n, double* a, double* b);
    SCISHARE void linalg_smadd(int n, double* result, double s, double* a, double* b);
    SCISHARE typedef double LinAlg_TriDiagRow[3];
    SCISHARE void linalg_tridiag(int n, LinAlg_TriDiagRow* data, double* c);
#ifdef __cplusplus
}
#endif

#endif