text:
#import "AWAVCapture.h"
#import "AWEncoderManager.h"

__weak static AWAVCapture *sAWAVCapture = nil;

extern void aw_rtmp_state_changed_cb_in_oc(aw_rtmp_state old_state, aw_rtmp_state new_state){
    NSLog(@"[OC] rtmp state changed from(%s), to(%s)", aw_rtmp_state_description(old_state), aw_rtmp_state_description(new_state));
    dispatch_async(dispatch_get_main_queue(), ^{
        [sAWAVCapture.stateDelegate avCapture:sAWAVCapture stateChangeFrom:old_state toState:new_state];
    });
}

@interface AWAVCapture()
//编码队列,发送队列
@property (nonatomic, strong) NSOperationQueue *encodeSampleOpQueue;
@property (nonatomic, strong) NSOperationQueue *sendSampleOpQueue;

//是否已发送了sps/pps
@property (nonatomic, unsafe_unretained) BOOL isSpsPpsAndAudioSpecificConfigSent;

//编码管理
@property (nonatomic, strong) AWEncoderManager *encoderManager;

//进入后台后,不推视频流
@property (nonatomic, unsafe_unretained) BOOL inBackground;
@end

@implementation AWAVCapture

-(NSOperationQueue *)encodeSampleOpQueue{
    if (!_encodeSampleOpQueue) {
        _encodeSampleOpQueue = [[NSOperationQueue alloc] init];
        _encodeSampleOpQueue.maxConcurrentOperationCount = 1;
    }
    return _encodeSampleOpQueue;
}

-(NSOperationQueue *)sendSampleOpQueue{
    if (!_sendSampleOpQueue) {
        _sendSampleOpQueue = [[NSOperationQueue alloc] init];
        _sendSampleOpQueue.maxConcurrentOperationCount = 1;
    }
    return _sendSampleOpQueue;
}

-(AWEncoderManager *)encoderManager{
    if (!_encoderManager) {
        _encoderManager = [[AWEncoderManager alloc] init];
        //设置编码器类型
        _encoderManager.audioEncoderType = self.audioEncoderType;
        _encoderManager.videoEncoderType = self.videoEncoderType;
    }
    return _encoderManager;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:@"please call initWithVideoConfig:audioConfig to init" reason:nil userInfo:nil];
}

-(instancetype) initWithVideoConfig:(AWVideoConfig *)videoConfig audioConfig:(AWAudioConfig *)audioConfig{
    self = [super init];
    if (self) {
        self.videoConfig = videoConfig;
        self.audioConfig = audioConfig;
        sAWAVCapture = self;
        [self onInit];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    }
    return self;
}

-(void) onInit{}

-(void) willEnterForeground{
    self.inBackground = NO;
}

-(void) didEnterBackground{
    self.inBackground = YES;
}

//修改fps
-(void) updateFps:(NSInteger) fps{
    NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    for (AVCaptureDevice *vDevice in videoDevices) {
        float maxRate = [(AVFrameRateRange *)[vDevice.activeFormat.videoSupportedFrameRateRanges objectAtIndex:0] maxFrameRate];
        if (maxRate >= fps) {
            if ([vDevice lockForConfiguration:NULL]) {
                vDevice.activeVideoMinFrameDuration = CMTimeMake(10, (int)(fps * 10));
                vDevice.activeVideoMaxFrameDuration = vDevice.activeVideoMinFrameDuration;
                [vDevice unlockForConfiguration];
            }
        }
    }
}

-(BOOL) startCaptureWithRtmpUrl:(NSString *)rtmpUrl{
    if (!rtmpUrl || rtmpUrl.length < 8) {
        NSLog(@"rtmpUrl is nil when start capture");
        return NO;
    }

    if (!self.videoConfig && !self.audioConfig) {
        NSLog(@"one of videoConfig and audioConfig must be NON-NULL");
        return NO;
    }

    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //先开启encoder
        [weakSelf.encoderManager openWithAudioConfig:weakSelf.audioConfig videoConfig:weakSelf.videoConfig];
        //再打开rtmp
        int retcode = aw_streamer_open(rtmpUrl.UTF8String, aw_rtmp_state_changed_cb_in_oc);

        if(retcode){
            weakSelf.isCapturing = YES;
        }else{
            NSLog(@"startCapture rtmpOpen error!!! retcode=%d", retcode);
            [weakSelf stopCapture];
        }
    });
    return YES;
}

-(void) stopCapture{
    self.isCapturing = NO;
    self.isSpsPpsAndAudioSpecificConfigSent = NO;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //关闭编码器
        [self.encodeSampleOpQueue cancelAllOperations];
        [self.encodeSampleOpQueue waitUntilAllOperationsAreFinished];

        [self.encoderManager close];

        //关闭流
        [self.sendSampleOpQueue cancelAllOperations];
        [self.sendSampleOpQueue waitUntilAllOperationsAreFinished];

        aw_streamer_close();
    });
}

-(void) switchCamera{}

-(void) onStopCapture{}

-(void) onStartCapture{}

-(void)setisCapturing:(BOOL)isCapturing{
    if (_isCapturing == isCapturing) {
        return;
    }

    if (!isCapturing) {
        [self onStopCapture];
    }else{
        [self onStartCapture];
    }

    _isCapturing = isCapturing;
}

-(UIView *)preview{
    if (!_preview) {
        _preview = [UIView new];
        _preview.bounds = [UIScreen mainScreen].bounds;
    }
    return _preview;
}

//发送数据
-(void) sendVideoSampleBuffer:(CMSampleBufferRef) sampleBuffer toEncodeQueue:(NSOperationQueue *) encodeQueue toSendQueue:(NSOperationQueue *) sendQueue{
    if (_inBackground) {
        return;
    }
    CFRetain(sampleBuffer);
    __weak typeof(self) weakSelf = self;
    [encodeQueue addOperationWithBlock:^{
        if (weakSelf.isCapturing) {
            aw_flv_video_tag *video_tag = [weakSelf.encoderManager.videoEncoder encodeVideoSampleBufToFlvTag:sampleBuffer];
            [weakSelf sendFlvVideoTag:video_tag toSendQueue:sendQueue];
        }
        CFRelease(sampleBuffer);
    }];
}

-(void) sendAudioSampleBuffer:(CMSampleBufferRef) sampleBuffer toEncodeQueue:(NSOperationQueue *) encodeQueue toSendQueue:(NSOperationQueue *) sendQueue{
    CFRetain(sampleBuffer);
    __weak typeof(self) weakSelf = self;
    [encodeQueue addOperationWithBlock:^{
        if (weakSelf.isCapturing) {
            aw_flv_audio_tag *audio_tag = [weakSelf.encoderManager.audioEncoder encodeAudioSampleBufToFlvTag:sampleBuffer];
            [weakSelf sendFlvAudioTag:audio_tag toSendQueue:sendQueue];
        }
        CFRelease(sampleBuffer);
    }];
}

-(void) sendVideoYuvData:(NSData *)yuvData toEncodeQueue:(NSOperationQueue *) encodeQueue toSendQueue:(NSOperationQueue *) sendQueue{
    if (_inBackground) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [encodeQueue addOperationWithBlock:^{
        if (weakSelf.isCapturing) {
            NSData *rotatedData = [weakSelf.encoderManager.videoEncoder rotateNV12Data:yuvData];
            aw_flv_video_tag *video_tag = [weakSelf.encoderManager.videoEncoder encodeYUVDataToFlvTag:rotatedData];
            [weakSelf sendFlvVideoTag:video_tag toSendQueue:sendQueue];
        }
    }];
}

-(void) sendAudioPcmData:(NSData *)pcmData toEncodeQueue:(NSOperationQueue *) encodeQueue toSendQueue:(NSOperationQueue *) sendQueue{
    __weak typeof(self) weakSelf = self;
    [encodeQueue addOperationWithBlock:^{
        if (weakSelf.isCapturing) {
            aw_flv_audio_tag *audio_tag = [weakSelf.encoderManager.audioEncoder encodePCMDataToFlvTag:pcmData];
            [weakSelf sendFlvAudioTag:audio_tag toSendQueue:sendQueue];
        }
    }];
}

-(void) sendFlvVideoTag:(aw_flv_video_tag *)video_tag toSendQueue:(NSOperationQueue *) sendQueue{
    if (_inBackground) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    if (video_tag) {
        [sendQueue addOperationWithBlock:^{
            if(weakSelf.isCapturing){
                if (!weakSelf.isSpsPpsAndAudioSpecificConfigSent) {
                    [weakSelf sendSpsPpsAndAudioSpecificConfigTagToSendQueue:sendQueue];
                    free_aw_flv_video_tag((aw_flv_video_tag **)&video_tag);
                }else{
                    aw_streamer_send_video_data(video_tag);
                }
            }else{
                free_aw_flv_video_tag((aw_flv_video_tag **)(&video_tag));
            }
        }];
    }
}

-(void) sendFlvAudioTag:(aw_flv_audio_tag *)audio_tag toSendQueue:(NSOperationQueue *) sendQueue{
    __weak typeof(self) weakSelf = self;
    if(audio_tag){
        [sendQueue addOperationWithBlock:^{
            if(weakSelf.isCapturing){
                if (!weakSelf.isSpsPpsAndAudioSpecificConfigSent) {
                    [weakSelf sendSpsPpsAndAudioSpecificConfigTagToSendQueue:sendQueue];
                    free_aw_flv_audio_tag((aw_flv_audio_tag **)&audio_tag);
                }else{
                    aw_streamer_send_audio_data(audio_tag);
                }
            }else{
                free_aw_flv_audio_tag((aw_flv_audio_tag **)&audio_tag);
            }
        }];
    }
}

-(void) sendSpsPpsAndAudioSpecificConfigTagToSendQueue:(NSOperationQueue *) sendQueue{
    if (self.isSpsPpsAndAudioSpecificConfigSent) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [sendQueue addOperationWithBlock:^{
        if (!weakSelf.isCapturing || weakSelf.isSpsPpsAndAudioSpecificConfigSent) {
            return;
        }
        //video sps pps tag
        aw_flv_video_tag *spsPpsTag = [weakSelf.encoderManager.videoEncoder createSpsPpsFlvTag];
        if (spsPpsTag) {
            aw_streamer_send_video_sps_pps_tag(spsPpsTag);
        }
        //audio specific config tag
        aw_flv_audio_tag *audioSpecificConfigTag = [weakSelf.encoderManager.audioEncoder createAudioSpecificConfigFlvTag];
        if (audioSpecificConfigTag) {
            aw_streamer_send_audio_specific_config_tag(audioSpecificConfigTag);
        }
        weakSelf.isSpsPpsAndAudioSpecificConfigSent = spsPpsTag || audioSpecificConfigTag;

        aw_log("[D] is sps pps and audio sepcific config sent=%d", weakSelf.isSpsPpsAndAudioSpecificConfigSent);
    }];
}

//使用rtmp协议发送数据
-(void) sendVideoSampleBuffer:(CMSampleBufferRef) sampleBuffer{
    [self sendVideoSampleBuffer:sampleBuffer toEncodeQueue:self.encodeSampleOpQueue toSendQueue:self.sendSampleOpQueue];
}

-(void) sendAudioSampleBuffer:(CMSampleBufferRef) sampleBuffer{
    [self sendAudioSampleBuffer:sampleBuffer toEncodeQueue:self.encodeSampleOpQueue toSendQueue:self.sendSampleOpQueue];
}

-(void) sendVideoYuvData:(NSData *)videoData{
    [self sendVideoYuvData:(NSData *)videoData toEncodeQueue:self.encodeSampleOpQueue toSendQueue:self.sendSampleOpQueue];
}
-(void) sendAudioPcmData:(NSData *)audioData{
    [self sendAudioPcmData:audioData toEncodeQueue:self.encodeSampleOpQueue toSendQueue:self.sendSampleOpQueue];
}

-(void) sendFlvVideoTag:(aw_flv_video_tag *)flvVideoTag{
    [self sendFlvVideoTag:flvVideoTag toSendQueue:self.sendSampleOpQueue];
}

-(void) sendFlvAudioTag:(aw_flv_audio_tag *)flvAudioTag{
    [self sendFlvAudioTag:flvAudioTag toSendQueue:self.sendSampleOpQueue];
}

-(NSString *)captureSessionPreset{
    NSString *captureSessionPreset = nil;
    if(self.videoConfig.width == 480 && self.videoConfig.height == 640){
        captureSessionPreset = AVCaptureSessionPreset640x480;
    }else if(self.videoConfig.width == 540 && self.videoConfig.height == 960){
        captureSessionPreset = AVCaptureSessionPresetiFrame960x540;
    }else if(self.videoConfig.width == 720 && self.videoConfig.height == 1280){
        captureSessionPreset = AVCaptureSessionPreset1280x720;
    }
    return captureSessionPreset;
}

@end


text:
layout: post
date: 2005-09-20
time: "09:00:00"
authors: ["Greg Wilson"]
title: "Day 9"
category: ["University of Toronto"]
---

Week two of Software Carpentry, and things are starting to settle down.  There are now 93 (!) people signed up for the course:

U of T
Elsewhere

Auditing
18
21

Enrolled
25

Unknown
29

Of those actually at the University of Toronto (as opposed to the

local hospitals—a few radiologists are sitting in) the breakdown

is:

16
Computer Science

14
Physics

9
Civil Engineering

Mechanical and Industrial Engineering

5
Biochemistry

Institute for Aerospace Studies

2
Institute of Medical Science

Mathematics

1
Astronomy

Biomaterials and Biomedical Engineering

Botany

Geology

Medical Biophysics

Zoology

Non-degree student

This week's lecture went much more smoothly than last week's, in part because we were in a larger room, with seating for everyone, and in part because the content was an introduction to Python, which I've given more times than I can count.  There were still some glitches in the slides, though: a few things were out of order, and I really do need to choose more concrete examples.  33 students have completed the first exercise, which is already more than I'd expected—I'm feeling uncharacteristically optimistic right now ;-)

The past week has also CSC49X, the fourth-year Computer Science project course.  23 students are working on 10 different projects (24 and 11 respectively, if you count Sean Dawson's paid-but-not-for-course-credit work on a sequence diagram debugger plugin for Eclipse).  DrProject (our Trac-derived project management system) is holding up so far, and we're almost finished setting it up for two other courses to use this term as well.  Not bad for Day 9 of term; not bad at all.

redpajama_set_name: RedPajamaGithub


text:
Client library for LanguageTool API

## Installation and Usage
```bash
npm install --save @datafire/languagetool
```
```js
let languagetool = require('@datafire/languagetool').create();

.then(data => {
  console.log(data);
});
```

## Description

Check texts for style and grammar issues with LanguageTool. Please consider the following default limitations:

your daily request limit depending on your plan
maximum number of requests per minute: 20 (free) / 80 (Premium)
maximum number of characters per minute: 75,000 (free) / 300,000 (Premium)
maximum number of characters per request: 20,000 (free) / 40,000 (Premium)
for the free version, also consider the limitations documented here
Note: any parameters or outputs not part of this documentation are internal and must not be relied on
 Need more generous limits? Just contact us.

## Actions

### check.post
The main feature - check a text with LanguageTool for possible style and grammar issues.

```js
languagetool.check.post({
  "language": ""
}, context)
```

#### Input
* input `object`
  * text `string`: The text to be checked. This or 'data' is required.
  * data `string`: The text to be checked, given as a JSON document that specifies what's text and what's markup. This or 'text' is required. Markup will be ignored when looking for errors. Example text:
A <b>test</b>
JSON for the example text:
{"annotation":[
  * language **required** `string`: A language code like `en-US`, `de-DE`, `fr`, or `auto` to guess the language automatically (see `preferredVariants` below). For languages with variants (English, German, Portuguese) spell checking will only be activated when you specify the variant, e.g. `en-GB` instead of just `en`.
  * username `string`: Set to get Premium API access: Your username/email as used to log in at languagetool.org.
  * apiKey `string`: Set to get Premium API access: your API key
  * dicts `string`: Comma-separated list of dictionaries to include words from; uses special default dictionary if this is unset
  * motherTongue `string`: A language code of the user's native language, enabling false friends checks for some language pairs.
  * preferredVariants `string`: Comma-separated list of preferred language variants. The language detector used with `language=auto` can detect e.g. English, but it cannot decide whether British English or American English is used. Thus this parameter can be used to specify the preferred variants like `en-GB` and `de-AT`. Only available with `language=auto`. You should set variants for at least German and English, as otherwise the spell checking will not work for those, as no spelling dictionary can be selected for just `en` or `de`.
  * enabledRules `string`: IDs of rules to be enabled, comma-separated
  * disabledRules `string`: IDs of rules to be disabled, comma-separated
  * enabledCategories `string`: IDs of categories to be enabled, comma-separated
  * disabledCategories `string`: IDs of categories to be disabled, comma-separated
  * enabledOnly `boolean`: If true, only the rules and categories whose IDs are specified with `enabledRules` or `enabledCategories` are enabled.
  * level `string` (values: default, picky): If set to `picky`, additional rules will be activated, i.e. rules that you might only find useful when checking formal text.

#### Output
* output `object`
  * language `object`: The language used for checking the text.
    * code **required** `string`: ISO 639-1 code like 'en', 'en-US', or 'ca-ES-valencia'
    * detectedLanguage **required** `object`: The automatically detected text language (might be different from the language actually used for checking).
      * code **required** `string`: ISO 639-1 code like 'en', 'en-US', or 'ca-ES-valencia'.
      * name **required** `string`: Language name like 'French' or 'English (US)'.
    * name **required** `string`: Language name like 'French' or 'English (US)'.
  * matches `array`
    * items `object`
      * context **required** `object`
        * length **required** `integer`: The length of the error in characters in the context.
        * offset **required** `integer`: The 0-based character offset of the error in the context text.
        * text **required** `string`: Context of the error, i.e. the error and some text to the left and to the left.
      * length **required** `integer`: The length of the error in characters.
      * message **required** `string`: Message about the error displayed to the user.
      * offset **required** `integer`: The 0-based character offset of the error in the text.
      * replacements **required** `array`: Replacements that might correct the error. The array can be empty, in this case there is no suggested replacement.
        * items `object`
          * value `string`: the replacement string
      * rule `object`
        * category **required** `object`
          * id `string`: A category's identifier that's unique for this language.
          * name `string`: A short description of the category.
        * description **required** `string`
        * id **required** `string`: An rule's identifier that's unique for this language.
        * issueType `string`: The Localization Quality Issue Type. This is not defined for all languages, in which case it will always be 'Uncategorized'.
        * subId `string`: An optional sub identifier of the rule, used when several rules are grouped.
        * urls `array`: An optional array of URLs with a more detailed description of the error.
          * items `object`
      * sentence **required** `string`: The sentence the error occurred in (since LanguageTool 4.0 or later)
      * shortMessage `string`: An optional shorter version of 'message'.
  * software `object`
    * apiVersion **required** `integer`: Version of this API response. We don't expect to make incompatible changes, so this can also be increased for newly added fields.
    * buildDate **required** `string`: Date when the software was built, e.g. '2016-05-25'.
    * name **required** `string`: Usually 'LanguageTool'.
    * premium `boolean`: true if you're using a Premium account with all the premium text checks (since LanguageTool 4.2)
    * status `string`: An optional warning, e.g. when the API format is not stable.
    * version **required** `string`: A version string like '3.3' or '3.4-SNAPSHOT'.

### languages.get
Get a list of supported languages.

```js
languagetool.languages.get(null, context)
```

#### Input
*This action has no parameters*

#### Output
* output `array`
  * items `object`
    * code **required** `string`: a language code like 'en'
    * longCode **required** `string`: a language code like 'en-US' or 'ca-ES-valencia'
    * name **required** `string`: a language name like 'French' or 'English (Australia)'

### words.get
List words in the user's personal dictionaries.

```js
languagetool.words.get({
  "username": "",
  "apiKey": ""
}, context)
```

#### Input
* input `object`
  * offset `integer`: Offset of where to start in the list of words. Defaults to 0.
  * limit `integer`: Maximum number of words to return. Defaults to 10.
  * username **required** `string`: Your username as used to log in at languagetool.org.
  * apiKey **required** `string`: Your API key.
  * dicts `string`: Comma-separated list of dictionaries to include words from; uses special default dictionary if this is unset

#### Output
* output `object`
  * words `array`: array of words
    * items `string`

### words.add.post
Add a word to one of the user's personal dictionaries. Please note that this feature is considered to be used for personal dictionaries which typically contain not more than a few hundred items per user. Adding more can have adverse effects on performance for every single text check. If this becomes an issue for you, contact us. Experimental user dictionary caching can be enabled by us on a per-account basis.

```js
languagetool.words.add.post({
  "word": "",
  "username": "",
  "apiKey": ""
}, context)
```

#### Input
* input `object`
  * word **required** `string`: The word to be added. Must not be a phrase, i.e. cannot contain white space. The word is added to a global dictionary that applies to all languages.
  * username **required** `string`: Your username as used to log in at languagetool.org.
  * apiKey **required** `string`: Your API key.
  * dict `string`: Name of the dictionary to add the word to; non-existent dictionaries are created after calling this; if unset, adds to special default dictionary

#### Output
* output `object`
  * added `boolean`: true if the word has been added. false means the word hasn't been added because it had been added before.

### words.delete.post
Remove a word from one of the user's personal dictionaries.

```js
languagetool.words.delete.post({
  "word": "",
  "username": "",
  "apiKey": ""
}, context)
```

#### Input
* input `object`
  * word **required** `string`: The word to be removed.
  * username **required** `string`: Your username as used to log in at languagetool.org.
  * apiKey **required** `string`: Your API key.
  * dict `string`: Name of the dictionary to remove the word from; if the dictionary is empty upon calling this, it is deleted; if unset, removes from special default dictionary

#### Output
* output `object`
  * deleted `boolean`: true if the word has been removed. false means the word hasn't been removed because it was not in the dictionary.

## Definitions

*This integration has no definitions*


text:
using System.Collections.Generic;
using System.Linq;
using Moon.AspNetCore.OData;
using Moon.OData;

// ReSharper disable once CheckNamespace

namespace Microsoft.Extensions.DependencyInjection
{
    public static class MvcBuilderExtensions
    {
        /// <summary>
        /// Adds services necessary to bind <see cref="ODataOptions{TEntity}" /> as an action method parameter.
        /// </summary>
        /// <param name="builder">The ASP.NET MVC builder.</param>
        public static IMvcBuilder AddOData(this IMvcBuilder builder)
        {
            return builder.AddOData(Enumerable.Empty<IPrimitiveType>());
        }

        /// <summary>
        /// Adds services necessary to bind <see cref="ODataOptions{TEntity}" /> as an action method parameter.
        /// </summary>
        /// <param name="builder">The ASP.NET MVC builder.</param>
        /// <param name="primitiveTypes">An enumeration of additional primitive types.</param>
        public static IMvcBuilder AddOData(this IMvcBuilder builder, IEnumerable<IPrimitiveType> primitiveTypes)
        {
            return builder.AddOData(primitiveTypes, true);
        }

        /// <summary>
        /// Adds services necessary to bind <see cref="ODataOptions{TEntity}" /> as an action method parameter.
        /// </summary>
        /// <param name="builder">The ASP.NET MVC builder.</param>
        /// <param name="isCaseSensitive">Indicates whether the property binding is case sensitive.</param>
        public static IMvcBuilder AddOData(this IMvcBuilder builder, bool isCaseSensitive)
        {
            return builder.AddOData(Enumerable.Empty<IPrimitiveType>(), isCaseSensitive);
        }

        /// <summary>
        /// Adds services necessary to bind <see cref="ODataOptions{TEntity}" /> as an action method parameter.
        /// </summary>
        /// <param name="builder">The ASP.NET MVC builder.</param>
        /// <param name="primitiveTypes">An enumeration of additional primitive types.</param>
        /// <param name="isCaseSensitive">Indicates whether the property binding is case sensitive.</param>
        public static IMvcBuilder AddOData(this IMvcBuilder builder, IEnumerable<IPrimitiveType> primitiveTypes, bool isCaseSensitive)
        {
            return builder.AddMvcOptions(o => o.ModelBinderProviders.Insert(0, new ODataOptionsModelBinderProvider(primitiveTypes, isCaseSensitive)));
        }
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types'
import Typography from 'material-ui/Typography';
import Paper from 'material-ui/Paper';
import Select from 'material-ui/Select';
import {MenuItem} from 'material-ui/Menu';

const style = {
    height: 75,
    width:  200,
    margin: 20,
    textAlign: 'center',
    display: 'inline-block',
};

export default class JoystickMotorSelect extends React.Component {

    handleMotorChange = event => {
        const {button, config} = this.props;
        const speed = config.speedForButton(button);
        const direction = config.directionForButton(button);
        this.updateParent(event.target.value, speed, direction);
    };

    handleSpeedChange(event) {
        const {button, config} = this.props;
        const direction = config.directionForButton(button);
        const motor = config.motorForButton(button);
        this.updateParent(motor, event.target.value, direction);
    }

    handleDirectionChange(event) {
        const {button, config} = this.props;
        const speed = config.speedForButton(button);
        const motor = config.motorForButton(button);
        this.updateParent(motor, speed, event.target.value);
    }

    updateParent(motor, speed, direction) {
        this.props.callback(this.props.button, motor, speed, direction)
    }

    render() {
        const {button, config} = this.props;
        const speed = config.speedForButton(button);
        const direction = config.directionForButton(button);
        const motor = config.motorForButton(button);

        return (
            <Paper style={style}>

                <Typography type="subheading" color="secondary">
                    {button}
                </Typography>
                <Select
                    value={motor}
                    onChange={this.handleMotorChange}
                >
                    <MenuItem value={""}>None</MenuItem>
                    <MenuItem value={"A"}>A</MenuItem>
                    <MenuItem value={"B"}>B</MenuItem>
                    <MenuItem value={"C"}>C</MenuItem>
                    <MenuItem value={"D"}>D</MenuItem>
                    <MenuItem value={"S"}>STOP</MenuItem>
                </Select>
                <Select
                    value={speed}
                    onChange={(e) => this.handleSpeedChange(e)}
                >
                    <MenuItem value={0}>0</MenuItem>
                    <MenuItem value={10}>10</MenuItem>
                    <MenuItem value={20}>20</MenuItem>
                    <MenuItem value={30}>30</MenuItem>
                    <MenuItem value={40}>40</MenuItem>
                    <MenuItem value={50}>50</MenuItem>
                    <MenuItem value={60}>60</MenuItem>
                    <MenuItem value={70}>70</MenuItem>
                    <MenuItem value={80}>80</MenuItem>
                    <MenuItem value={90}>90</MenuItem>
                    <MenuItem value={100}>100</MenuItem>
                </Select>
                <Select
                    value={direction}
                    onChange={(e) => this.handleDirectionChange(e)}
                >
                    <MenuItem value={"f"}>fwd</MenuItem>
                    <MenuItem value={"r"}>rvs</MenuItem>
                </Select>

            </Paper>
        )
    }
}

JoystickMotorSelect.propTypes = {
    button: PropTypes.string.isRequired,
    config: PropTypes.object.isRequired,
    callback: PropTypes.func.isRequired
}


text:
from distutils.version import StrictVersion
import json
import os
import time
import logging

import boto3
from botocore.config import Config
import botocore

from ray.ray_constants import BOTO_MAX_RETRIES

logger = logging.getLogger(__name__)

RAY = "ray-autoscaler"
DEFAULT_RAY_INSTANCE_PROFILE = RAY + "-v1"
DEFAULT_RAY_IAM_ROLE = RAY + "-v1"
SECURITY_GROUP_TEMPLATE = RAY + "-{}"

DEFAULT_AMI_NAME = "AWS Deep Learning AMI (Ubuntu 18.04) V26.0"

# Obtained from https://aws.amazon.com/marketplace/pp/B07Y43P7X5 on 1/20/2020.
DEFAULT_AMI = {
    "us-east-2": "ami-0bb99846db2df6e38",  # US East (Ohio)
    "us-east-1": "ami-0698bcaf8bd9ef56d",  # US East (N. Virginia)
    "us-west-1": "ami-074c29e29c500f623",  # US West (N. California)
    "us-west-2": "ami-010a96c958f9ee5cf",  # US West (Oregon)
    "ca-central-1": "ami-086b864eabf2da9b1",  # Canada (Central)
    "eu-central-1": "ami-0dcdcc4bc9e75005f",  # EU (Frankfurt)
    "eu-west-1": "ami-071e6d171b20431fb",  # EU (Ireland)
    "eu-west-2": "ami-0470e741c969b62fc",  # EU (London)
    "eu-west-3": "ami-064f884d98b90a453",  # EU (Paris)
    "sa-east-1": "ami-054e94fd9b444491d",  # SA (Sao Paulo)
}

assert StrictVersion(boto3.__version__) >= StrictVersion("1.4.8"), \
    "Boto3 version >= 1.4.8 required, try `pip install -U boto3`"

def key_pair(i, region):
    """Returns the ith default (aws_key_pair_name, key_pair_path)."""
    if i == 0:
        return ("{}_{}".format(RAY, region),
                os.path.expanduser("~/.ssh/{}_{}.pem".format(RAY, region)))
    return ("{}_{}_{}".format(RAY, i, region),
            os.path.expanduser("~/.ssh/{}_{}_{}.pem".format(RAY, i, region)))

# Suppress excessive connection dropped logs from boto
logging.getLogger("botocore").setLevel(logging.WARNING)

def bootstrap_aws(config):
    # The head node needs to have an IAM role that allows it to create further
    # EC2 instances.
    config = _configure_iam_role(config)

    # Configure SSH access, using an existing key pair if possible.
    config = _configure_key_pair(config)

    # Pick a reasonable subnet if not specified by the user.
    config = _configure_subnet(config)

    # Cluster workers should be in a security group that permits traffic within
    # the group, and also SSH access from outside.
    config = _configure_security_group(config)

    # Provide a helpful message for missing AMI.
    _check_ami(config)

    return config

def _configure_iam_role(config):
    if "IamInstanceProfile" in config["head_node"]:
        return config

    profile = _get_instance_profile(DEFAULT_RAY_INSTANCE_PROFILE, config)

    if profile is None:
        logger.info("_configure_iam_role: "
                    "Creating new instance profile {}".format(
                        DEFAULT_RAY_INSTANCE_PROFILE))
        client = _client("iam", config)
        client.create_instance_profile(
            InstanceProfileName=DEFAULT_RAY_INSTANCE_PROFILE)
        profile = _get_instance_profile(DEFAULT_RAY_INSTANCE_PROFILE, config)
        time.sleep(15)  # wait for propagation

    assert profile is not None, "Failed to create instance profile"

    if not profile.roles:
        role = _get_role(DEFAULT_RAY_IAM_ROLE, config)
        if role is None:
            logger.info("_configure_iam_role: "
                        "Creating new role {}".format(DEFAULT_RAY_IAM_ROLE))
            iam = _resource("iam", config)
            iam.create_role(
                RoleName=DEFAULT_RAY_IAM_ROLE,
                AssumeRolePolicyDocument=json.dumps({
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {
                                "Service": "ec2.amazonaws.com"
                            },
                            "Action": "sts:AssumeRole",
                        },
                    ],
                }))
            role = _get_role(DEFAULT_RAY_IAM_ROLE, config)
            assert role is not None, "Failed to create role"
        role.attach_policy(
            PolicyArn="arn:aws:iam::aws:policy/AmazonEC2FullAccess")
        role.attach_policy(
            PolicyArn="arn:aws:iam::aws:policy/AmazonS3FullAccess")
        profile.add_role(RoleName=role.name)
        time.sleep(15)  # wait for propagation

    logger.info("_configure_iam_role: "
                "Role not specified for head node, using {}".format(
                    profile.arn))
    config["head_node"]["IamInstanceProfile"] = {"Arn": profile.arn}

    return config

def _configure_key_pair(config):
    if "ssh_private_key" in config["auth"]:
        assert "KeyName" in config["head_node"]
        assert "KeyName" in config["worker_nodes"]
        return config

    ec2 = _resource("ec2", config)

    # Try a few times to get or create a good key pair.
    MAX_NUM_KEYS = 30
    for i in range(MAX_NUM_KEYS):
        key_name, key_path = key_pair(i, config["provider"]["region"])
        key = _get_key(key_name, config)

        # Found a good key.
        if key and os.path.exists(key_path):
            break

        # We can safely create a new key.
        if not key and not os.path.exists(key_path):
            logger.info("_configure_key_pair: "
                        "Creating new key pair {}".format(key_name))
            key = ec2.create_key_pair(KeyName=key_name)
            with open(key_path, "w") as f:
                f.write(key.key_material)
            os.chmod(key_path, 0o600)
            break

    if not key:
        raise ValueError(
            "No matching local key file for any of the key pairs in this "
            "account with ids from 0..{}. ".format(key_name) +
            "Consider deleting some unused keys pairs from your account.")

    assert os.path.exists(key_path), \
        "Private key file {} not found for {}".format(key_path, key_name)

    logger.info("_configure_key_pair: "
                "KeyName not specified for nodes, using {}".format(key_name))

    config["auth"]["ssh_private_key"] = key_path
    config["head_node"]["KeyName"] = key_name
    config["worker_nodes"]["KeyName"] = key_name

    return config

def _configure_subnet(config):
    ec2 = _resource("ec2", config)
    use_internal_ips = config["provider"].get("use_internal_ips", False)
    subnets = sorted(
        (s for s in ec2.subnets.all() if s.state == "available" and (
            use_internal_ips or s.map_public_ip_on_launch)),
        reverse=True,  # sort from Z-A
        key=lambda subnet: subnet.availability_zone)
    if not subnets:
        raise Exception(
            "No usable subnets found, try manually creating an instance in "
            "your specified region to populate the list of subnets "
            "and trying this again. Note that the subnet must map public IPs "
            "on instance launch unless you set 'use_internal_ips': True in "
            "the 'provider' config.")
    if "availability_zone" in config["provider"]:
        azs = config["provider"]["availability_zone"].split(",")
        subnets = [s for s in subnets if s.availability_zone in azs]
        if not subnets:
            raise Exception(
                "No usable subnets matching availability zone {} "
                "found. Choose a different availability zone or try "
                "manually creating an instance in your specified region "
                "to populate the list of subnets and trying this again.".
                format(config["provider"]["availability_zone"]))

    subnet_ids = [s.subnet_id for s in subnets]
    subnet_descr = [(s.subnet_id, s.availability_zone) for s in subnets]
    if "SubnetIds" not in config["head_node"]:
        config["head_node"]["SubnetIds"] = subnet_ids
        logger.info("_configure_subnet: "
                    "SubnetIds not specified for head node, using {}".format(
                        subnet_descr))

    if "SubnetIds" not in config["worker_nodes"]:
        config["worker_nodes"]["SubnetIds"] = subnet_ids
        logger.info("_configure_subnet: "
                    "SubnetId not specified for workers,"
                    " using {}".format(subnet_descr))

    return config

def _configure_security_group(config):
    if "SecurityGroupIds" in config["head_node"] and \
            "SecurityGroupIds" in config["worker_nodes"]:
        return config  # have user-defined groups

    group_name = SECURITY_GROUP_TEMPLATE.format(config["cluster_name"])
    vpc_id = _get_vpc_id_or_die(config, config["worker_nodes"]["SubnetIds"][0])
    security_group = _get_security_group(config, vpc_id, group_name)

    if security_group is None:
        logger.info("_configure_security_group: "
                    "Creating new security group {}".format(group_name))
        client = _client("ec2", config)
        client.create_security_group(
            Description="Auto-created security group for Ray workers",
            GroupName=group_name,
            VpcId=vpc_id)
        security_group = _get_security_group(config, vpc_id, group_name)
        assert security_group, "Failed to create security group"

    if not security_group.ip_permissions:
        security_group.authorize_ingress(IpPermissions=[{
            "FromPort": -1,
            "ToPort": -1,
            "IpProtocol": "-1",
            "UserIdGroupPairs": [{
                "GroupId": security_group.id
            }]
        }, {
            "FromPort": 22,
            "ToPort": 22,
            "IpProtocol": "TCP",
            "IpRanges": [{
                "CidrIp": "0.0.0.0/0"
            }]
        }])

    if "SecurityGroupIds" not in config["head_node"]:
        logger.info(
            "_configure_security_group: "
            "SecurityGroupIds not specified for head node, using {}".format(
                security_group.group_name))
        config["head_node"]["SecurityGroupIds"] = [security_group.id]

    if "SecurityGroupIds" not in config["worker_nodes"]:
        logger.info(
            "_configure_security_group: "
            "SecurityGroupIds not specified for workers, using {}".format(
                security_group.group_name))
        config["worker_nodes"]["SecurityGroupIds"] = [security_group.id]

    return config

def _check_ami(config):
    """Provide helpful message for missing ImageId for node configuration."""

    region = config["provider"]["region"]
    default_ami = DEFAULT_AMI.get(region)
    if not default_ami:
        # If we do not provide a default AMI for the given region, noop.
        return

    if config["head_node"].get("ImageId", "").lower() == "latest_dlami":
        config["head_node"]["ImageId"] = default_ami
        logger.info("_check_ami: head node ImageId is 'latest_dlami'. "
                    "Using '{ami_id}', which is the default {ami_name} "
                    "for your region ({region}).".format(
                        ami_id=default_ami,
                        ami_name=DEFAULT_AMI_NAME,
                        region=region))

    if config["worker_nodes"].get("ImageId", "").lower() == "latest_dlami":
        config["worker_nodes"]["ImageId"] = default_ami
        logger.info("_check_ami: worker nodes ImageId is 'latest_dlami'. "
                    "Using '{ami_id}', which is the default {ami_name} "
                    "for your region ({region}).".format(
                        ami_id=default_ami,
                        ami_name=DEFAULT_AMI_NAME,
                        region=region))

def _get_vpc_id_or_die(config, subnet_id):
    ec2 = _resource("ec2", config)
    subnet = list(
        ec2.subnets.filter(Filters=[{
            "Name": "subnet-id",
            "Values": [subnet_id]
        }]))
    assert len(subnet) == 1, "Subnet not found"
    subnet = subnet[0]
    return subnet.vpc_id

def _get_security_group(config, vpc_id, group_name):
    ec2 = _resource("ec2", config)
    existing_groups = list(
        ec2.security_groups.filter(Filters=[{
            "Name": "vpc-id",
            "Values": [vpc_id]
        }]))
    for sg in existing_groups:
        if sg.group_name == group_name:
            return sg

def _get_role(role_name, config):
    iam = _resource("iam", config)
    role = iam.Role(role_name)
    try:
        role.load()
        return role
    except botocore.exceptions.ClientError as exc:
        if exc.response.get("Error", {}).get("Code") == "NoSuchEntity":
            return None
        else:
            raise exc

def _get_instance_profile(profile_name, config):
    iam = _resource("iam", config)
    profile = iam.InstanceProfile(profile_name)
    try:
        profile.load()
        return profile
    except botocore.exceptions.ClientError as exc:
        if exc.response.get("Error", {}).get("Code") == "NoSuchEntity":
            return None
        else:
            raise exc

def _get_key(key_name, config):
    ec2 = _resource("ec2", config)
    for key in ec2.key_pairs.filter(Filters=[{
            "Name": "key-name",
            "Values": [key_name]
    }]):
        if key.name == key_name:
            return key

def _client(name, config):
    boto_config = Config(retries={"max_attempts": BOTO_MAX_RETRIES})
    return boto3.client(name, config["provider"]["region"], config=boto_config)

def _resource(name, config):
    boto_config = Config(retries={"max_attempts": BOTO_MAX_RETRIES})
    return boto3.resource(
        name, config["provider"]["region"], config=boto_config)


text:
package org.thingsboard.server.cache;

public interface TbCacheTransaction<K, V> {

    void putIfAbsent(K key, V value);

    boolean commit();

    void rollback();

}


text:
using namespace std;

bool contains(vector<int> keys, int key){
    for(int i = 0; i < keys.size(); i++){
        if(keys[i] == key){
            return true;
        }
    }
    return false;
}

int charToInt(char *a){
    int result = 0;
    for(int i = 0; i < strlen(a); ++i){
        result *= 10;
        result += (int)a[i] - '0';
    }
    return result;
}

//./main [k hashfunctions] [p familyhash] [m familyhash] [n iterations] [maximum n] [T tableSize]
//./main [k hashfunctions] [p famylyhash] [m familyHash] [dir keys] [T tableSize]

int main(int argc, char *argv[]){
    int numberHashFunc;
    int pFamily;
    int mFamily;
    int nKeys;
    int maxN;
    int sizeT;
    if(argc == 7){
        //./main [k hashfunctions] [p familyhash] [m familyhash] [n iterations] [maximum n] [T tableSize]
        numberHashFunc = charToInt(argv[1]);
        pFamily = charToInt(argv[2]);
        mFamily = charToInt(argv[3]);
        nKeys = charToInt(argv[4]);
        maxN = charToInt(argv[5]);
        sizeT = charToInt(argv[6]);

    }else if(argc == 6){
        //./main [p hash] [m hash] [n iterations] [max maximum] [T tableSize]
        pFamily = charToInt(argv[1]);
        mFamily = charToInt(argv[2]);
        nKeys = charToInt(argv[3]);
        maxN = charToInt(argv[4]);
        sizeT = charToInt(argv[5]);
        numberHashFunc = ((sizeT*9)/(nKeys*13));
        if(numberHashFunc <= 1) numberHashFunc = 2;
        cout << "Calculating optimal number of hash functions = " << numberHashFunc << endl;
    }else{
        exit(0);
    }
    srand(time(NULL));
    Cuckoo_Hashing cuckoo(sizeT);
    cout << numberHashFunc << " : " << pFamily << " : ";
    cout << mFamily << " : " << nKeys << " : ";
    cout << maxN << " : " << sizeT << endl;

    cuckoo.setFamilyHashFunc(pFamily, mFamily);
    cout << "Creating hash functions..." << endl;
    for(int i = 0; i < numberHashFunc; ++i){
        cuckoo.generateHashFunc();
    }
    vector<int> keys;

    int n_inserts = 0;
    int n_iterations = 0;

    cout << "Entring to loop filter..." << endl;
    while(n_iterations < nKeys){
        int key = rand() % maxN + 1; // generates number in the range 1..maxN
        //cout << "     key: " << key << endl;
        if(!(cuckoo.contains(key))){
            keys.push_back(key);
            cuckoo.insertValue(key);
            ++n_inserts;
        }
        //cuckoo.printFilter(); //imprimir la taula del filtre de cuckoo
        ++n_iterations;
    }
    cuckoo.printFilter(); //imprimir la taula del filtre de cuckoo
    cout << "Number of inserts: " << n_inserts << endl;
    cout << "Total iterations: " << n_iterations << endl;
    cout << "Inserted keys: ";
    for(int i = 0; i < keys.size(); ++i){
        cout << keys[i] << " , ";
    }
    cout << endl << "Querys: ";
    int entry;
    while(cin >> entry){
        if(cuckoo.contains(entry)){
            cout << "On the filter!" << endl;
        }else{
            cout << "Not on filter" << endl;
        }
    }
}


text:
package me.magicall.db.meta;

import me.magicall.coll.ElementTransformerUtil;
import me.magicall.util.kit.Kits;

import java.util.List;

public class BaseDbMetaWithMultiColumns extends BaseDbMeta {
	protected transient List<String> columnNames;

	public List<String> getColumnNames() {
		if (columnNames == null) {
			columnNames = Kits.LIST.transform(getList(), ElementTransformerUtil.TO_NAME);
		}
		return columnNames;
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>knife diff — chef-client Man Pages</title>

    <link rel="stylesheet" href="_static/guide.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

knife diff¶

The knife diff subcommand is used to compare the differences between files and directories on the Chef server and in the chef-repo. For example, to compare files on the Chef server prior to an uploading or downloading files using the <tt class="docutils literal">knife download</tt> and <tt class="docutils literal">knife upload</tt> subcommands, or to ensure that certain files in multiple production environments are the same. This subcommand is similar to the <tt class="docutils literal">git diff</tt> command that can be used to diff what is in the chef-repo with what is synced to a git repository.

Syntax¶

This subcommand has the following syntax:

$ knife diff [PATTERN...] (options)

Options¶

Note

Review the list of common options available to this (and all) knife subcommands and plugins.

This subcommand has the following options:

<tt class="docutils literal">--chef-repo-path PATH</tt>

The path to the chef-repo. This setting will override the default path to the chef-repo. Default: same value as specified by <tt class="docutils literal">chef_repo_path</tt> in client.rb.

<tt class="docutils literal">--cookbook-version VERSION</tt>

The version of a cookbook to download.

<tt class="docutils literal">--concurrency</tt>

The number of allowed concurrent connections. Default: <tt class="docutils literal">10</tt>.

<tt class="docutils literal">--diff-filter=[(A|D|M|T)...[*]]</tt>

Use to select only files that have been added (<tt class="docutils literal">A</tt>), deleted (<tt class="docutils literal">D</tt>), modified (<tt class="docutils literal">M</tt>), and/or have had their type changed (<tt class="docutils literal">T</tt>). Any combination of filter characters may be used, including no filter characters. Use <tt class="docutils literal">*</tt> to select all paths if a file matches other criteria in the comparison. Default value: <tt class="docutils literal">nil</tt>.

<tt class="docutils literal">--name-only</tt>

Use to show only the names of modified files.

<tt class="docutils literal">--name-status</tt>

Use to show only the names of files with a status of <tt class="docutils literal">Added</tt>, <tt class="docutils literal">Deleted</tt>, <tt class="docutils literal">Modified</tt>, or <tt class="docutils literal">Type Changed</tt>.

<tt class="docutils literal">--no-recurse</tt>

Use <tt class="docutils literal">--no-recurse</tt> to disable listing a directory recursively. Default: <tt class="docutils literal">--recurse</tt>.

<tt class="docutils literal">--repo-mode MODE</tt>

The layout of the local chef-repo. Possible values: <tt class="docutils literal">static</tt>, <tt class="docutils literal">everything</tt>, or <tt class="docutils literal">hosted_everything</tt>. Use <tt class="docutils literal">static</tt> for just roles, environments, cookbooks, and data bags. By default, <tt class="docutils literal">everything</tt> and <tt class="docutils literal">hosted_everything</tt> are dynamically selected depending on the server type. Default: <tt class="docutils literal">everything</tt> / <tt class="docutils literal">hosted_everything</tt>.

Examples¶

The following examples show how to use this knife subcommand:

Compare files that contain JSON data

To compare the <tt class="docutils literal">base.json</tt> role to a <tt class="docutils literal">webserver.json</tt> role, enter:

$ knife diff roles/base.json roles/webserver.json

Compare the chef-repo and the server

To compare the differences between the local chef-repo and the files that are on the Chef server, enter:

$ knife diff

Compare, then return results

To diff a node named <tt class="docutils literal">node-lb</tt> and then only return files that have been added, deleted, modified, or changed, enter:

$ knife diff --name-status node-lb

to return something like:

node-lb/recipes/eip.rb
node-lb/recipes/heartbeat-int.rb
node-lb/templates/default/corpsite.conf.erb
node-lb/files/default/wildcard.node.com.crt
node-lb/files/default/wildcard.node.com.crt-2009
node-lb/files/default/wildcard.node.com.key
node-lb/.gitignore
node-lb/Rakefile


text:
package org.opencb.opencga.core.models.variant;

import org.opencb.opencga.core.tools.ToolParams;

public class IndividualQcAnalysisParams extends ToolParams {
    public static final String DESCRIPTION = "Individual QC analysis params";
    private String individual;
    private String sample;
    private String inferredSexMethod;

    private String outdir;

    public IndividualQcAnalysisParams() {
    }

    public IndividualQcAnalysisParams(String individual, String sample, String inferredSexMethod, String outdir) {
        this.individual = individual;
        this.sample = sample;
        this.inferredSexMethod = inferredSexMethod;
        this.outdir = outdir;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("IndividualQcAnalysisParams{");
        sb.append("individual='").append(individual).append('\'');
        sb.append(", sample='").append(sample).append('\'');
        sb.append(", inferredSexMethod='").append(inferredSexMethod).append('\'');
        sb.append(", outdir='").append(outdir).append('\'');
        sb.append('}');
        return sb.toString();
    }

    public String getIndividual() {
        return individual;
    }

    public IndividualQcAnalysisParams setIndividual(String individual) {
        this.individual = individual;
        return this;
    }

    public String getSample() {
        return sample;
    }

    public IndividualQcAnalysisParams setSample(String sample) {
        this.sample = sample;
        return this;
    }

    public String getInferredSexMethod() {
        return inferredSexMethod;
    }

    public IndividualQcAnalysisParams setInferredSexMethod(String inferredSexMethod) {
        this.inferredSexMethod = inferredSexMethod;
        return this;
    }

    public String getOutdir() {
        return outdir;
    }

    public IndividualQcAnalysisParams setOutdir(String outdir) {
        this.outdir = outdir;
        return this;
    }
}


text:
Examl

DDL

CREATE DATABASE Bitbucket
GO
USE Bitbucket
GO

CREATE TABLE Users(
	Id INT PRIMARY KEY IDENTITY(1,1),
	Username VARCHAR(30) NOT NULL,
	[Password] VARCHAR(30) NOT NULL,
	Email VARCHAR(30) NOT NULL
)

CREATE TABLE Repositories(
	Id INT PRIMARY KEY IDENTITY,
	[Name] VARCHAR(50) NOT NULL
)

CREATE TABLE RepositoriesContributors(
	RepositoryId INT FOREIGN KEY REFERENCES Repositories(Id) NOT NULL,
	ContributorId INT FOREIGN KEY REFERENCES Users(Id) NOT NULL,
	CONSTRAINT PK_RepositoriesContributors PRIMARY KEY (RepositoryId, ContributorId)
)

CREATE TABLE Issues(
	Id INT PRIMARY KEY IDENTITY,
	[Title] VARCHAR(255) NOT NULL,
	IssueStatus CHAR(6) NOT NULL,
	RepositoryId INT FOREIGN KEY REFERENCES Repositories(Id) NOT NULL,
	AssigneeId INT FOREIGN KEY REFERENCES Users(Id) NOT NULL,
)

CREATE TABLE Commits(
	Id INT PRIMARY KEY IDENTITY,
	[Message] VARCHAR(255) NOT NULL,
	IssueId INT FOREIGN KEY REFERENCES Issues(Id),
	RepositoryId INT FOREIGN KEY REFERENCES Repositories(Id) NOT NULL,
	ContributorId INT FOREIGN KEY REFERENCES Users(Id) NOT NULL,
)

CREATE TABLE Files(
	Id INT PRIMARY KEY IDENTITY,
	[Name] VARCHAR(100) NOT NULL,
	[Size] DECIMAL(15,2) NOT NULL,
	ParentId INT FOREIGN KEY REFERENCES Files(Id),
	CommitId INT FOREIGN KEY REFERENCES Commits(Id) NOT NULL,
)

-- GRUD

INSERT INTO Files([Name], [Size], ParentId, CommitId) VALUES
('Trade.idk', 2598.0,1,1),
('menu.net', 9238.31, 2,2),
('Administrate.soshy', 1246.93,	3,	3),
('Controller.php',7353.15,	4,	4),
('Find.java', 9957.86,5,	5),
('Controller.json',	14034.87,	3,	6),
('Operate.xix',	7662.92, 7,	7);

INSERT INTO Issues(Title, IssueStatus, RepositoryId, AssigneeId) VALUES
('Critical Problem with HomeController.cs file', 'open', 1, 4),
('Typo fix in Judge.html', 'open', 4, 3),
('Implement documentation for UsersService.cs', 'closed', 8, 2),
('Unreachable code in Index.cs', 'open', 9, 8);

UPDATE Issues
SET IssueStatus = 'closed'
WHERE AssigneeId IN (6);

SELECT * FROM Repositories
WHERE Name = 'Softuni-Teamwork'

SELECT * FROM Commits
WHERE RepositoryId = 3
SELECT * FROM Files
WHERE CommitId = 36

DELETE FROM RepositoriesContributors
WHERE RepositoryId IN (
						SELECT RepositoryId FROM Repositories
						WHERE Name = 'Softuni-Teamwork'
)

DELETE FROM Files
WHERE CommitId IN (
	SELECT CommitId FROM Commits
	WHERE RepositoryId IN(
						SELECT RepositoryId FROM Repositories
						WHERE Name = 'Softuni-Teamwork')
)

DELETE FROM Commits
WHERE RepositoryId IN (
						SELECT RepositoryId FROM Repositories
						WHERE Name = 'Softuni-Teamwork'
)

DELETE FROM Issues
WHERE RepositoryId IN (
						SELECT RepositoryId FROM Repositories
						WHERE Name = 'Softuni-Teamwork'
)

SELECT Id, Message, RepositoryId, ContributorId FROM Commits
ORDER BY Id, Message, RepositoryId, ContributorId

SELECT Id, Name, Size FROM Files
WHERE Size > 1000 AND Name Like '%html%'
ORDER BY Size DESC, Id, Name

SELECT i.Id, CONCAT(u.Username,' : ', i.Title) AS IssueAssignee  FROM Issues i
JOIN Users u
ON i.AssigneeId = u.Id
ORDER BY i.Id DESC, IssueAssignee

SELECT Id, Name, CONCAT(Size, 'KB') as Size FROM Files
WHERE Id NOT IN (SELECT DISTINCT ParentId FROM Files f1
WHERE ParentId IS NOT NULL)

SELECT TOP(5) r.Id, r.Name, COUNT(c.RepositoryId) as Commits FROM Repositories r
JOIN Commits c
ON r.Id = c.RepositoryId
GROUP BY r.Id, r.Name

SELECT  * FROM Commits c
ORDER BY c.RepositoryId

GO

WITH CTE AS
(
SELECT TOP(5) c.RepositoryId, COUNT(c.RepositoryId) AS Commits FROM Commits c
GROUP BY c.RepositoryId
ORDER BY COUNT(c.RepositoryId) DESC
)
SELECT r.Id, r.Name, Commits FROM CTE
RIGHT JOIN Repositories as r
ON r.Id = CTE.RepositoryId
WHERE Commits IS NOT NULL
ORDER BY Commits DESC, r.Id, r.Name

GO

SELECT * FROM Repositories r
JOIN Commits c
ON r.Id = c.RepositoryId

SELECT u.Username, AVG(f.Size) AS Size FROM Commits c
JOIN Users u
ON u.Id = c.ContributorId
JOIN Files f
ON f.CommitId = c.Id
GROUP BY u.Username
ORDER BY [Size] DESC,  u.Username

SELECT * FROM Users u
WHERE u.Id IN (SELECT DISTINCT ContributorId FROM Commits);
GO

CREATE FUNCTION dbo.udf_UserTotalCommits (@username VARCHAR(30))
RETURNS int
AS
BEGIN
     RETURN(
  SELECT COUNT(c.Id) AS [Output] FROM Commits c
	WHERE c.ContributorId IN (SELECT Id FROM Users
								WHERE Username = @username)
   );
END;


text:
<?php

namespace Bolt\Nut;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Nut command to repair/update database schema
 */
class DatabaseRepair extends BaseCommand
{
    /**
     * @see \Symfony\Component\Console\Command\Command::configure()
     */
    protected function configure()
    {
        $this
            ->setName('database:update')
            ->setDescription('Repair and/or update the database.');
    }

    /**
     * @see \Symfony\Component\Console\Command\Command::execute()
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $response = $this->app['schema']->update();

        if (!$response->hasResponses()) {
            $output->writeln('<info>Your database is already up to date.</info>');
        } else {
            $output->writeln('<comment>Modifications made to the database:</comment>');
            foreach ($response->getResponseStrings() as $messages) {
                $output->writeln('<info> - ' . $messages . '</info>');
            }
            $output->writeln('<info>Your database is now up to date.</info>');

            $this->auditLog(__CLASS__, 'Database updated');
        }
    }
}


text:
angular.module('starter.controllers', [])

.controller('DashCtrl', function($scope, CameraControlService) {

  function refreshStatus() {
    CameraControlService.getCameraStatus().then(function(data) {
      var status = data.data;
      $scope.enabled = status.enabled;
    });
  }

  refreshStatus();

  function toggleCamera() {
    CameraControlService.setCameraStatus(!$scope.enabled).then(
      function(data) {
        var status = data.data;
        $scope.enabled = status.enabled;
      }
    )
  }
  $scope.toggleCamera = toggleCamera;

})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
});


text:
% gets prolog to work from command line

:- initialization main.

%Pass the File location you want to read in,
%the temperature you want to start with,
%the temperature you want to reach,
%and the constant by which the temperature is increasing

%i.e temp start is 1, temp reach is 1000000, constant is 4

main:-

b_setval('Temp', 1),
b_setval('Temp_min' , 1000000),
b_setval('A', 1.9),
b_setval('mincost', 1000000),
b_setval('currentcost', 0),
%read in command lines
  current_prolog_flag(argv, AllArgs),
  append(_, [-- | File1], AllArgs),
nth0(0, File1, File2),

atom_string(File, File2),

%open the file and disregard extra input, im too lazy to
open(File,read,ID),
read_line_to_codes(ID,_),
read_line_to_codes(ID,_),
read_line_to_codes(ID,_),
read_line_to_codes(ID,Y ),
split_string(Y, " ", "", [_, B]),
b_setval('Dim', B),
read_line_to_codes(ID,_),
read_line_to_codes(ID,_),
reads(ID,_),

%Get the list, and generate a completely random list
b_getval('List1', List1),
generate_random_sol(List1,List2),
%store the cost of the list for time

calculate_Cost(List2, Cost1),
b_setval('List', List2),
b_setval('currentcost', Cost1),

%find the optimal node pairings
find_Optimal(Solution),
 open('results.txt',write,X),

 % Output the optimal answer
 b_getval('List',List3),
 G is Solution / 10,
 write(X,'The current distance is :'),
 write(X, G),
 nl(X),
 write(X,'The current node set is : '),
  nl(X),
 printlist(List3,X),

 %close input and output streams
 close(X),
 close(ID),
 halt.

printlist([], _).

printlist([H|T], X):-
write(X,H),
nl(X),
printlist(T,X).

% Get all of the Node pairings from the input, and store them globally
% and inside of a giant list with all of the Node names
reads(ID,List):-
read_line_to_codes(ID, X),
split_string(X, " ", "", L),
delete(L,"", [A,B,C]),
A\="end_of_line",
B\="end_of_line",
C\="end_of_line",
atom_number(A, A1),
atom_number(B, B1),
atom_number(C, C1),
term_to_atom(A, A2),
b_setval(A2, (B1,C1)),
append(List, [A1], List1 ),
b_setval('List1',List1),
reads(ID,List1).

reads(_, _):-

!.

% Will return a value above 0 based on Temperature, and the cost of the two
acceptance_Probability(Cost1, Cost2, _, Result) :-
Cost1-Cost2 > 100,
Result is 0.
acceptance_Probability(Cost1, Cost2, T, Result) :-
Result is e^((Cost1-Cost2)/T).

% attempts to find the best node pairings by looping through the pairings
% and randomly finding a neighbor that might be better than the current solution
find_Optimal(K) :-

	b_getval('Temp', X),
	b_getval('Temp_min',Y),

    X=<Y,
     solve(1),
    b_getval('A', A1),

    G is X * A1,
    b_setval('Temp', G),
    b_getval('List',Max),
    generate_random_neighbor(Max, A ),
    b_setval('List',A),

    find_Optimal(K).

% In this case, the loop is done so we find the final cost and store it

find_Optimal(Solution) :-

	b_getval('Temp', X),
	b_getval('Temp_min',Y),
	X>Y,
	b_getval('List', Z),
    calculate_Cost(Z, Solution).

% This loops through starting at a random permutation pairings
% and attempts to find the best pairings set

solve(I):-

I<300,
b_getval('List', L1),
b_getval('currentcost',Cost1),
generate_random_neighbor(L1,L2),
calculate_Cost(L2, Cost2),
!,
b_getval('mincost', Cost3),
checkcost(Cost1,Cost3),
checkcost(Cost2,Cost3),
b_getval('Temp', T),
acceptance_Probability(Cost1, Cost2, T, Result),
random(A2),
J is I + 1,

% see if we want to pick the neighboring set instead
(  Result > A2
    -> b_setval('List', L2),
    	b_setval('currentcost', Cost2),
    !,
    solve(J)
    ; !,
    solve(J)
 ).

solve(X):-
X>=100.

% Check to see if the cost is minimial
checkcost(C1,C3):-
C1 < C3,
b_setval('mincost',C1).

checkcost(_,_).

% calculating cost of traveling along the selected path

calculate_Cost([H|[H1|T]], Cost) :-

 distance(H,H1, A),
  !,
 calculate_Cost([H1|T],Rest),
 Cost is A + Rest.

calculate_Cost([_], Cost) :-

Cost is 0.

%get distance between two nodes

distance(A,B, Dist) :-

term_string(A, A1),
term_string(B, B1),
term_to_atom(A1, A2),
term_to_atom(B1, B2),
b_getval(A2,(X1,Y1)),
b_getval(B2, (X2,Y2)),
K is X2- X1,
K1 is Y2-Y1,
K2 is K * K,
K3 is K1 * K1,
K4 is K2 + K3,
K5 is sqrt(K4),
Dist is K5.

%generate a random solution of the biggining

generate_random_sol(A,X) :-
random_permutation(A, X).

%generate a random neighbor of the list,
%neighbor being two elements in the list swapped

generate_random_neighbor(A,X) :-

b_getval('Dim',Max1),
number_string(Max2, Max1),
Max is Max2-1,
random(2, Max, G),
random(2, Max, H),
list_swap(A, G,H, Y),
random(2, Max, G1),
random(2, Max, H1),
list_swap(Y, G1,H1, X).

%swap two elements in the list randomly,
%making sure the lists remain

list_swap(Before,_,_,After) :-

   same_length(Before,After),
   append(B1,[A1|A11],Before),
   append(B1,[A2|A11],Swap),
   append(B2,[A2|A22],Swap),
   append(B2,[A1|A22],After).


text:
package nest.sparkle.loader

import scala.language.existentials
import scala.reflect.ClassTag
import scala.reflect.runtime.universe._
import scala.util.Try

import nest.sparkle.datastream.DataArray
import nest.sparkle.loader.Loader._
import nest.sparkle.util.{FieldsDescriptor, Flags, Log, ReflectionUtil, TryUtil}

/**
 * A transformer that can convert column slices with boolean values to a single column
 * slice with the boolean values stored as a Long (ie Flags object).
 */
abstract class TransformFlags[T <: Flags :TypeTag](flagsFactory: () => T)
  extends LoadingTransformer with Log {

  implicit val flagsClassTag: ClassTag[T] = ReflectionUtil.classTag[T]

  val fieldsDescriptor: FieldsDescriptor = flagsFactory().fields

  /** column name to use for the slice of Flags objects */
  def flagsColumn: String

  override def transform(sourceBlock: TaggedBlock): Try[TaggedBlock] = {

    var optFlagsDataset: Option[String] = None // dataset for the Flags

    // split into slices that are and aren't part of the Flags
    val (flagSlices, otherSlices) = sourceBlock.partition { slice =>
      val idx = slice.columnPath.lastIndexOf('/')
      val field = slice.columnPath.substring(idx + 1)
      fieldsDescriptor.positionOfField(field).isDefined
    }

    // convert to FlagUpdates
    val flagUpdatesIter: Iterator[Try[Seq[FlagUpdate]]] =
      flagSlices.iterator.map { slice =>
        val idx = slice.columnPath.lastIndexOf('/')
        val field = slice.columnPath.substring(idx + 1)
        val optPosition = fieldsDescriptor.positionOfField(field)
        assert(optPosition.isDefined)
        val position = optPosition.get
        val dataset = slice.columnPath.substring(0, idx)
        optFlagsDataset match {
          case Some(flagsDataset) => assert(flagsDataset == dataset)
          case None               => optFlagsDataset = Some(dataset)
        }
        for {
          dataArray <- Try(slice.dataArray.asInstanceOf[DataArray[Any,Boolean]])
        } yield {
          dataArray.map { case (key, value: Boolean) => FlagUpdate(key, position, value) }
        }
      }

    TryUtil.firstFailureOrElseSuccessVector(flagUpdatesIter).map { flagUpdates =>
      if (flagUpdates.isEmpty) {
        otherSlices
      } else {
        // Flags-ify
        val flagsByKey: Map[Any, T] = flagUpdates.flatten.groupBy(_.key).map { case (key, flagUpdates) =>
          (key, flagUpdates.foldLeft(flagsFactory())((flags, flagUpdate) =>
            flags.updatedFlags(flagUpdate.position, flagUpdate.value).asInstanceOf[T]))
        }
        assert(optFlagsDataset.isDefined)
        otherSlices :+ TaggedSlice[Any, T](s"${optFlagsDataset.get}/$flagsColumn", DataArray.fromPairs(flagsByKey))
      }
    }
  }

}

/** Indicates there's an issue transforming a block to a slice of Flags */
case class TransformFlagsException(msg: String) extends RuntimeException(msg)

/** Holds the bit value at a given position for the Flags id'ed by key */
case class FlagUpdate(key: Any, position: Int, value: Boolean)