text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('course', '0003_auto_20150425_1609'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='MessageComment',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('text', models.TextField(max_length=500)),
            ],
        ),
        migrations.CreateModel(
            name='Topic',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=150)),
                ('pub_date', models.DateTimeField(auto_now_add=True)),
                ('course', models.ForeignKey(to='course.Course')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='TopicMessage',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('text', models.TextField(max_length=1000)),
                ('pub_date', models.DateTimeField(auto_now_add=True)),
                ('topic', models.ForeignKey(to='forum.Topic')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='messagecomment',
            name='topic_message',
            field=models.ForeignKey(to='forum.TopicMessage'),
        ),
        migrations.AddField(
            model_name='messagecomment',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription, TeardownLogic } from '../Subscription';
import { OuterSubscriber } from '../OuterSubscriber';
import { subscribeToResult } from '../util/subscribeToResult';

/**
 * Converts a higher-order Observable into a first-order Observable by dropping
 * inner Observables while the previous inner Observable has not yet completed.
 *
 * Flattens an Observable-of-Observables by dropping the
 * next inner Observables while the current inner is still executing.
 *
 *
 *
 * `exhaust` subscribes to an Observable that emits Observables, also known as a
 * higher-order Observable. Each time it observes one of these emitted inner
 * Observables, the output Observable begins emitting the items emitted by that
 * inner Observable. So far, it behaves like {@link mergeAll}. However,
 * `exhaust` ignores every new inner Observable if the previous Observable has
 * not yet completed. Once that one completes, it will accept and flatten the
 * next inner Observable and repeat this process.
 *
 * @example
Run a finite timer for each click, only if there is no currently active timer

 * var clicks = Rx.Observable.fromEvent(document, 'click');
 * var higPuppyrder = clicks.map((ev) => Rx.Observable.interval(1000));
 * var result = higPuppyrder.exhaust();
 * result.subscribe(x => console.log(x));
 *
 * @see {@link combineAll}
 * @see {@link concatAll}
 * @see {@link switch}
 * @see {@link mergeAll}
 * @see {@link exhaustMap}
 * @see {@link zipAll}
 *
 * @return {Observable} Returns an Observable that takes a source of Observables
 * and propagates the first observable exclusively until it completes before
 * subscribing to the next.
 * @method exhaust
 * @owner Observable
 */
export function exhaust<T>(this: Observable<T>): Observable<T> {
  return this.lift(new SwitchFirstOperator<T>());
}

class SwitchFirstOperator<T> implements Operator<T, T> {
  call(subscriber: Subscriber<T>, source: any): TeardownLogic {
    return source.subscribe(new SwitchFirstSubscriber(subscriber));
  }
}

/**
 * We need this JSDoc comment for affecting ESDoc.
 * @ignore
 * @extends {Ignored}
 */
class SwitchFirstSubscriber<T> extends OuterSubscriber<T, T> {
  private hasCompleted: boolean = false;
  private hasSubscription: boolean = false;

  constructor(destination: Subscriber<T>) {
    super(destination);
  }

  protected _next(value: T): void {
    if (!this.hasSubscription) {
      this.hasSubscription = true;
      this.add(subscribeToResult(this, value));
    }
  }

  protected _complete(): void {
    this.hasCompleted = true;
    if (!this.hasSubscription) {
      this.destination.complete();
    }
  }

  notifyComplete(innerSub: Subscription): void {
    this.remove(innerSub);
    this.hasSubscription = false;
    if (this.hasCompleted) {
      this.destination.complete();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
use std::{
    char, fmt,
    iter::{Iterator, Peekable},
    result::Result,
    str::CharIndices,
};

use crate::parser::{SourcePosition, Spanning};

#[doc(hidden)]
#[derive(Debug)]
pub struct Lexer<'a> {
    iterator: Peekable<CharIndices<'a>>,
    source: &'a str,
    length: usize,
    position: SourcePosition,
    has_reached_eof: bool,
}

/// A single scalar value literal
///
/// This is only used for tagging how the lexer has interpreted a value literal
#[derive(Debug, PartialEq, Clone, Copy)]
#[allow(missing_docs)]
pub enum ScalarToken<'a> {
    String(&'a str),
    Float(&'a str),
    Int(&'a str),
}

/// A single token in the input source
#[derive(Debug, PartialEq, Clone, Copy)]
#[allow(missing_docs)]
pub enum Token<'a> {
    Name(&'a str),
    Scalar(ScalarToken<'a>),
    ExclamationMark,
    Dollar,
    ParenOpen,
    ParenClose,
    BracketOpen,
    BracketClose,
    CurlyOpen,
    CurlyClose,
    Ellipsis,
    Colon,
    Equals,
    At,
    Pipe,
    EndOfFile,
}

/// Error when tokenizing the input source
#[derive(Debug, PartialEq, Eq)]
pub enum LexerError {
    /// An unknown character was found
    ///
    /// Unknown characters are characters that do not occur anywhere in the
    /// GraphQL language, such as `?` or `%`.
    UnknownCharacter(char),

    /// An unexpected character was found
    ///
    /// Unexpected characters are characters that _do_ exist in the GraphQL
    /// language, but is not expected at the current position in the document.
    UnexpectedCharacter(char),

    /// An unterminated string literal was found
    ///
    /// Apart from forgetting the ending `"`, terminating a string within a
    /// Unicode escape sequence or having a line break in the string also
    /// causes this error.
    UnterminatedString,

    /// An unknown character in a string literal was found
    ///
    /// This occurs when an invalid source character is found in a string
    /// literal, such as ASCII control characters.
    UnknownCharacterInString(char),

    /// An unknown escape sequence in a string literal was found
    ///
    /// Only a limited set of escape sequences are supported, this is emitted
    /// when e.g. `"\l"` is parsed.
    UnknownEscapeSequence(String),

    /// The input source was unexpectedly terminated
    ///
    /// Emitted when the current token requires a succeeding character, but
    /// the source has reached EOF. Emitted when scanning e.g. `"1."`.
    UnexpectedEndOfFile,

    /// An invalid number literal was found
    InvalidNumber,
}

pub type LexerResult<'a> = Result<Spanning<Token<'a>>, Spanning<LexerError>>;

impl<'a> Lexer<'a> {
    #[doc(hidden)]
    pub fn new(source: &'a str) -> Lexer<'a> {
        Lexer {
            iterator: source.char_indices().peekable(),
            source,
            length: source.len(),
            position: SourcePosition::new_origin(),
            has_reached_eof: false,
        }
    }

    fn peek_char(&mut self) -> Option<(usize, char)> {
        assert!(self.position.index() <= self.length);
        assert!(!self.has_reached_eof);

        self.iterator.peek().map(|&(idx, ch)| (idx, ch))
    }

    fn next_char(&mut self) -> Option<(usize, char)> {
        assert!(self.position.index() <= self.length);
        assert!(!self.has_reached_eof);

        let next = self.iterator.next();

        if let Some((_, ch)) = next {
            if ch == '\n' {
                self.position.advance_line();
            } else {
                self.position.advance_col();
            }
        }

        next
    }

    fn emit_single_char(&mut self, t: Token<'a>) -> Spanning<Token<'a>> {
        assert!(self.position.index() <= self.length);

        let start_pos = self.position;

        self.next_char()
            .expect("Internal error in GraphQL lexer: emit_single_char reached EOF");

        Spanning::single_width(&start_pos, t)
    }

    fn scan_over_whitespace(&mut self) {
        while let Some((_, ch)) = self.peek_char() {
            if ch == '\t' || ch == ' ' || ch == '\n' || ch == '\r' || ch == ',' {
                self.next_char();
            } else if ch == '#' {
                self.next_char();

                while let Some((_, ch)) = self.peek_char() {
                    if is_source_char(ch) && (ch == '\n' || ch == '\r') {
                        self.next_char();
                        break;
                    } else if is_source_char(ch) {
                        self.next_char();
                    } else {
                        break;
                    }
                }
            } else {
                break;
            }
        }
    }

    fn scan_ellipsis(&mut self) -> LexerResult<'a> {
        let start_pos = self.position;

        for _ in 0..3 {
            let (_, ch) = self.next_char().ok_or_else(|| {
                Spanning::zero_width(&self.position, LexerError::UnexpectedEndOfFile)
            })?;
            if ch != '.' {
                return Err(Spanning::zero_width(
                    &start_pos,
                    LexerError::UnexpectedCharacter('.'),
                ));
            }
        }

        Ok(Spanning::start_end(
            &start_pos,
            &self.position,
            Token::Ellipsis,
        ))
    }

    fn scan_name(&mut self) -> LexerResult<'a> {
        let start_pos = self.position;
        let (start_idx, start_ch) = self
            .next_char()
            .ok_or_else(|| Spanning::zero_width(&self.position, LexerError::UnexpectedEndOfFile))?;
        assert!(is_name_start(start_ch));

        let mut end_idx = start_idx;

        while let Some((idx, ch)) = self.peek_char() {
            if is_name_cont(ch) {
                self.next_char();
                end_idx = idx;
            } else {
                break;
            }
        }

        Ok(Spanning::start_end(
            &start_pos,
            &self.position,
            Token::Name(&self.source[start_idx..=end_idx]),
        ))
    }

    fn scan_string(&mut self) -> LexerResult<'a> {
        let start_pos = self.position;
        let (start_idx, start_ch) = self
            .next_char()
            .ok_or_else(|| Spanning::zero_width(&self.position, LexerError::UnexpectedEndOfFile))?;
        if start_ch != '"' {
            return Err(Spanning::zero_width(
                &self.position,
                LexerError::UnterminatedString,
            ));
        }

        let mut escaped = false;
        let mut old_pos = self.position;
        while let Some((idx, ch)) = self.next_char() {
            match ch {
                'b' | 'f' | 'n' | 'r' | 't' | '\\' | '/' | '"' if escaped => {
                    escaped = false;
                }
                'u' if escaped => {
                    self.scan_escaped_unicode(&old_pos)?;
                    escaped = false;
                }
                c if escaped => {
                    return Err(Spanning::zero_width(
                        &old_pos,
                        LexerError::UnknownEscapeSequence(format!("\\{}", c)),
                    ));
                }
                '\\' => escaped = true,
                '"' if !escaped => {
                    return Ok(Spanning::start_end(
                        &start_pos,
                        &self.position,
                        Token::Scalar(ScalarToken::String(&self.source[start_idx + 1..idx])),
                    ));
                }
                '\n' | '\r' => {
                    return Err(Spanning::zero_width(
                        &old_pos,
                        LexerError::UnterminatedString,
                    ));
                }
                c if !is_source_char(c) => {
                    return Err(Spanning::zero_width(
                        &old_pos,
                        LexerError::UnknownCharacterInString(ch),
                    ));
                }
                _ => {}
            }
            old_pos = self.position;
        }

        Err(Spanning::zero_width(
            &self.position,
            LexerError::UnterminatedString,
        ))
    }

    fn scan_escaped_unicode(
        &mut self,
        start_pos: &SourcePosition,
    ) -> Result<(), Spanning<LexerError>> {
        let (start_idx, _) = self
            .peek_char()
            .ok_or_else(|| Spanning::zero_width(&self.position, LexerError::UnterminatedString))?;
        let mut end_idx = start_idx;
        let mut len = 0;

        for _ in 0..4 {
            let (idx, ch) = self.next_char().ok_or_else(|| {
                Spanning::zero_width(&self.position, LexerError::UnterminatedString)
            })?;

            if !ch.is_alphanumeric() {
                break;
            }

            end_idx = idx;
            len += 1;
        }

        // Make sure we are on a valid char boundary.
        let escape = self
            .source
            .get(start_idx..=end_idx)
            .ok_or_else(|| Spanning::zero_width(&self.position, LexerError::UnterminatedString))?;

        if len != 4 {
            return Err(Spanning::zero_width(
                start_pos,
                LexerError::UnknownEscapeSequence("\\u".to_owned() + escape),
            ));
        }

        let code_point = u32::from_str_radix(escape, 16).map_err(|_| {
            Spanning::zero_width(
                start_pos,
                LexerError::UnknownEscapeSequence("\\u".to_owned() + escape),
            )
        })?;

        char::from_u32(code_point)
            .ok_or_else(|| {
                Spanning::zero_width(
                    start_pos,
                    LexerError::UnknownEscapeSequence("\\u".to_owned() + escape),
                )
            })
            .map(|_| ())
    }

    fn scan_number(&mut self) -> LexerResult<'a> {
        let start_pos = self.position;
        let (start_idx, _) = self
            .peek_char()
            .ok_or_else(|| Spanning::zero_width(&self.position, LexerError::UnexpectedEndOfFile))?;

        let mut last_idx = start_idx;
        let mut last_char = '1';
        let mut is_float = false;

        let mut end_idx = loop {
            if let Some((idx, ch)) = self.peek_char() {
                if ch.is_digit(10) || (ch == '-' && last_idx == start_idx) {
                    if ch == '0' && last_char == '0' && last_idx == start_idx {
                        return Err(Spanning::zero_width(
                            &self.position,
                            LexerError::UnexpectedCharacter('0'),
                        ));
                    }
                    self.next_char();
                    last_char = ch;
                } else if last_char == '-' {
                    return Err(Spanning::zero_width(
                        &self.position,
                        LexerError::UnexpectedCharacter(ch),
                    ));
                } else {
                    break idx;
                }
                last_idx = idx;
            } else {
                break last_idx + 1;
            }
        };

        if let Some((start_idx, '.')) = self.peek_char() {
            is_float = true;
            let mut last_idx = start_idx;
            self.next_char();
            end_idx = loop {
                if let Some((idx, ch)) = self.peek_char() {
                    if ch.is_digit(10) {
                        self.next_char();
                    } else if last_idx == start_idx {
                        return Err(Spanning::zero_width(
                            &self.position,
                            LexerError::UnexpectedCharacter(ch),
                        ));
                    } else {
                        break idx;
                    }
                    last_idx = idx;
                } else if last_idx == start_idx {
                    return Err(Spanning::zero_width(
                        &self.position,
                        LexerError::UnexpectedEndOfFile,
                    ));
                } else {
                    break last_idx + 1;
                }
            };
        }
        if let Some((start_idx, ch)) = self.peek_char() {
            if ch == 'e' || ch == 'E' {
                is_float = true;
                self.next_char();
                let mut last_idx = start_idx;

                end_idx = loop {
                    if let Some((idx, ch)) = self.peek_char() {
                        if ch.is_digit(10) || (last_idx == start_idx && (ch == '-' || ch == '+')) {
                            self.next_char();
                        } else if last_idx == start_idx {
                            // 1e is not a valid floating point number
                            return Err(Spanning::zero_width(
                                &self.position,
                                LexerError::UnexpectedCharacter(ch),
                            ));
                        } else {
                            break idx;
                        }
                        last_idx = idx;
                    } else if last_idx == start_idx {
                        // 1e is not a valid floting point number
                        return Err(Spanning::zero_width(
                            &self.position,
                            LexerError::UnexpectedEndOfFile,
                        ));
                    } else {
                        break last_idx + 1;
                    }
                };
            }
        }
        let number = &self.source[start_idx..end_idx];
        let end_pos = &self.position;

        let token = if is_float {
            Token::Scalar(ScalarToken::Float(number))
        } else {
            Token::Scalar(ScalarToken::Int(number))
        };

        Ok(Spanning::start_end(&start_pos, end_pos, token))
    }
}

impl<'a> Iterator for Lexer<'a> {
    type Item = LexerResult<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.has_reached_eof {
            return None;
        }

        self.scan_over_whitespace();

        let ch = self.iterator.peek().map(|&(_, ch)| ch);

        Some(match ch {
            Some('!') => Ok(self.emit_single_char(Token::ExclamationMark)),
            Some('$') => Ok(self.emit_single_char(Token::Dollar)),
            Some('(') => Ok(self.emit_single_char(Token::ParenOpen)),
            Some(')') => Ok(self.emit_single_char(Token::ParenClose)),
            Some('[') => Ok(self.emit_single_char(Token::BracketOpen)),
            Some(']') => Ok(self.emit_single_char(Token::BracketClose)),
            Some('{') => Ok(self.emit_single_char(Token::CurlyOpen)),
            Some('}') => Ok(self.emit_single_char(Token::CurlyClose)),
            Some(':') => Ok(self.emit_single_char(Token::Colon)),
            Some('=') => Ok(self.emit_single_char(Token::Equals)),
            Some('@') => Ok(self.emit_single_char(Token::At)),
            Some('|') => Ok(self.emit_single_char(Token::Pipe)),
            Some('.') => self.scan_ellipsis(),
            Some('"') => self.scan_string(),
            Some(ch) => {
                if is_number_start(ch) {
                    self.scan_number()
                } else if is_name_start(ch) {
                    self.scan_name()
                } else {
                    Err(Spanning::zero_width(
                        &self.position,
                        LexerError::UnknownCharacter(ch),
                    ))
                }
            }
            None => {
                self.has_reached_eof = true;
                Ok(Spanning::zero_width(&self.position, Token::EndOfFile))
            }
        })
    }
}

impl<'a> fmt::Display for Token<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Token::Name(name) => write!(f, "{}", name),
            Token::Scalar(ScalarToken::Int(s)) | Token::Scalar(ScalarToken::Float(s)) => {
                write!(f, "{}", s)
            }
            Token::Scalar(ScalarToken::String(s)) => {
                write!(f, "\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
            }
            Token::ExclamationMark => write!(f, "!"),
            Token::Dollar => write!(f, "$"),
            Token::ParenOpen => write!(f, "("),
            Token::ParenClose => write!(f, ")"),
            Token::BracketOpen => write!(f, "["),
            Token::BracketClose => write!(f, "]"),
            Token::CurlyOpen => write!(f, "{{"),
            Token::CurlyClose => write!(f, "}}"),
            Token::Ellipsis => write!(f, "..."),
            Token::Colon => write!(f, ":"),
            Token::Equals => write!(f, "="),
            Token::At => write!(f, "@"),
            Token::Pipe => write!(f, "|"),
            Token::EndOfFile => write!(f, "End of file"),
        }
    }
}

fn is_source_char(c: char) -> bool {
    c == '\t' || c == '\n' || c == '\r' || c >= ' '
}

fn is_name_start(c: char) -> bool {
    c == '_' || ('A'..='Z').contains(&c) || ('a'..='z').contains(&c)
}

fn is_name_cont(c: char) -> bool {
    is_name_start(c) || ('0'..='9').contains(&c)
}

fn is_number_start(c: char) -> bool {
    c == '-' || ('0'..='9').contains(&c)
}

impl fmt::Display for LexerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            LexerError::UnknownCharacter(c) => write!(f, "Unknown character \"{}\"", c),
            LexerError::UnterminatedString => write!(f, "Unterminated string literal"),
            LexerError::UnknownCharacterInString(c) => {
                write!(f, "Unknown character \"{}\" in string literal", c)
            }
            LexerError::UnknownEscapeSequence(ref s) => {
                write!(f, "Unknown escape sequence \"{}\" in string", s)
            }
            LexerError::UnexpectedCharacter(c) => write!(f, "Unexpected character \"{}\"", c),
            LexerError::UnexpectedEndOfFile => write!(f, "Unexpected end of input"),
            LexerError::InvalidNumber => write!(f, "Invalid number literal"),
        }
    }
}

impl std::error::Error for LexerError {}


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2022 informedcitizenry <informedcitizenry@gmail.com>
//
// Licensed under the MIT license. See LICENSE for full license information.
//
//-----------------------------------------------------------------------------

using Antlr4.Runtime;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

namespace Sixty502DotNet
{
    /// <summary>
    /// A simple, flexible error log.
    /// </summary>
    public class ErrorLog : BaseErrorListener
    {
        private readonly HashSet<Error> _errors;
        private readonly bool _warningsAsErrors;
        private bool _hasErrors;
        private bool _hasWarnings;
        private bool _hasCriticalErrors;

        /// <summary>
        /// Construct a new instance of the <see cref="ErrorLog"/> class.
        /// </summary>
        public ErrorLog()
            : this(false)
        {

        }

        /// <summary>
        /// Construct a new instance of the <see cref="ErrorLog"/> class.
        /// </summary>
        /// <param name="warningsAsErrors">Treat warnings as error.</param>
        public ErrorLog(bool warningsAsErrors)
            => (_errors, _warningsAsErrors, _hasErrors) = (new HashSet<Error>(), warningsAsErrors, false);

        /// <summary>
        /// Log a parsing syntax error.
        /// </summary>
        /// <param name="output">The error writer output.</param>
        /// <param name="recognizer">The recognizer reporting the parsing error.</param>
        /// <param name="offendingSymbol">The source of the syntax error.</param>
        /// <param name="line">The line in source.</param>
        /// <param name="charPositionInLine">The character position in the line of soure.</param>
        /// <param name="msg">The parsing error messsage.</param>
        /// <param name="e">The recognition exception, if any.</param>
        public override void SyntaxError(TextWriter output, IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
        {
            if (recognizer is Parser parser)
            {
                var ruleContext = parser.RuleContext;
                if (e is not CustomParseError)
                {
                    if (e is RecognitionException)
                    {
                        if (offendingSymbol.Type == Lexer.Eof)
                        {
                            msg = "Unexpected end of file encoutered.";
                        }
                        else
                        {
                            msg = $"Unexpected token \"{offendingSymbol.Text}\".";
                        }
                    }
                    else
                    {
                        msg = Sixty502DotNet.Errors.UnexpectedExpression;
                    }
                }
                LogEntry(ruleContext, offendingSymbol, msg, true);
            }
            base.SyntaxError(output, recognizer, offendingSymbol, line, charPositionInLine, msg, e);
        }

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="token">The token that is the source of the error or warning.</param>
        /// <param name="message">The message.</param>
        /// <param name="isError">The message is an error.</param>
        public void LogEntry(Token token, string message, bool isError)
            => LogEntry(null, token, message, isError);

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="token">The token that is the source of the error or warning.</param>
        /// <param name="message">The message.</param>
        public void LogEntry(Token token, string message)
            => LogEntry(null, token, message, true);

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="context">The parse tree context where the error or warning ocurred.</param>
        /// <param name="message">The message.</param>
        public void LogEntry(ParserRuleContext context, string message)
            => LogEntry(context, (Token)context.Start, message, true);

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="context">The parse tree context where the error or warning ocurred.</param>
        /// <param name="message">The message.</param>
        /// <param name="isError">The message is an error.</param>
        public void LogEntry(ParserRuleContext context, string message, bool isError)
            => LogEntry(context, (Token)context.Start, message, isError);

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="context">The parse tree context where the error or warning ocurred.</param>
        /// <param name="offendingSymbol">The token that is the source of the error or warning.</param>
        /// <param name="message">The message.</param>
        public void LogEntry(ParserRuleContext? context, IToken offendingSymbol, string message)
            => LogEntry(context, offendingSymbol, message, true);

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="context">The parse tree context where the error or warning ocurred.</param>
        /// <param name="offendingSymbol">The token that is the source of the error or warning.</param>
        /// <param name="message">The message.</param>
        /// <param name="isError">The message is an error.</param>
        public void LogEntry(ParserRuleContext? context, IToken offendingSymbol, string message, bool isError)
        {
            var line = offendingSymbol.Line;
            var charPositionInLine = offendingSymbol.Column;
            var token = offendingSymbol as Token;
            isError |= _warningsAsErrors;
            _hasErrors |= isError;
            _hasWarnings |= !isError;
            _errors.Add(new Error(context, message, token, token!.Filename, line, charPositionInLine, isError));
        }

        public void LogCriticalError(string message)
        {
            var consoleColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Error.WriteLine("One or more critical errors encountered: ");
            Console.ForegroundColor = consoleColor;
            LogEntrySimple(message);
            _hasCriticalErrors = true;
        }

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="message"></param>
        public void LogEntrySimple(string message)
            => LogEntrySimple(message, true);

        /// <summary>
        /// Log a message.
        /// </summary>
        /// <param name="message"></param>
        /// <param name="isError"></param>
        public void LogEntrySimple(string message, bool isError)
        {
            _errors.Add(new Error(message, isError));
            _hasErrors |= isError;
            _hasWarnings |= !isError;
        }

        /// <summary>
        /// Dump messages.
        /// </summary>
        /// <param name="includeWarnings"></param>
        /// <param name="noHighlighting"></param>
        public void Dump(bool includeWarnings, bool noHighlighting) => Dump(includeWarnings, noHighlighting, Console.Error);

        /// <summary>
        /// Dump messages.
        /// </summary>
        /// <param name="includeWarnings"></param>
        /// <param name="noHighlighting"></param>
        /// <param name="writer">The <see cref="TextWriter"/> to output
        /// the log.</param>
        public void Dump(bool includeWarnings, bool noHighlighting, TextWriter writer)
        {
            foreach (var e in _errors)
            {
                if ((includeWarnings && !_hasCriticalErrors) || e.IsError)
                {
                    e.Print(noHighlighting, writer);
                }
            }
            if (!_hasCriticalErrors)
            {
                PrintLogCount(writer);
            }
        }

        /// <summary>
        /// Print the count of log messages.
        /// </summary>
        public void PrintLogCount() => PrintLogCount(Console.Out);

        /// <summary>
        /// Print the count of log messages.
        /// </summary>
        /// <param name="writer">The <see cref="TextWriter"/> to output the
        /// log count.</param>
        public void PrintLogCount(TextWriter writer)
        {
            writer.WriteLine($"Number of errors: {ErrorCount}");
            writer.WriteLine($"Number of warnings: {WarningCount}");
        }

        /// <summary>
        /// Dump errors.
        /// </summary>
        /// <param name="noHighlighting">Suppress highlighting the
        /// sources of errors in the messages.</param>
        public void DumpErrors(bool noHighlighting)
            => DumpErrors(noHighlighting, Console.Error);

        /// <summary>
        /// Dump errors.
        /// </summary>
        /// <param name="noHighlighting">Suppress highlighting the
        /// sources of errors in the messages.</param>
        /// <param name="writer">The output to dump the error messages.</param>
        public void DumpErrors(bool noHighlighting, TextWriter writer)
        {
            foreach (var e in _errors.Where(e => e.IsError))
            {
                e.Print(noHighlighting, writer);
            }
        }

        /// <summary>
        /// Clear the log.
        /// </summary>
        public void Clear() => _errors.Clear();

        /// <summary>
        /// Get the list of errors.
        /// </summary>
        public ReadOnlyCollection<Error> Errors => _errors.ToList().AsReadOnly();

        /// <summary>
        /// Get if errors have been logged.
        /// </summary>
        public bool HasErrors => _hasErrors;

        /// <summary>
        /// Get if warnings have been logged.
        /// </summary>
        public bool HasWarnings => _hasWarnings;

        /// <summary>
        /// Get if any messages have been logged.
        /// </summary>
        public bool HasMessages => _hasErrors || _hasWarnings;

        /// <summary>
        /// Get the error count.
        /// </summary>
        public int ErrorCount => _errors.Count(e => e.IsError);

        /// <summary>
        /// Get the warning count.
        /// </summary>
        public int WarningCount => _errors.Count(e => !e.IsError);
    }
}


text:
enum class MessageType : short
{
    kHiHoneyGiveMeFood,

	kFoodCompleted,
	kEatCompleted,
	kToiletUseCompleted,
    kStudyCompleted,
    kWatchTVCompleted,
    kSleepCompleted,

    kBedArrived,
	kMineArrived,
	kBankArrived,
	kHomeArrived,
    kToiletArrived,
    kKitchenArrived,
    kSchoolArrived,

    kMoveEntity,
    kPushLog
};

class MoveEntityDataBundle
{

public:

    Entity entity;
    Location dest;
    double spendTime;

    MoveEntityDataBundle() : entity(Entity::kDefault), dest(Location::kDefault), spendTime(0.0f)
    {}

    MoveEntityDataBundle(Entity entity, Location dest, double spendTime) : entity(entity), dest(dest), spendTime(spendTime)
    {}

    MoveEntityDataBundle(const MoveEntityDataBundle& rhs) : entity(rhs.entity), dest(rhs.dest), spendTime(rhs.spendTime)
    {}

    MoveEntityDataBundle& operator=(const MoveEntityDataBundle& rhs)
    {
        if(this == &rhs)
        {
            return *this;
        }
        entity = rhs.entity;
        dest = rhs.dest;
        spendTime = rhs.spendTime;
        return *this;
    }

};

class PushLogDataBundle
{

public:

    Entity entity;
    std::string text;

    PushLogDataBundle() : entity(Entity::kDefault)
    {}

    PushLogDataBundle(Entity entity, std::string text) : entity(entity), text(text)
    {}

    PushLogDataBundle(const PushLogDataBundle& rhs) : entity(rhs.entity), text(rhs.text)
    {}

    PushLogDataBundle& operator=(const PushLogDataBundle& rhs)
    {
        if(this == &rhs)
        {
            return *this;
        }
        entity = rhs.entity;
        text = rhs.text;
        return *this;
    }
};

class PushMessageQueueDataBundle
{

public:

    std::string                     sender;
    std::string                     receiver;
    double                          remainSeconds;
    MessageType                     messageType;

    PushMessageQueueDataBundle() :
    sender(sender),
    receiver(receiver),
    remainSeconds(remainSeconds),
    messageType(messageType)
    {}

    PushMessageQueueDataBundle(std::string  sender, std::string  receiver, double remainSeconds, MessageType messageType) :
    sender(sender),
    receiver(receiver),
    remainSeconds(remainSeconds),
    messageType(messageType)
    {}

    PushMessageQueueDataBundle(const PushMessageQueueDataBundle& rhs) :
    sender(rhs.sender),
    receiver(rhs.receiver),
    remainSeconds(rhs.remainSeconds),
    messageType(rhs.messageType)
    {}

    PushMessageQueueDataBundle& operator=(const PushMessageQueueDataBundle& rhs)
    {
        if(this == &rhs)
        {
            return *this;
        }
        sender = rhs.sender;
        receiver = rhs.receiver;
        remainSeconds = rhs.remainSeconds;
        messageType = rhs.messageType;
        return *this;
    }

};


text:
import { readFileSync } from 'fs';
import { transpileModule, ScriptTarget, ModuleKind } from 'typescript';

const requireFromString: (js: string, filepath?: string) => any = require('require-from-string');

export function loadFile<T>(path: string, verbose: boolean = false): T {
  let script = readFileSync(path, { encoding: 'utf8' });

  if (path.endsWith('.ts')) {
    let result = transpileModule(script, {
      compilerOptions: {
        target: ScriptTarget.ES2015,
        module: ModuleKind.CommonJS,
        experimentalDecorators: true,
        emitDecoratorMetadata: true,
        lib: ['es2016']
      }
    });

    if (verbose) {
      console.log(JSON.stringify(result.diagnostics, null, 4));
    }

    script = result.outputText;
  }

  return requireFromString(script, path);
}


text:
package org.sqlite;

import static org.assertj.core.api.Assertions.assertThat;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.jupiter.api.Test;

/** A test to make sure that getMetadata is properly freed */
public class MetadataLeakTest {
    /**
     * Check that statement is properly closed when result set is closed. See
     * https://github.com/xerial/sqlite-jdbc/issues/423
     *
     * @throws Exception on failure
     */
    @Test
    void testMemoryIsFreed() throws Exception {
        try (Connection con = DriverManager.getConnection("jdbc:sqlite::memory:")) {
            DatabaseMetaData meta = con.getMetaData();

            Statement statement;
            try (ResultSet tables = meta.getTables(null, null, null, null); ) {
                statement = tables.getStatement();
                assertThat(statement.isClosed()).isFalse();
            }
            assertThat(statement.isClosed()).isTrue();
        }
    }
}


text:
/**
 * IDs hasher
 */
export declare class IdHash {
    /**
     * The seed
     */
    protected seed: string;
    /**
     * Generates a random seed
     */
    static generateSeed(): string;
    /**
     * Create a new ID hasher
     * @param {?} seed Set to String to use a predefined seed and TRUE to generate a new one
     */
    constructor(seed?: string | boolean);
    /**
     * Get seed
     */
    getSeed(): string;
    /**
     * Set seed
     */
    setSeed(seed: string): IdHash;
    /**
     * Equivalent to: `hasher.setSeed(IdHash.generateSeed());`
     */
    useRandomSeed(): IdHash;
    /**
     * Encode the given ID
     */
    encode(id: number): string;
    /**
     * Decode the given hash
     */
    decode(hash: string): number;
}


text:
package org.jzb.execution.domain;

import com.fasterxml.jackson.annotation.JsonGetter;
import com.sun.security.auth.UserPrincipal;
import org.apache.commons.io.FileUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.jzb.J;
import org.jzb.execution.Util;

import javax.persistence.*;
import java.io.File;
import java.time.LocalDate;

import static org.jzb.execution.Constant.UPLOAD_BASE_PATH;

/**
 * Created by jzb on 17-4-15.
 */
@Entity
@Table(name = "T_UPLOADFILE")
@NamedQueries({
        @NamedQuery(name = "UploadFile.findBySha256Hex", query = "SELECT o FROM UploadFile o WHERE o.sha256Hex=:sha256Hex")
})
public class UploadFile extends AbstractLogable {
    @Column(unique = true)
    @NotBlank
    private String sha256Hex;
    @NotBlank
    private String fileName;
    private long fileSize;
    private String mediaType;

    public File _file() {
        LocalDate ld = J.localDate(getCreateDateTime());
        String year = String.valueOf(ld.getYear());
        String month = String.valueOf(ld.getMonthValue());
        String day = String.valueOf(ld.getDayOfMonth());
        return FileUtils.getFile(UPLOAD_BASE_PATH, year, month, day, id);
    }

    @JsonGetter
    public String getDownloadToken() {
        return Util.downloadToken(new UserPrincipal(getCreator().getName()), _file(), getMediaType(), getFileName());
    }

    public String getSha256Hex() {
        return sha256Hex;
    }

    public void setSha256Hex(String sha256Hex) {
        this.sha256Hex = sha256Hex;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public long getFileSize() {
        return fileSize;
    }

    public void setFileSize(long fileSize) {
        this.fileSize = fileSize;
    }

    public String getMediaType() {
        return mediaType;
    }

    public void setMediaType(String mediaType) {
        this.mediaType = mediaType;
    }
}


text:
var jsontr = require('./json-transform.js');

var items = require('./exhibits.json');
var transform = {
  uuid: {
    props: {value:String}
  },
  created: {
    props: {value:Number}
  },
  changed: {
    props: {value:Number}
  },
  sticky: {
    props: {value:Boolean}
  },
  promote: {
    props: {value:Boolean}
  },
  title: {
    props: {value: String}
  },
  body: {
    props: {value: String}
  },
  field_date: {
    newName: "date",
    props: {value: String}
  },
  field_end_date: {
    newName: "endDate",
    props: {value: String}
  },
  field_image: {
    newName: "image",
    publishImage: 'url',
    props: {alt:String, width:Number, height:Number, url:String,
            target_uuid:{
              type: String,
              newName: "uuid"
            }
           }
  },
  field_main_exhibit: {
    newName: "mainExhibit",
    props: {value: Boolean}
  },
  field_exhibition_status_type: {
    newName: "exhibitStatus",
    props: {value: String}
  },
  field_further_location_informati: {
    newName: "furtherLocInfo",
    props: {value:String}
  },
  field_library: {
    newName: "library",
    props: {target_uuid:String}
  },
  field_link_to_exhibit_informatio: {
    newName: "link",
    props: {value: String}
  },
  field_location_url: {
    newName: "locationURL",
    props: {value:String}
  }
};

var json = JSON.stringify( jsontr.transform(items,transform) ).replace("drupal.lib.virginia.edu/sites/default","wwwstatic.lib.virginia.edu");
console.log( json );


text:
package org.onosproject.pcepio.types;

import com.google.common.testing.EqualsTester;
import org.junit.Test;

/**
 * Test of the LinkLocalRemoteIdentifiersSubTlv.
 */
public class LinkLocalRemoteIdentifiersSubTlvTest {

    private final LinkLocalRemoteIdentifiersSubTlv tlv1 = LinkLocalRemoteIdentifiersSubTlv.of(10, 20);
    private final LinkLocalRemoteIdentifiersSubTlv sameAsTlv1 = LinkLocalRemoteIdentifiersSubTlv.of(10, 20);
    private final LinkLocalRemoteIdentifiersSubTlv tlv2 = LinkLocalRemoteIdentifiersSubTlv.of(20, 30);

    @Test
    public void basics() {
        new EqualsTester()
        .addEqualityGroup(tlv1, sameAsTlv1)
        .addEqualityGroup(tlv2)
        .testEquals();
    }
}


text:
For information about wfLZ, see https://github.com/ShaneWF/wflz

## Codecs ##

- **wflz** — Raw wfLZ data.
- **wflz-chunked** — Chunked wfLZ.

## Options ##

- **level** (integer, 1-2, default 1) — compression level.  Lower is
  faster, higher has a better compression ratio.  2 is currently
  *very* slow.
- **chunk-size** (*wflz-chunked*-only, integer, 4096 - UINT32_MAX,
  multiple of 16, default 16384) — chunk size.

### Compression Only ###

- **endianness** (enum, "little" or "big", default "little") —
  Endianness of the compressed file.

## License ##

The wflz plugin is licensed under the [MIT
License](http://opensource.org/licenses/MIT), and wfLZ is licensed
under the [WTFPL](http://www.wtfpl.net/).


text:
package org.gradle.api.internal.artifacts.ivyservice.ivyresolve;

import org.gradle.internal.component.external.model.ModuleComponentResolveMetadata;

class RepositoryChainModuleResolution implements StringVersioned {
    public final ModuleComponentRepository repository;
    public final ModuleComponentResolveMetadata module;

    public RepositoryChainModuleResolution(ModuleComponentRepository repository, ModuleComponentResolveMetadata module) {
        this.repository = repository;
        this.module = module;
    }

    public String getVersion() {
        return module.getModuleVersionId().getVersion();
    }
}


text:
<script>
    StrolchInspectorPagingBehavior = {

        properties: {
            dataObj: {
                type: Object,
                value: {
                    data: null,
                    offset: 0,
                    limit: 20,
                    dataSetSize: 0,
                    descending: true,
                    sortBy: 'id',
                    size: 0,
                    nextOffset: 0,
                    previousOffset: 0,
                    lastOffset: 0
                }
            }
        },

        _getDefaultObj: function () {
            return {
                data: null,
                offset: 0,
                limit: 20,
                dataSetSize: 0,
                descending: true,
                sortBy: 'id',
                size: 0,
                nextOffset: 0,
                previousOffset: 0,
                lastOffset: 0
            }
        },

        _hasNext: function (dataObj) {
            return dataObj != null && dataObj.nextOffset > dataObj.offset;
        },
        _hasPrevious: function (dataObj) {
            return dataObj != null && dataObj.previousOffset < dataObj.offset;
        },

        _getEnd: function (dataObj) {
            if (this._hasNext(dataObj)) return dataObj.nextOffset;
            return dataObj == null ? 0 : dataObj.size;
        },

        _setLimit: function (e) {
            this.dataObj.limit = parseInt(e.target.textContent.trim());
            this.queryPage();
        },

        _toFirstPage: function () {
            this.dataObj.offset = 0;
            this.queryPage();
        },
        _toPreviousPage: function () {
            this.dataObj.offset = this.dataObj.previousOffset;
            this.queryPage();
        },
        _toNextPage: function () {
            this.dataObj.offset = this.dataObj.nextOffset;
            this.queryPage();
        },
        _toLastPage: function () {
            this.dataObj.offset = this.dataObj.lastOffset;
            this.queryPage();
        }
    };
</script>


text:
<?php

namespace NicMart\Generics\Example\PHP5\Product;

/**
 * Class AbstractTuple
 * @package NicMart\Generics\Example\PHP5\Product
 */
abstract class AbstractTuple implements Product
{
    /**
     * @param $n
     */
    protected function assertValidIndex($n)
    {
        if ($n >= $this->arity()) {
            throw new \UnexpectedValueException(
                "Index must be less than the arity"
            );
        }
    }

    /**
     * @return \Iterator
     */
    public function iterator()
    {
        return new \ArrayIterator(array_values((array) $this));
    }
}


text:
using DotLiquid;
using System;
using ZKWebStandard.Extensions;

namespace ZKWeb.Localize {
	///
	/// A class wrap original text and return translated text

	/// Translation will perform when calling ToString

	/// This class can convert to string implicit, or use ToString explicit

	/// 用于包装原文并返回译文的类

	/// 翻译会在调用ToString函数时执行

	/// 这个类可以隐式转换到string, 也可以显式调用ToString函数

	///
	/// <seealso cref="ITranslateProvider"/>
	/// <seealso cref="TranslateManager"/>
	/// <example>
	///
	/// string translated = new T("Original");
	///
	/// </example>
	public struct T : ILiquidizable, IEquatable<T> {
		///
		/// Original text

		/// 原文

		///
		private string Text { get; set; }
		///
		/// Format parameters

		/// 格式化参数

		///
		private object[] Parameters { get; set; }

		///
		/// Get the translation of text

		/// 获取文本的翻译

		///
		/// <param name="text">Original text</param>
		public T(string text) : this(text, null) { }

		///
		/// Get the translation of formatted text

		/// 获取格式化的文本的翻译

		///
		/// <param name="text">Original text</param>
		/// <param name="parameters">Format parameters</param>
		public T(string text, params object[] parameters) {
			Text = text;
			Parameters = parameters;
		}

		///
		/// Get translated text

		/// 获取翻译后的文本

		///
		/// <param name="t">This object</param>
		public static implicit operator string(T t) {
			return t.ToString();
		}

		///
		/// Support render to template

		/// 支持描画到模板

		///
		/// <returns></returns>
		object ILiquidizable.ToLiquid() {
			return ToString();
		}

		///
		/// Get translated text

		/// 获取翻译后的文本

		///
		/// <returns></returns>
		public override string ToString() {
			var translateManager = Application.Ioc.Resolve<TranslateManager>();
			var text = translateManager.Translate(Text);
			if (Parameters != null) {
				text = string.Format(text, Parameters);
			}
			return text;
		}

		///
		/// Compare two objects are equatable

		/// 比较两个对象是否相等

		///
		public bool Equals(T other) {
			return Text == other.Text &&
				Parameters.EqualsSupportsNull(other.Parameters);
		}
	}
}


text:
namespace bgTeam.DataAccess.Impl.Memory
{
    using System;
    using System.Linq;
    using System.Threading;

    public class CacheRepository<TKey, TValue> : BaseMemoryRepository<TKey, CacheValue<TValue>>, ICacheRepository<TKey, TValue>
    {
        protected const int _defaultCacheMinutes = 10;
        protected readonly bool _defaultIsTouched = false;
        protected readonly TimeSpan _expireTime;
        protected readonly Timer _timer;

        protected readonly IMemoryRepository<TKey, CacheValue<TValue>> _repository;

        public CacheRepository()
                    : this(new TimeSpan(0, _defaultCacheMinutes, 0), false)
        {
        }

        public CacheRepository(TimeSpan expireTime)
                    : this(expireTime, false)
        {
        }

        public CacheRepository(bool defaultIsTouched)
                    : this(new TimeSpan(0, _defaultCacheMinutes, 0), defaultIsTouched)
        {
        }

        public CacheRepository(TimeSpan expireTime, bool defaultIsTouched)
            : base()
        {
            _expireTime = expireTime;
            _repository = new MemoryRepository<TKey, CacheValue<TValue>>();
            _timer = new Timer(Clear, null, new TimeSpan(0, 0, 0), new TimeSpan(0, 2, 0));
            _defaultIsTouched = defaultIsTouched;
        }

        public virtual bool TryGetValue(TKey key, out TValue value, bool? isTouched)
        {
            var result = base.TryGetValue(key, out CacheValue<TValue> cacheValue);
            if (!result || cacheValue.IsExpire)
            {
                value = default(TValue);
                return false;
            }

            isTouched = isTouched ?? _defaultIsTouched;
            if ((bool)isTouched)
            {
                cacheValue.Refresh(_expireTime);
            }

            value = cacheValue.Value;
            return result;
        }

        public virtual bool TryGetValue(TKey key, out TValue value)
        {
            return this.TryGetValue(key, out value, null);
        }

        public virtual bool TrySetValue(TKey key, TValue value)
        {
            var newVal = new CacheValue<TValue>(value, _expireTime);
            return base.TrySetValue(key, newVal);
        }

        public virtual new int Count()
        {
            return base.Count();
        }

        public virtual new IQueryable<TValue> GetAll()
        {
            return base.GetAll().Select(x => x.Value);
        }

        public virtual new bool Remove(TKey key)
        {
            return base.Remove(key);
        }

        protected virtual void Clear(object state)
        {
            foreach (var item in _container)
            {
                if (item.Value.IsExpire)
                {
                    this.Remove(item.Key);
                }
            }
        }

        protected new bool TryGetValue(TKey key, out CacheValue<TValue> value)
        {
            return base.TryGetValue(key, out value);
        }

        protected new bool TrySetValue(TKey key, CacheValue<TValue> value)
        {
            return base.TrySetValue(key, value);
        }
    }
}


text:
class Engine {
  constructor(cubicCapacity, fuel) {
    this.cubicCapacity = cubicCapacity;
    this.fuel = fuel;
  }
}

class EngineBuilder {
  constructor() {
    this.cubicCapacity = null;
    this.fuel = null;
  }

  withCubicCapacity(cubicCapacity) {
    this.cubicCapacity = cubicCapacity;
    return this;
  }

  withFuel(fuel) {
    this.fuel = fuel;
    return this;
  }

  build() {
    return new Engine(
      this.cubicCapacity,
      this.fuel
    );
  }
}

module.exports = {
  Engine: Engine,
  EngineBuilder: EngineBuilder
};


text:
package org.image.DAO;

import org.image.model.User;
import org.image.model.UserInformation;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserPageDao {
    DatabaseConnection databaseConnection = new DatabaseConnection();
    Connection connection=null;
    PreparedStatement preparedStatement=null;

    public UserInformation getUserInformation(User user,UserInformation userInformation){
        try{
            connection = databaseConnection.getDbConnection();
            if(connection!=null){
                String sql="select u.id,u.username,s.head_img,s.email,s.birthday,s.sex,s.signature,s.selfintro from selfinf s,users u where u.username=? and u.id=s.belonguserid";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,user.getName());
                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()){
                    userInformation.setBelonguserid(resultSet.getInt("id"));
                    userInformation.setName(resultSet.getString("username"));
                    userInformation.setHead_img(resultSet.getString("head_img"));
                    userInformation.setEmail(resultSet.getString("email"));
                    userInformation.setBirthday(resultSet.getString("birthday"));
                    userInformation.setSex(resultSet.getString("sex"));
                    userInformation.setSignature(resultSet.getString("signature"));
                    userInformation.setSelfintro(resultSet.getString("selfintro"));
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                closeConnection();
            }
            catch (Exception e){

            }
        }
        return userInformation;
    }

    public void setUserInformation(HttpServletRequest request,UserInformation userInformation){
        String name=request.getParameter("name");
        String email=request.getParameter("email");
        String year=request.getParameter("year");
        String month=request.getParameter("month");
        String day=request.getParameter("day");
        String birthday=year+"-"+month+"-"+day;
        String sex=request.getParameter("sex");
        String signature=request.getParameter("signature");
        String selfIntro=request.getParameter("selfIntro");
        try{
            connection = databaseConnection.getDbConnection();
            if(connection!=null){
                String sql="update selfinf s,users u set u.username=?,s.email=?,s.birthday=?,s.sex=?,s.signature=?,s.selfintro=? where s.belonguserid=? and u.id=s.belonguserid";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,name);
                preparedStatement.setString(2,email);
                preparedStatement.setString(3,birthday);
                preparedStatement.setString(4,sex);
                preparedStatement.setString(5,signature);
                preparedStatement.setString(6,selfIntro);
                preparedStatement.setInt(7,userInformation.getBelonguserid());

                preparedStatement.executeUpdate();

                userInformation.setName(name);
                userInformation.setEmail(email);
                userInformation.setBirthday(birthday);
                userInformation.setSex(sex);
                userInformation.setSignature(signature);
                userInformation.setSelfintro(selfIntro);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                closeConnection();
            }
            catch (Exception e){

            }
        }

    }

    public void updateHead(String belongid,String path){
        try{
            connection = databaseConnection.getDbConnection();
            if (connection!=null){
                String sql="update selfinf set head_img=? where belonguserid=?";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1,path);
                preparedStatement.setString(2,belongid);
                preparedStatement.executeUpdate();

            }
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                closeConnection();
            }
            catch (Exception e){

            }
        }
    }

    private void closeConnection(){
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connection = null;
        }
    }
}


text:
import sys
sys.path.insert(0, '../3rdparty')
sys.path.insert(0, '../lib')

import ofx
import ofx_test_utils

import unittest

class DocumentTests(unittest.TestCase):
    def setUp(self):
        self.checking = ofx_test_utils.get_checking_stmt()

    def test_statement_as_xml(self):
        response = ofx.Response(self.checking)
        self.assertEqual('<?xml version="1.0"', response.as_xml()[:19])

if __name__ == '__main__':
    unittest.main()


text:
struct RegData
{
	ULONG validateHwndOffset;
	ULONG gpresUserOffset;
	ULONG userGetAtomNameOffset;
	ULONG atomArrayOffset;
	ULONG grpWinstaListOffset;
};

extern "C"
{
	NTSTATUS InitializeEnvironment(PUNICODE_STRING pusRegPath);
	NTSTATUS QueryRegistryParams(const UNICODE_STRING& usRegPath, RegData& regData);
	PVOID GetModuleAddress(const STRING& sModuleToFile, ULONG& moduleSize);
}

#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, InitializeEnvironment)
#pragma alloc_text(INIT, QueryRegistryParams)
#pragma alloc_text(PAGE, GetModuleAddress)
#endif

#endif


text:
package com.leansoft.mxjc.util;

import java.io.File;

/**
 * Utility to for class/package name handling
 *
 * @author bulldog
 *
 */
public final class ClassNameUtil {

	/**
	 * Strip qualifier of a fully qualified class name,
	 *
	 * @param className, fully qualified class name, such as java.util.List
	 * @return qualified stripped class name, such List
	 */
    public static String stripQualifier(String className) {
        String qual = getQualifier(className);
        if (qual == null) return className;
        int len = className.length();
        return className.substring(qual.length() + 1, len);
    }

    /**
     *
     * Get package name a fully qualified class name
     *
     * @param className, fully qualified class anme, such as java.util.List
     * @return package name, such as java.util
     */
    public static String getPackageName(String className) {
        String packageName = getQualifier(className);
        return packageName != null ? packageName : "";
    }

	/**
	 * Get qualifier of a class name
	 *
	 * @param className, full qualified class name, such as java.util.List
	 * @return String qualifier, such as java.util
	 */
    public static String getQualifier(String className) {
    	String name = className;
    	if (name.indexOf('<') >= 0) {//is generic class?
    		name = erase(name);
    	}
        int index = name.lastIndexOf('.');
        return (index < 0) ? null : name.substring(0, index);
    }

    /**
     *
     * Erase type parameters of a generic class
     *
     * @param className Generic class name, such as java.util.List<java.lang.String>
     * @return type parameters erased class name, such as java.util.List
     */
    public static String erase(String className) {
       int index = className.indexOf('<');
       if(index < 0)
           return className;
       return (index > 0)?className.substring(0, index):className;
    }

    /**
     * change package name into a relative file path
     * @param pkgName, the name of the package
     * @return relative file path
     */
    public static String packageNameToPath(String pkgName) {
    	if (pkgName == null) return null;
    	String path = pkgName.replace('.', File.separatorChar);
    	return path;
    }

}


text:
"""Wrapper for SQL API client."""

from httplib2 import HttpLib2Error
from ratelimiter import RateLimiter

from google.cloud.security.common.gcp_api import _base_client
from google.cloud.security.common.gcp_api import errors as api_errors
from google.cloud.security.common.util import log_util
from googleapiclient.errors import HttpError

LOGGER = log_util.get_logger(__name__)

class CloudsqlClient(_base_client.BaseClient):
    """CloudSQL Client."""

    API_NAME = 'sqladmin'
    DEFAULT_QUOTA_TIMESPAN_PER_SECONDS = 100  # pylint: disable=invalid-name

    def __init__(self, global_configs, credentials=None):
        """Initialize.

        Args:
            global_configs (dict): Global configurations.
            credentials (GoogleCredentials): Google credentials for auth-ing
                to the API.
        """
        super(CloudsqlClient, self).__init__(
            global_configs, credentials=credentials, api_name=self.API_NAME)

        self.rate_limiter = RateLimiter(
            self.global_configs.get('max_sqladmin_api_calls_per_100_seconds'),
            self.DEFAULT_QUOTA_TIMESPAN_PER_SECONDS)

    def get_instances(self, project_id):
        """Gets all CloudSQL instances for a project.

        Args:
            project_id (int): The project id for a GCP project.

        Returns:
            dict: If successful, this function returns a dictionary for the
                instances in the project.
            {
              "kind": "sql#instancesList",
              "nextPageToken": string,
              "items": [
                instances Resource
              ]
            }

        Raises:
            ApiExecutionError: ApiExecutionError is raised if the call to the
                GCP ClodSQL API fails
        """
        instances_api = self.service.instances()
        try:
            instances_request = instances_api.list(project=project_id)
            instances = self._execute(instances_request, self.rate_limiter)
            return instances
        except (HttpError, HttpLib2Error) as e:
            LOGGER.error(api_errors.ApiExecutionError(project_id, e))
            raise api_errors.ApiExecutionError('instances', e)


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

// Define DEBUG just for this file (#define in C# only operates per file
// as opposed to C / C++ which defines from that point onward) to be able
// to use Debug.WriteLine even in a release build

// Windows 2012 doesn't define the more generic variants

#if (NETFRAMEWORK || NET462 || NETCOREAPP || NETCOREAPP3_1_OR_GREATER) && !NET6_0_WINDOWS10_0_19041_0 && !__MOBILE__
#define DEBUG
using System;
using System.Diagnostics;
using System.Threading;

using Couchbase.Lite.DI;
using Couchbase.Lite.Logging;

namespace Couchbase.Lite.Support
{
    [CouchbaseDependency]
    internal sealed class DesktopConsoleLogger : IConsoleLogger
    {
        #region Properties

        public LogDomain Domains { get; set; } = LogDomain.All;

        public LogLevel Level { get; set; } = LogLevel.Warning;

        #endregion

        #region Private Methods

        private static string MakeMessage(string message, LogLevel level, LogDomain domain)
        {
            var dateTime = DateTime.Now.ToLocalTime().ToString("yyyy-M-d hh:mm:ss.fffK");
            var threadId = Thread.CurrentThread.Name ?? Thread.CurrentThread.ManagedThreadId.ToString();
            return $"{dateTime} [{threadId}]| {level.ToString().ToUpperInvariant()})  [{domain}] {message}";
        }

        #endregion

        #region ILogger

        public void Log(LogLevel level, LogDomain domain, string message)
        {
            if (level < Level || !Domains.HasFlag(domain)) {
                return;
            }

            var finalStr = MakeMessage(message, level, domain);
            Console.WriteLine(finalStr);
            if (Debugger.IsAttached) {
                Debug.WriteLine(finalStr);
            }
        }

        #endregion
    }
}
#endif


text:
package org.eclipse.microprofile.metrics.tck.cdi;

import org.eclipse.microprofile.metrics.Counter;
import org.eclipse.microprofile.metrics.Gauge;
import org.eclipse.microprofile.metrics.annotation.Metric;
import org.eclipse.microprofile.metrics.tck.util.FooQualifier;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;

@ApplicationScoped
public class MetricProducerFieldBean {

    @Produces
    @Metric(name = "counter1", absolute = true)
    private final Counter counter1 = new SimpleCounter() {

    };

    @Produces
    @Metric(name = "counter2", absolute = true)
    private final Counter counter2 = new SimpleCounter();

    @Produces
    @Metric(name = "ratioGauge", absolute = true)
    private final Gauge<Double> gauge = new Gauge<Double>() {
        public Double getValue() {
            return (double) counter1.getCount() / (double) counter2.getCount();
        };
    };

    @Produces
    @FooQualifier
    @Metric(name = "not_registered_metric", absolute = true)
    private final Counter not_registered_metric = new SimpleCounter();

    class SimpleCounter implements Counter {

        private long count;

        @Override
        public void inc() {
            count++;
        }

        @Override
        public void inc(long n) {
            count += n;
        }

        @Override
        public long getCount() {
            return count;
        }
    }

    @Override
    public String toString() {
        return "MetricProducerFieldBean{}";
    }
}


text:
import { SentryError } from './error';
import { rejectedSyncPromise, resolvedSyncPromise, SyncPromise } from './syncpromise';

export interface PromiseBuffer<T> {
  // exposes the internal array so tests can assert on the state of it.
  // XXX: this really should not be public api.
  $: Array<PromiseLike<T>>;
  add(taskProducer: () => PromiseLike<T>): PromiseLike<T>;
  drain(timeout?: number): PromiseLike<boolean>;
}

/**
 * Creates an new PromiseBuffer object with the specified limit
 * @param limit max number of promises that can be stored in the buffer
 */
export function makePromiseBuffer<T>(limit?: number): PromiseBuffer<T> {
  const buffer: Array<PromiseLike<T>> = [];

  function isReady(): boolean {
    return limit === undefined || buffer.length < limit;
  }

  /**
   * Remove a promise from the queue.
   *
   * @param task Can be any PromiseLike<T>
   * @returns Removed promise.
   */
  function remove(task: PromiseLike<T>): PromiseLike<T> {
    return buffer.splice(buffer.indexOf(task), 1)[0];
  }

  /**
   * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.
   *
   * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:
   *        PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor
   *        functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By
   *        requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer
   *        limit check.
   * @returns The original promise.
   */
  function add(taskProducer: () => PromiseLike<T>): PromiseLike<T> {
    if (!isReady()) {
      return rejectedSyncPromise(new SentryError('Not adding Promise due to buffer limit reached.'));
    }

    // start the task and add its promise to the queue
    const task = taskProducer();
    if (buffer.indexOf(task) === -1) {
      buffer.push(task);
    }
    void task
      .then(() => remove(task))
      // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`
      // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't
      // have promises, so TS has to polyfill when down-compiling.)
      .then(null, () =>
        remove(task).then(null, () => {
          // We have to add another catch here because `remove()` starts a new promise chain.
        }),
      );
    return task;
  }

  /**
   * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.
   *
   * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or
   * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to
   * `true`.
   * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and
   * `false` otherwise
   */
  function drain(timeout?: number): PromiseLike<boolean> {
    return new SyncPromise<boolean>((resolve, reject) => {
      let counter = buffer.length;

      if (!counter) {
        return resolve(true);
      }

      // wait for `timeout` ms and then resolve to `false` (if not cancelled first)
      const capturedSetTimeout = setTimeout(() => {
        if (timeout && timeout > 0) {
          resolve(false);
        }
      }, timeout);

      // if all promises resolve in time, cancel the timer and resolve to `true`
      buffer.forEach(item => {
        void resolvedSyncPromise(item).then(() => {
          // eslint-disable-next-line no-plusplus
          if (!--counter) {
            clearTimeout(capturedSetTimeout);
            resolve(true);
          }
        }, reject);
      });
    });
  }

  return {
    $: buffer,
    add,
    drain,
  };
}


text: Config screen for pollen forecast watchface


text:
package org.apache.flink.api.scala.typeutils

import org.apache.flink.annotation.Internal
import org.apache.flink.api.common.typeutils._
import org.apache.flink.core.memory.{DataInputView, DataOutputView}

/** Serializer for [[Option]]. */
@Internal
@SerialVersionUID(-8635243274072627338L)
class OptionSerializer[A](val elemSerializer: TypeSerializer[A]) extends TypeSerializer[Option[A]] {

  override def duplicate: OptionSerializer[A] = {
    val duplicatedElemSerializer = elemSerializer.duplicate()

    if (duplicatedElemSerializer.eq(elemSerializer)) {
      this
    } else {
      new OptionSerializer[A](duplicatedElemSerializer)
    }
  }

  override def createInstance: Option[A] = {
    None
  }

  override def isImmutableType: Boolean = elemSerializer == null || elemSerializer.isImmutableType

  override def getLength: Int = -1

  override def copy(from: Option[A]): Option[A] = from match {
    case Some(a) => Some(elemSerializer.copy(a))
    case None => from
  }

  override def copy(from: Option[A], reuse: Option[A]): Option[A] = copy(from)

  override def copy(source: DataInputView, target: DataOutputView): Unit = {
    val isSome = source.readBoolean()
    target.writeBoolean(isSome)
    if (isSome) {
      elemSerializer.copy(source, target)
    }
  }

  override def serialize(either: Option[A], target: DataOutputView): Unit = either match {
    case Some(a) =>
      target.writeBoolean(true)
      elemSerializer.serialize(a, target)
    case None =>
      target.writeBoolean(false)
  }

  override def deserialize(source: DataInputView): Option[A] = {
    val isSome = source.readBoolean()
    if (isSome) {
      Some(elemSerializer.deserialize(source))
    } else {
      None
    }
  }

  override def deserialize(reuse: Option[A], source: DataInputView): Option[A] = deserialize(source)

  override def equals(obj: Any): Boolean = {
    obj match {
      case optionSerializer: OptionSerializer[_] =>
        elemSerializer.equals(optionSerializer.elemSerializer)
      case _ => false
    }
  }

  override def hashCode(): Int = {
    elemSerializer.hashCode()
  }

  // --------------------------------------------------------------------------------------------
  // Serializer configuration snapshotting & compatibility
  // --------------------------------------------------------------------------------------------

  override def snapshotConfiguration(): TypeSerializerSnapshot[Option[A]] = {
    new ScalaOptionSerializerSnapshot[A](this)
  }
}


text:
Mac Installation Instructions
-----------------------------

You might run into a dialog box like this:

![Security-Dialog](https://github.com/malcolmalex/onsight-timer/raw/master/doc/mac-security/file-cant-be-opened.png)

If so, click OK, go to your Mac System Preferences (fromt he Apple at the top left of the menubar), click Security & Privacy:

![Security-Dialog2](https://github.com/malcolmalex/onsight-timer/raw/master/doc/mac-security/system-preferences.png)

Then click on the "Open Anyway" button. This will allow you to run the program:

![Security-Dialog2](https://github.com/malcolmalex/onsight-timer/raw/master/doc/mac-security/open-anyway.png)


text:
namespace Org.Cen.RobotManager.Controls.Servo
{
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;
    using Devices.Servo;
    using Devices.Servo.Com;

    /// <summary>
    /// Interaction logic for ServoControl.xaml
    /// </summary>
    public partial class ServoControl : UserControl
    {
        public int ServoIndex { get; set; }

        private bool readValue = false;

        private bool speedDragStarted = false;
        private bool targetPositionDragStarted = false;

        private MainWindow Main
        {
            get { return (MainWindow)Window.GetWindow(this); }
        }

        public ServoControl()
        {
            InitializeComponent();
        }

        private void ReadServo()
        {
            Main.receivedData.Clear();
            ServoReadParametersOutData outData = new ServoReadParametersOutData(ServoIndex);
            string message = outData.GetMessage();
            Main.SendText(message);

            ServoReadParametersInDataDecoder decoder = new ServoReadParametersInDataDecoder();
            while (Main.receivedData.Length < decoder.GetDataLength(null))
            {
            }
            ServoReadParametersInData inData = (ServoReadParametersInData)decoder.Decode(Main.receivedData.ToString());

            ServoData servoData = inData.Data;

            readValue = true;
            ServoSpeedSlider.Value = servoData.ServoSpeed;
            ServoTargetPositionSlider.Value = servoData.ServoTargetPosition;
            ServoCurrentPositionValueLabel.Content = servoData.ServoCurrentPosition.ToString();
            readValue = false;
        }

        private void WriteServo()
        {
            if (Main == null)
            {
                return;
            }
            int servoSpeed = (int ) ServoSpeedSlider.Value;
            int servoTargetPosition = (int)ServoTargetPositionSlider.Value;
            ServoSpeedValueLabel.Content = servoSpeed.ToString();
            ServoTargetPositionValueLabel.Content = servoTargetPosition.ToString();

            ServoData servoData = new ServoData(ServoIndex, servoSpeed, servoTargetPosition);
            ServoWriteParametersOutData outData = new ServoWriteParametersOutData(servoData);
            string message = outData.GetMessage();
            Main.SendText(message);
        }

        // Event Management

        private void ReadServoParametersButton_Click(object sender, RoutedEventArgs e)
        {
            ReadServo();
        }

        // Speed

        private void ServoSpeedSlider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (readValue || speedDragStarted)
            {
                return;
            }
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            WriteServo();
        }

        private void ServoSpeedSlider_OnDragStarted(object sender, DragStartedEventArgs e)
        {
            speedDragStarted = true;
        }

        private void ServoSpeedSlider_OnDragCompleted(object sender, DragCompletedEventArgs e)
        {
            WriteServo();
            speedDragStarted = false;
        }

        // target Position

        private void ServoTargetPositionSlider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (readValue || targetPositionDragStarted)
            {
                return;
            }
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            WriteServo();
        }

        private void ServoTargetPositionSlider_OnDragStarted(object sender, DragStartedEventArgs e)
        {
            targetPositionDragStarted = true;
        }

        private void ServoTargetPositionSlider_OnDragCompleted(object sender, DragCompletedEventArgs e)
        {
            WriteServo();
            targetPositionDragStarted = false;
        }

        private void ResetServoPositionButton_OnClick(object sender, RoutedEventArgs e)
        {
            ServoTargetPositionSlider.Value = 1500;
        }
    }
}


text:
void initDisplay();

void showLeft();

void showRight();

#endif // DISPLAY_H_


text:
import React, { Component } from 'react';

class UserList extends React.Component {
  constructor(props) {
    super(props);
    this.renderUserNames = this.renderUserNames.bind(this);
    this.renderAccountBalance = this.renderAccountBalance.bind(this);
    this.renderIndex = this.renderIndex.bind(this);
    this.renderAnswer = this.renderAnswer.bind(this);
    this.renderBet = this.renderBet.bind(this);
  }

  renderUserNames(user){
    if(user.id === this.props.user.id){
      return You
    } else {
      return { user.name }
    }
  }

  renderAccountBalance(user){
    return { user.account }
  }

  renderAnswer(user){
    if(user.id === this.props.user.id && this.props.user.answer !== ""){
      return { user.answer }
    } else if(user.answer !== "") {
      return Submitted answer
    } else  {
      return Waiting for answer
    }
  }

  renderIndex(index){
    return {index + 1 }
  }

  renderBet(user){
    return {user.bet}
  }

  render() {
    var that = this;
    return (

            #
            Name
            Balance
            Bet
            Answer

          {
            this.props.users.map(function(user, index){
              return(

                  {that.renderIndex(index)}
                  {that.renderUserNames(user)}
                  {that.renderAccountBalance(user)}
                  {that.renderBet(user)}
                  {that.renderAnswer(user)}

              )
            })
          }

    );
  }
}

export default UserList;


text: It's a personal blog where I take notes of my everyday learning.


text:
require "rails_helper"

describe AssessmentSubmissionService do
  include FormAnswerTestMethods

  subject { described_class.new(assessment, assessor) }

  let(:form_answer) { create(:form_answer, :trade, :submitted) }
  let(:document) { { "verdict_desc" => "description NOT to copy", "verdict_rate" => "positive" } }
  let(:assessor) { create(:assessor, :lead_for_all) }

  before do
    allow_any_instance_of(AssessorAssignment).to receive(:valid?).and_return(true)
    assessment.document = document

    primary = form_answer.assessor_assignments.primary
    primary.assessor_id = assessor.id
    primary.document = { "verdict_desc" => "description to copy", "verdict_rate" => "negative" }
    primary.save!

    create(:settings, :expired_submission_deadlines)
    form_answer.state_machine.perform_transition(:assessment_in_progress)
  end

  context "moderated form submission" do
    let(:assessment) { form_answer.assessor_assignments.moderated }

    it "populates the lead case summary form with values from primary form" do
      expected = {
        "verdict_desc" => "description to copy",
        "verdict_rate" => "positive"
      }

      expect { expect_to_submit }.to change {
        form_answer.assessor_assignments.case_summary.document == expected
      }.from(false).to(true)
    end
  end

  context "case summary submission" do
    let(:form_answer) { create(:form_answer, :development, :submitted) }
    let(:assessment) { form_answer.assessor_assignments.case_summary }

    it "performs state transition when case summary is submitted" do
      assessment.document =  { "verdict_desc" => "description to copy", "verdict_rate" => "negative" }

      subject.perform
      expect(form_answer.reload.state).to eq("not_recommended")
    end
  end

  context "feedback pre-population" do
    let(:assessment) { form_answer.assessor_assignments.primary }

    before do
      assessment.assessor = assessor

      assessment.document = {
        overseas_earnings_growth_desc: "Good",
        overseas_earnings_growth_rate: "positive",
        commercial_success_desc: "Mild",
        commercial_success_rate: "average",
        strategy_desc: "Good",
        strategy_rate: "positive",
        corporate_social_responsibility_desc: "Bad",
        corporate_social_responsibility_rate: "negative",
        verdict_desc: "Mild",
        verdict_rate: "average"
      }

      assessment.save!
    end

    it "pre-populates feedback" do
      subject.perform

      feedback = form_answer.feedback
      expect(feedback).to be

      expected_document = {
        "overseas_earnings_growth_strength" => "Good",
        "overseas_earnings_growth_weakness" => "",
        "commercial_success_weakness" => "Mild",
        "commercial_success_strength" => "",
        "strategy_strength" => "Good",
        "strategy_weakness" => "",
        "corporate_social_responsibility_weakness" => "Bad",
        "corporate_social_responsibility_strength" => "",
        "overall_summary" => "Mild"
      }

      expect(feedback.document).to eq(expected_document)
    end
  end
end

def expect_to_submit
  expect { subject.perform }.to change { assessment.submitted? }.from(false).to(true)
end


text:
<?php
/**
 * Various constants used for flags, data-type encoding and decoding, etc...
 * throughout this SDK.
 *
 * @author Brett Lawson <brett19@gmail.com>
 */

/** @internal */ define('COUCHBASE_VAL_MASK', 0x1F);
/** @internal */ define('COUCHBASE_VAL_IS_STRING', 0);
/** @internal */ define('COUCHBASE_VAL_IS_LONG', 1);
/** @internal */ define('COUCHBASE_VAL_IS_DOUBLE', 2);
/** @internal */ define('COUCHBASE_VAL_IS_BOOL', 3);
/** @internal */ define('COUCHBASE_VAL_IS_SERIALIZED', 4);
/** @internal */ define('COUCHBASE_VAL_IS_IGBINARY', 5);
/** @internal */ define('COUCHBASE_VAL_IS_JSON', 6);
/** @internal */ define('COUCHBASE_COMPRESSION_MASK', 0x7 << 5);
/** @internal */ define('COUCHBASE_COMPRESSION_NONE', 0 << 5);
/** @internal */ define('COUCHBASE_COMPRESSION_ZLIB', 1 << 5);
/** @internal */ define('COUCHBASE_COMPRESSION_FASTLZ', 2 << 5);
/** @internal */ define('COUCHBASE_COMPRESSION_MCISCOMPRESSED', 1 << 4);

/** @internal */ define('COUCHBASE_SERTYPE_JSON', 0);
/** @internal */ define('COUCHBASE_SERTYPE_IGBINARY', 1);
/** @internal */ define('COUCHBASE_SERTYPE_PHP', 2);
/** @internal */ define('COUCHBASE_CMPRTYPE_NONE', 0);
/** @internal */ define('COUCHBASE_CMPRTYPE_ZLIB', 1);
/** @internal */ define('COUCHBASE_CMPRTYPE_FASTLZ', 2);

/** @internal */ define('COUCHBASE_CFFMT_MASK', 0xFF << 24);
/** @internal */ define('COUCHBASE_CFFMT_PRIVATE', 1 << 24);
/** @internal */ define('COUCHBASE_CFFMT_JSON', 2 << 24);
/** @internal */ define('COUCHBASE_CFFMT_RAW', 3 << 24);
/** @internal */ define('COUCHBASE_CFFMT_STRING', 4 << 24);


text:
package io.artsoftware.person.mock;

import io.artsoftware.person.Role;

public final class MockRole implements Role{

    private final int id;
    private final String name;

    public MockRole(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int id() {
        return this.id;
    }

    public String name(){
        return this.name;
    }
}


text:
angular.module('yoda-converter')
    .controller('sentenceController',['$scope', 'sentenceService',
        function ($scope, sentenceService){

            $scope.sentence = {
                input: 'This is super simple',
                output: ''
            };

            $scope.onClick = function(){
                sentenceService.converting($scope.sentence.input)
                    .then(function(data){
                        $scope.sentence.output = data;
                });
            };

        }]
    );


text:
    <input type="text" placeholder="Filter by name" ng-model="nameFilter" />

Fetching users...


text:
mkdir $PREFIX/bin
cp feht $PREFIX/bin/
chmod 755 $PREFIX/bin/feht


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.storage.common.implementation;

import com.azure.core.util.CoreUtils;
import com.azure.storage.common.StorageSharedKeyCredential;
import com.azure.storage.common.sas.AccountSasPermission;
import com.azure.storage.common.sas.AccountSasSignatureValues;
import com.azure.storage.common.sas.SasIpRange;
import com.azure.storage.common.sas.SasProtocol;

import java.time.OffsetDateTime;

import static com.azure.storage.common.implementation.SasImplUtils.formatQueryParameterDate;
import static com.azure.storage.common.implementation.SasImplUtils.tryAppendQueryParameter;

/**
 * This class provides helper methods for common account sas patterns.
 *
 * RESERVED FOR INTERNAL USE.
 */
public class AccountSasImplUtil {

    private String version;

    private SasProtocol protocol;

    private OffsetDateTime startTime;

    private OffsetDateTime expiryTime;

    private String permissions;

    private SasIpRange sasIpRange;

    private String services;

    private String resourceTypes;

    /**
     * Creates a new {@link AccountSasImplUtil} with the specified parameters
     *
     * @param sasValues {@link AccountSasSignatureValues}
     */
    public AccountSasImplUtil(AccountSasSignatureValues sasValues) {
        this.version = sasValues.getVersion();
        this.protocol = sasValues.getProtocol();
        this.startTime = sasValues.getStartTime();
        this.expiryTime = sasValues.getExpiryTime();
        this.permissions = sasValues.getPermissions();
        this.sasIpRange = sasValues.getSasIpRange();
        this.services = sasValues.getServices();
        this.resourceTypes = sasValues.getResourceTypes();
    }

    /**
     * Generates a Sas signed with a {@link StorageSharedKeyCredential}
     *
     * @param storageSharedKeyCredentials {@link StorageSharedKeyCredential}
     * @return A String representing the Sas
     */
    public String generateSas(StorageSharedKeyCredential storageSharedKeyCredentials) {
        StorageImplUtils.assertNotNull("storageSharedKeyCredentials", storageSharedKeyCredentials);
        StorageImplUtils.assertNotNull("services", this.services);
        StorageImplUtils.assertNotNull("resourceTypes", this.resourceTypes);
        StorageImplUtils.assertNotNull("expiryTime", this.expiryTime);
        StorageImplUtils.assertNotNull("permissions", this.permissions);

        if (CoreUtils.isNullOrEmpty(version)) {
            version = Constants.HeaderConstants.TARGET_STORAGE_VERSION;
        }

        // Signature is generated on the un-url-encoded values.
        String signature = storageSharedKeyCredentials.computeHmac256(stringToSign(storageSharedKeyCredentials));

        return encode(signature);
    }

    private String stringToSign(final StorageSharedKeyCredential storageSharedKeyCredentials) {
        return String.join("\n",
            storageSharedKeyCredentials.getAccountName(),
            AccountSasPermission.parse(this.permissions).toString(), // guarantees ordering
            this.services,
            resourceTypes,
            this.startTime == null ? "" : Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.startTime),
            Constants.ISO_8601_UTC_DATE_FORMATTER.format(this.expiryTime),
            this.sasIpRange == null ? "" : this.sasIpRange.toString(),
            this.protocol == null ? "" : this.protocol.toString(),
            this.version,
            "" // Account SAS requires an additional newline character
        );
    }

    private String encode(String signature) {
        /*
         We should be url-encoding each key and each value, but because we know all the keys and values will encode to
         themselves, we cheat except for the signature value.
         */
        StringBuilder sb = new StringBuilder();

        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SERVICE_VERSION, this.version);
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SERVICES, this.services);
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_RESOURCES_TYPES, this.resourceTypes);
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_PROTOCOL, this.protocol);
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_START_TIME, formatQueryParameterDate(this.startTime));
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_EXPIRY_TIME, formatQueryParameterDate(this.expiryTime));
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_IP_RANGE, this.sasIpRange);
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNED_PERMISSIONS, this.permissions);
        tryAppendQueryParameter(sb, Constants.UrlConstants.SAS_SIGNATURE, signature);

        return sb.toString();
    }
}


text:
package org.olat.core.commons.services.webdav;

import java.net.URI;

import org.apache.http.client.methods.HttpRequestBase;

/**
 *
 * Initial date: 11.11.2013<br>
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 *
 */
public class HttpMkcol extends HttpRequestBase {

    public final static String METHOD_NAME = "MKCOL";

    public HttpMkcol() {
        super();
    }

    public HttpMkcol(final URI uri) {
        super();
        setURI(uri);
    }

    /**
     * @throws IllegalArgumentException if the uri is invalid.
     */
    public HttpMkcol(final String uri) {
        super();
        setURI(URI.create(uri));
    }

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }
}


text:
<?php

include_once('BCGParseException.php');
include_once('BCGean13.barcode.php');

class BCGupca extends BCGean13 {
    protected $labelRight = null;

    /**
     * Constructor.
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * Draws the barcode.
     *
     * @param resource $im
     */
    public function draw($im) {
        // The following code is exactly the same as EAN13. We just add a 0 in front of the code !
        $this->text = '0' . $this->text; // We will remove it at the end... don't worry

        parent::draw($im);

        // We remove the 0 in front, as we said :)
        $this->text = substr($this->text, 1);
    }

    /**
     * Draws the extended bars on the image.
     *
     * @param resource $im
     * @param int $plus
     */
    protected function drawExtendedBars($im, $plus) {
        $temp_text = $this->text . $this->keys[$this->checksumValue];
        $rememberX = $this->positionX;
        $rememberH = $this->thickness;

        // We increase the bars
        // First 2 Bars
        $this->thickness = $this->thickness + intval($plus / $this->scale);
        $this->positionX = 0;
        $this->drawSingleBar($im, BCGBarcode::COLOR_FG);
        $this->positionX += 2;
        $this->drawSingleBar($im, BCGBarcode::COLOR_FG);

        // Attemping to increase the 2 following bars
        $this->positionX += 1;
        $code1 = $this->positionX;
        $temp_value = $this->findCode($temp_text[1]);
        $this->drawChar($im, $temp_value, false);

        // Center Guard Bar
        $this->positionX += 36;
        $this->drawSingleBar($im, BCGBarcode::COLOR_FG);
        $this->positionX += 2;
        $this->drawSingleBar($im, BCGBarcode::COLOR_FG);

        // Attemping to increase the 2 last bars
        $this->positionX += 37;
        $temp_value = $this->findCode($temp_text[12]);
        $this->drawChar($im, $temp_value, true);

        // Completly last bars
        $this->drawSingleBar($im, BCGBarcode::COLOR_FG);
        $this->positionX += 2;
        $this->drawSingleBar($im, BCGBarcode::COLOR_FG);

        $this->positionX = $rememberX;
        $this->thickness = $rememberH;
    }

    /**
     * Adds the default label.
     */
    protected function addDefaultLabel() {
        if ($this->isDefaultEanLabelEnabled()) {
            $this->processChecksum();
            $label = $this->getLabel();
            $font = $this->font;

            $this->labelLeft = new BCGLabel(substr($label, 0, 1), $font, BCGLabel::POSITION_LEFT, BCGLabel::ALIGN_BOTTOM);
            $this->labelLeft->setSpacing(4 * $this->scale);

            $this->labelCenter1 = new BCGLabel(substr($label, 1, 5), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT);
            $labelCenter1Dimension = $this->labelCenter1->getDimension();
            $this->labelCenter1->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 6);

            $this->labelCenter2 = new BCGLabel(substr($label, 6, 5), $font, BCGLabel::POSITION_BOTTOM, BCGLabel::ALIGN_LEFT);
            $labelCenter2Dimension = $this->labelCenter2->getDimension();
            $this->labelCenter2->setOffset(($this->scale * 44 - $labelCenter1Dimension[0]) / 2 + $this->scale * 45);

            $this->labelRight = new BCGLabel($this->keys[$this->checksumValue], $font, BCGLabel::POSITION_RIGHT, BCGLabel::ALIGN_BOTTOM);
            $this->labelRight->setSpacing(4 * $this->scale);

            if ($this->alignLabel) {
                $labelDimension = $this->labelCenter1->getDimension();
                $this->labelLeft->setOffset($labelDimension[1]);
                $this->labelRight->setOffset($labelDimension[1]);
            } else {
                $labelDimension = $this->labelLeft->getDimension();
                $this->labelLeft->setOffset($labelDimension[1] / 2);
                $labelDimension = $this->labelLeft->getDimension();
                $this->labelRight->setOffset($labelDimension[1] / 2);
            }

            $this->addLabel($this->labelLeft);
            $this->addLabel($this->labelCenter1);
            $this->addLabel($this->labelCenter2);
            $this->addLabel($this->labelRight);
        }
    }

    /**
     * Check correct length.
     */
    protected function checkCorrectLength() {
        // If we have 12 chars, just flush the last one without throwing anything
        $c = strlen($this->text);
        if ($c === 12) {
            $this->text = substr($this->text, 0, 11);
        } elseif ($c !== 11) {
            throw new BCGParseException('upca', 'Must contain 11 digits, the 12th digit is automatically added.');
        }
    }
}
?>