text:
<?php

namespace PDepend\Report\Overview;

use PDepend\AbstractTest;
use PDepend\Report\DummyAnalyzer;

/**
 * Test case for the overview pyramid logger.
 *
 * @copyright 2008-2015 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 *
 * @covers \PDepend\Report\Overview\Pyramid
 * @group unittest
 */
class PyramidTest extends AbstractTest
{
    /**
     * Tests that the logger returns the expected set of analyzers.
     *
     * @return void
     */
    public function testReturnsExceptedAnalyzers()
    {
        $logger    = new Pyramid();
        $actual    = $logger->getAcceptedAnalyzers();
        $exptected = array(
            'pdepend.analyzer.coupling',
            'pdepend.analyzer.cyclomatic_complexity',
            'pdepend.analyzer.inheritance',
            'pdepend.analyzer.node_count',
            'pdepend.analyzer.node_loc',
        );

        $this->assertEquals($exptected, $actual);
    }

    /**
     * Tests that the logger throws an exception if the log target wasn't
     * configured.
     *
     * @return void
     */
    public function testThrowsExceptionForInvalidLogTarget()
    {
        $this->setExpectedException(
            '\\PDepend\\Report\\NoLogOutputException',
            "The log target is not configured for 'PDepend\\Report\\Overview\\Pyramid'."
        );

        $logger = new Pyramid();
        $logger->close();
    }

    /**
     * Tests that the log method returns <b>false</b> for an invalid logger.
     *
     * @return void
     */
    public function testPyramidDoesntAcceptInvalidAnalyzer()
    {
        $logger = new Pyramid();
        $this->assertFalse($logger->log(new DummyAnalyzer()));
    }

    /**
     * Tests that the logger checks for the required analyzer.
     *
     * @return void
     */
    public function testCloseThrowsAnExceptionIfNoCouplingAnalyzerWasSet()
    {
        $this->setExpectedException(
            '\RuntimeException',
            'Missing Coupling analyzer.'
        );

        $log = new Pyramid();
        $log->setLogFile(self::createRunResourceURI('_tmp_.svg'));
        $log->log($this->createComplexityAnalyzer());
        $log->log($this->createInheritanceAnalyzer());
        $log->log($this->createNodeCountAnalyzer());
        $log->log($this->createNodeLocAnalyzer());
        $log->close();
    }

    /**
     * Tests that the logger checks for the required analyzer.
     *
     * @return void
     */
    public function testCloseThrowsAnExceptionIfNoCyclomaticComplexityAnalyzerWasSet()
    {
        $this->setExpectedException(
            '\RuntimeException',
            'Missing Cyclomatic Complexity analyzer.'
        );

        $log = new Pyramid();
        $log->setLogFile(self::createRunResourceURI('_tmp_.svg'));
        $log->log($this->createCouplingAnalyzer());
        $log->log($this->createInheritanceAnalyzer());
        $log->log($this->createNodeCountAnalyzer());
        $log->log($this->createNodeLocAnalyzer());
        $log->close();
    }

    /**
     * Tests that the logger checks for the required analyzer.
     *
     * @return void
     */
    public function testCloseThrowsAnExceptionIfNoInheritanceAnalyzerWasSet()
    {
        $this->setExpectedException(
            '\RuntimeException',
            'Missing Inheritance analyzer.'
        );

        $log = new Pyramid();
        $log->setLogFile(self::createRunResourceURI('_tmp_.svg'));
        $log->log($this->createCouplingAnalyzer());
        $log->log($this->createComplexityAnalyzer());
        $log->log($this->createNodeCountAnalyzer());
        $log->log($this->createNodeLocAnalyzer());
        $log->close();
    }

    /**
     * Tests that the logger checks for the required analyzer.
     *
     * @return void
     */
    public function testCloseThrowsAnExceptionIfNoNodeCountAnalyzerWasSet()
    {
        $this->setExpectedException(
            '\RuntimeException',
            'Missing Node Count analyzer.'
        );

        $log = new Pyramid();
        $log->setLogFile(self::createRunResourceURI('_tmp_.svg'));
        $log->log($this->createCouplingAnalyzer());
        $log->log($this->createComplexityAnalyzer());
        $log->log($this->createInheritanceAnalyzer());
        $log->log($this->createNodeLocAnalyzer());
        $log->close();
    }

    /**
     * Tests that the logger checks for the required analyzer.
     *
     * @return void
     */
    public function testCloseThrowsAnExceptionIfNoNodeLOCAnalyzerWasSet()
    {
        $this->setExpectedException(
            '\RuntimeException',
            'Missing Node LOC analyzer.'
        );

        $log = new Pyramid();
        $log->setLogFile(self::createRunResourceURI('_tmp_.svg'));
        $log->log($this->createCouplingAnalyzer());
        $log->log($this->createComplexityAnalyzer());
        $log->log($this->createInheritanceAnalyzer());
        $log->log($this->createNodeCountAnalyzer());
        $log->close();
    }

    /**
     * testCollectedAndComputedValuesInOutputSVG
     *
     * @return void
     */
    public function testCollectedAndComputedValuesInOutputSVG()
    {
        $output = self::createRunResourceURI('temp.svg');
        if (file_exists($output)) {
            unlink($output);
        }

        $log = new Pyramid();
        $log->setLogFile($output);
        $log->log($this->createCouplingAnalyzer());
        $log->log($this->createComplexityAnalyzer());
        $log->log($this->createInheritanceAnalyzer());
        $log->log($this->createNodeCountAnalyzer());
        $log->log($this->createNodeLocAnalyzer());
        $log->close();

        $this->assertFileExists($output);

        $expected = array(
            'cyclo'         =>  5579,
            'loc'           =>  35175,
            'nom'           =>  3618,
            'noc'           =>  384,
            'nop'           =>  19,
            'andc'          =>  0.31,
            'ahh'           =>  0.12,
            'calls'         =>  15128,
            'fanout'        =>  8590,
            'cyclo-loc'     =>  0.15,
            'loc-nom'       =>  9.72,
            'nom-noc'       =>  9.42,
            'noc-nop'       =>  20.21,
            'fanout-calls'  =>  0.56,
            'calls-nom'     =>  4.18
        );

        $svg = new \DOMDocument();
        $svg->load($output);

        // TODO: Replace this loop assertion
        foreach ($expected as $name => $value) {
            $elem = $svg->getElementById("pdepend.{$name}");
            $this->assertInstanceOf('\\DOMElement', $elem);
            $this->assertEquals($value, $elem->nodeValue, null, 0.01);
        }

        unlink($output);
    }

    private function createCouplingAnalyzer()
    {
        $mock = $this->getMock('\\PDepend\\Metrics\\Analyzer\\CouplingAnalyzer');
        $mock->expects($this->any())
            ->method('getProjectMetrics')
            ->will($this->returnValue(
                array(
                    'fanout'  =>  8590,
                    'calls'   =>  15128
                )
            ));

        return $mock;
    }

    private function createComplexityAnalyzer()
    {
        $mock = $this->getMock('\\PDepend\\Metrics\\Analyzer\\CyclomaticComplexityAnalyzer');
        $mock->expects($this->any())
            ->method('getProjectMetrics')
            ->will($this->returnValue(
                    array(
                        'ccn2'  =>  5579
                    )
                ));

        return $mock;
    }

    private function createInheritanceAnalyzer()
    {
        $mock = $this->getMock('\\PDepend\\Metrics\\Analyzer\\InheritanceAnalyzer');
        $mock->expects($this->any())
            ->method('getProjectMetrics')
            ->will($this->returnValue(
                    array(
                        'andc'  =>  0.31,
                        'ahh'   =>  0.12
                    )
                ));

        return $mock;
    }

    private function createNodeCountAnalyzer()
    {
        $mock = $this->getMock('\\PDepend\\Metrics\\Analyzer\\NodeCountAnalyzer');
        $mock->expects($this->any())
            ->method('getProjectMetrics')
            ->will($this->returnValue(
                    array(
                        'nop'  =>  19,
                        'noc'  =>  384,
                        'nom'  =>  2018,
                        'nof'  =>  1600
                    )
                ));

        return $mock;
    }

    private function createNodeLocAnalyzer()
    {
        $mock = $this->getMock('\\PDepend\\Metrics\\Analyzer\\NodeLocAnalyzer');
        $mock->expects($this->any())
            ->method('getProjectMetrics')
            ->will($this->returnValue(
                    array(
                        'eloc'  =>  35175
                    )
                ));

        return $mock;
    }
}


text:
package cn.eeemt.entity;

import cn.eeemt.constant.ViewPermission;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.ColumnDefault;
import org.hibernate.annotations.Type;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * author: HuangXiquan

 * date: 2017/10/31/031

 * time: 23:05

 * description: 文章
 */
@Entity
@Table(name = "article")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public class Article {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;
    /**
     * 标题
     */
    private String title;
    /**
     * 文章内容
     */
    @Type(type = "text")
    private String content;
    /**
     * 文章简介
     */
    private String intro;
    /**
     * 标题图
     */
    private String headerPic;
    /**
     * 访问权限
     */
    @Enumerated(EnumType.STRING)
    private ViewPermission viewPermission;
    /**
     * 允许评论
     */
    private Boolean allowComment;
    /**
     * 发布时间
     */
    @ColumnDefault("current_timestamp")
    private LocalDateTime publishTime;
    /**
     * 创建时间
     */
    @Column(updatable = false)
    @ColumnDefault("current_timestamp")
    private LocalDateTime createTime;
    /**
     * 更新时间
     */
    @ColumnDefault("current_timestamp")
    private LocalDateTime updateTime;
    /**
     * 分类
     */
    @ManyToMany(fetch = FetchType.LAZY)
    @Cascade({CascadeType.SAVE_UPDATE})
    @JoinTable(name = "category_article", joinColumns = @JoinColumn(name = "article_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
    private List<Category> category;
    /**
     * 用户
     */
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "USER_ID")
    @Cascade(CascadeType.SAVE_UPDATE)
    private User user;
    /**
     * 标签
     */
    @ManyToMany(fetch = FetchType.LAZY)
    @Cascade({CascadeType.SAVE_UPDATE})
    @JoinTable(name = "tag_article", joinColumns = @JoinColumn(name = "article_id"), inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private List<Tag> tags;

    @OneToMany(mappedBy = "article", fetch = FetchType.LAZY)
    @Cascade(CascadeType.SAVE_UPDATE)
    private List<Comment> comments;
    /**
     * 删除标记
     */
    @ColumnDefault("0")
    private boolean delFlag = false;
    /**
     * 删除日期
     */
    private LocalDateTime delTime;

    /**
     * 统计字数
     *
     * @return 字数
     */
    public int wordCount() {
        return 0;
    }

    /**
     * 投票/赞同/顶 数
     */
    @Column(nullable = false)
    @ColumnDefault("0")
    private int votes;

    /*
     ############################
     ### 操作实体本身属性的方法 ####
     ############################
    */

    /**
     * 投票/赞同/顶
     */
    public void vote() {
        votes++;
    }

    /**
     * 取消投票/踩/反对
     */
    public void unVote() {
        votes--;
    }

    public void countWords() {

    }

    /*
     ##########################
     ### getter and setter ####
     ##########################
    */

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getIntro() {
        return intro;
    }

    public void setIntro(String intro) {
        this.intro = intro;
    }

    public String getHeaderPic() {
        return headerPic;
    }

    public void setHeaderPic(String headerPic) {
        this.headerPic = headerPic;
    }

    public ViewPermission getViewPermission() {
        return viewPermission;
    }

    public void setViewPermission(ViewPermission viewPermission) {
        this.viewPermission = viewPermission;
    }

    public Boolean getAllowComment() {
        return allowComment;
    }

    public void setAllowComment(Boolean allowComment) {
        this.allowComment = allowComment;
    }

    public LocalDateTime getPublishTime() {
        return publishTime;
    }

    public void setPublishTime(LocalDateTime publishTime) {
        this.publishTime = publishTime;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }

    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }

    public List<Category> getCategory() {
        return category;
    }

    public void setCategory(List<Category> category) {
        this.category = category;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    public List<Comment> getComments() {
        return comments;
    }

    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }

    public boolean isDelFlag() {
        return delFlag;
    }

    public void setDelFlag(boolean delFlag) {
        this.delFlag = delFlag;
    }

    public LocalDateTime getDelTime() {
        return delTime;
    }

    public void setDelTime(LocalDateTime delTime) {
        this.delTime = delTime;
    }

    public int getVotes() {
        return votes;
    }

    public void setVotes(int votes) {
        this.votes = votes;
    }
}

redpajama_set_name: RedPajamaGithub


text:
The multiremote examples demonstrate how you can use more than one browser to test a specific thing. This feature is not meant to run tests in parallel, it helps you test interactive features (e.g. a chat system) where you need more than one browser to test.

__Note:__ in order to run these examples you need to have two Chromedriver instances running:

```sh
chromedriver --port=4444
# in an other terminal window
$ chromedriver --port=4445
```

## webrtc.js

Run this test by executing the file using node. It opens up a WebRTC page with two Chrome browser. Both browser will connect to each other and will have a two seconds long call.

```sh
npm run test:webrtc
```

## webdriverio.multiremote.chat.js

This example demonstrates how you could test a chat system. Both browsers will connect to a text based chat. One browser will input something whereas the other browser reads the message, interprets it and returns with a proper response message. You can execute the test using Mocha. Make sure you pass a high timeout as argument to make the test work properly.

```sh
npm run test:chat
```


text:
#ifndef THIRD_PARTY_ML_METADATA_SIMPLE_TYPES_SIMPLE_TYPES_CONSTANTS_H_
#define THIRD_PARTY_ML_METADATA_SIMPLE_TYPES_SIMPLE_TYPES_CONSTANTS_H_

#include <array>

#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"

namespace ml_metadata {

static const int kNumSimpleTypes = 9;

// The in-memory encoding of SimpleTypes proto.
ABSL_CONST_INIT extern const absl::string_view kSimpleTypes;

// A list of simple type names.
ABSL_CONST_INIT extern const std::array<absl::string_view, kNumSimpleTypes>
    kSimpleTypeNames;

}  // namespace ml_metadata

#endif  // THIRD_PARTY_ML_METADATA_SIMPLE_TYPES_SIMPLE_TYPES_CONSTANTS_H_


text:
#ifndef TASKDATA_H
#define TASKDATA_H

#include <string>
#include <memory>
#include <iostream>

class TaskData : public std::enable_shared_from_this<TaskData>
{
public:
    virtual ~TaskData() = 0;

    std::string get_name() const;
    std::size_t get_n() const;

    virtual std::shared_ptr<TaskData> clone() = 0;

    /* clone_copy should return same data because algorithm may rely on it
     **/
    virtual std::shared_ptr<TaskData> clone_copy() const = 0;
/*
    {
        // cout << warning
    }
*/

protected:
    TaskData(const std::string & name, std::size_t);

private:
    const std::string m_name;
    const std::size_t m_n;
};

#endif // TASKDATA_H


text:
'use strict';

import * as assert from 'assert';
import { Logger } from 'node-file-log';
import { ConnectionLike } from './connection';
import { Command, ErrorCode, Response, StackFrame, Variable } from './protocol';

export type ContextId = number;

const contextLog = Logger.create('Context');

export class Context {
    constructor(private connection: ConnectionLike, public readonly id: ContextId, public readonly name: string, public stopped?: boolean) {}

    public isStopped(): boolean {
        return this.stopped ? this.stopped : false;
    }

    public pause(): Promise<void> {
        contextLog.debug(`request 'pause' for context ${this.id}`);

        const req = new Command('pause', this.id);
        return this.connection.sendRequest(req, (res: Response) => {

            return new Promise<void>((resolve, reject) => {
                if (res.type === 'error') {
                    if (res.content.code === ErrorCode.IS_PAUSED) {
                        contextLog.warn(`context ${this.id} is already paused`);
                        resolve();
                        return;
                    }

                    reject(new Error(res.content.message));
                    return;
                }

                resolve();
            });
        });
    }

    public continue(): Promise<void> {
        // contextLog.debug(`request 'continue' for context ${this.id}`);

        const cmd = new Command('continue', this.id);
        return this.connection.sendRequest(cmd);
    }

    public getStacktrace(): Promise<StackFrame[]> {
        // contextLog.debug(`request 'get_stacktrace' for context ${this.id}`);

        const req = new Command('get_stacktrace', this.id);
        return this.connection.sendRequest(req, (res: Response) => {
            return new Promise<StackFrame[]>((resolve, reject) => {
                if (res.type === 'error') {
                    reject(new Error(res.content.message));
                } else {
                    const stacktrace: StackFrame[] = [];
                    assert.ok(res.content.stacktrace);
                    resolve(res.content.stacktrace);
                }
            });
        });
    }

    /**
     * Returns all variables in the top-most frame of this context.
     */
    public getVariables(): Promise<Variable[]> {
        // contextLog.debug(`request 'get_variables' for context ${this.id}`);

        const req = Command.getVariables(this.id, {
            depth: 0,
            options: {
                "evaluation-depth": 1,
                "show-hierarchy": true,
            },
        });
        return this.connection.sendRequest(req, (res: Response) => {
            return new Promise<Variable[]>((resolve, reject) => {
                if (res.type === 'error') {
                    reject(new Error(res.content.message));
                } else {

                    const variables: Variable[] = [];

                    // This should be named 'frames' because it really holds all frames and for each frame
                    // an array of variables
                    assert.equal(res.content.variables.length, 1);

                    res.content.variables.forEach((element: any) => {

                        // Each element got a stackElement which describes the frame and a list of
                        // variables.

                        element.variables.forEach((variable: any) => {
                            variables.push(variable);
                        });
                    });

                    resolve(variables);
                }
            });
        });
    }

    public next(): Promise<void> {
        // contextLog.debug(`request 'next' for context ${this.id}`);
        return this.connection.sendRequest(new Command('next', this.id));
    }

    public stepIn(): Promise<void> {
        // contextLog.debug(`request 'stepIn' for context ${this.id}`);
        return this.connection.sendRequest(new Command('step', this.id));
    }

    public stepOut(): Promise<void> {
        // contextLog.debug(`request 'stepOut' for context ${this.id}`);
        return this.connection.sendRequest(new Command('step_out', this.id));
    }

    /**
     * Evaluate arbitrary JS inside the current frame.
     *
     * Example:
     *      const expr = "(function(){return JSON.stringify({answer: 42});})();";
     *      const result = await context.evaluate2(expr);
     *
     * @param expression A JS expression
     * @returns The result of the expression as string
     */
    public evaluate2(expression: string): Promise<string> {

        const req = Command.evaluate(this.id, {
            path: expression,
            options: {
                "show-hierarchy": true,
                "evaluation-depth": 1,
            },
        });

        return this.connection.sendRequest(req, (res: Response) => {
            return new Promise<Variable>((resolve, reject) => {
                if (res.type === 'error') {
                    return reject(new Error(res.content.message));
                } else {
                    assert.equal(res.subtype, 'evaluated');
                    resolve(res.content.result);
                }
            });
        });
    }

    // FIXME: this implementation is only for evaluating variables and variable values? This shouldn't be here. Should be around variableMap.ts
    public evaluate(expression: string): Promise<Variable> {
        // contextLog.debug(`request 'evaluate' for context ${this.id}`);

        // For now this solution is okay, in future it would be better if the debugger is smart enough to decide how the
        // value of the "thing" to evaluate should be represented.
        const evaluateReplaceFunction = (key: any, value: any) => {
            if (typeof value === "function") {
                return "function " + value.toString().match(/(\([^\)]*\))/)[1] + "{ ... }";
            } else {
                return value;
            }
        };

        const req = Command.evaluate(this.id, {
            path: `JSON.stringify(${expression}, ${evaluateReplaceFunction.toString()})`,
            options: {
                "show-hierarchy": true,
                "evaluation-depth": 1,
            },
        });

        return this.connection.sendRequest(req, (res: Response) => {
            return new Promise<Variable>((resolve, reject) => {
                if (res.type === 'error') {
                    reject(new Error(res.content.message));
                } else {
                    assert.equal(res.subtype, 'evaluated');
                    let variableType: string;

                    if (res.content.result.startsWith("function")) {
                        variableType = "function";
                    } else {
                        const _variable = JSON.parse(res.content.result);
                        variableType = (Array.isArray(_variable)) ? "array" : typeof _variable;
                    }

                    const variable: Variable = {
                        name: "",
                        value: res.content.result,
                        type: variableType,
                    };
                    resolve(variable);
                }
            });
        });
    }

    public setVariable(variableName: string, variableValue: string): Promise<void> {
        if (typeof variableValue === "string") {
            variableValue = `"${variableValue}"`;
        }

        const cmd = Command.evaluate(this.id, {
            path: `${variableName}=${variableValue}`,
            options: {
                "show-hierarchy": false,
                "evaluation-depth": 0,
            },
        });

        return this.connection.sendRequest(cmd);
    }

    public handleResponse(response: Response): Promise<void> {
        // contextLog.debug(`handleResponse ${JSON.stringify(response)} for context ${this.id}`);
        if (response.type === "info" && response.subtype && response.subtype === "paused") {
            contextLog.debug(`${this.id} -> paused`);
            this.stopped = true;
        }
        return Promise.resolve();
    }
}

const coordinatorLog = Logger.create('ContextCoordinator');

/**
 * Coordinates requests and responses for all available contexts.
 *
 * Responsibilities:
 * - Keep track of all available contexts of the target.
 * - Dispatch incoming responses to their corresponding context.
 */
export class ContextCoordinator {
    private contextById: Map<ContextId, Context> = new Map();

    constructor(private connection: ConnectionLike) { }

    public async getAllAvailableContexts(): Promise<Context[]> {
        // coordinatorLog.debug(`getAllAvailableContexts`);

        // After connecting the remote debugger, it responses with a context list
        // that doesn't contain an id. But when we send the 'get_available_contexts'
        // request, the response contains an id. Anyway, for now we do not check the
        // id but simply take the next response that contains a context list. But this
        // is very likely a correct answer.
        // TODO: insert id check
        await this.connection.sendRequest(new Command('get_available_contexts'), (res) => this.handleResponse(res));
        const contexts = Array.from(this.contextById.values());
        const contextNames = contexts.map(context => context.stopped ? ` '${context.name}' (${context.id}) paused` : ` '${context.name}' (${context.id})`);
        coordinatorLog.debug(`contexts on server:${contextNames}`);
        return contexts;
    }

    public getContext(id: ContextId): Context {
        const context = this.contextById.get(id);
        if (context === undefined) {
            const contents = Array.from(this.contextById.values());
            const contextIds = contents.map(someContext => someContext.id);
            coordinatorLog.warn(`unknown context ${id} requested, available: ${JSON.stringify(contextIds)}`);
            throw new Error(`No such context ${id}`);
        }
        return context;
    }

    public handleResponse(response: Response): Promise<void> {
        // coordinatorLog.debug(`handleResponse`);

        return new Promise<void>((resolve, reject) => {

            if (response.contextId === undefined) {

                // Not meant for a particular context

                if (response.type === 'info' && response.subtype === 'contexts_list') {
                    // coordinatorLog.debug('updating list of available contexts');

                    if (!response.content.hasOwnProperty('id')) {
                        // no id and subtype 'contexts_list' so this means, that this is the
                        // first response that we get after we connected the remote debugger
                        // simply log an information message
                        coordinatorLog.info(`connected to remote debugger`);
                    }

                    assert.ok(response.content.hasOwnProperty('contexts'));

                    // Add new contexts
                    response.content.contexts.forEach((element: any) => {
                        const context = this.contextById.get(element.contextId);
                        if (context === undefined) {
                            // coordinatorLog.debug(`creating new context with id: ${element.contextId}`);
                            const newContext: Context = new Context(this.connection, element.contextId, element.contextName, element.paused);
                            this.contextById.set(element.contextId, newContext);

                            // Notify the frontend that we have a new context in the target
                            this.connection.emit('newContext', newContext.id, newContext.name, newContext.isStopped());
                        } else {
                            context.stopped = element.paused;
                        }
                    });

                    // Delete the contexts that no longer exist
                    const dead: ContextId[] = [];
                    this.contextById.forEach(context => {
                        if (!response.content.contexts.find((element: any) => element.contextId === context.id)) {
                            coordinatorLog.debug(`context ${context.id} no longer exists`);
                            dead.push(context.id);
                        }
                    });
                    dead.forEach(id => this.contextById.delete(id));
                }
            } else {

                // Dispatch to the corresponding context

                const context: Context | undefined = this.contextById.get(response.contextId);
                if (context === undefined) {
                    reject(new Error(`response for unknown context`));
                    return;
                }
                context.handleResponse(response);
            }

            resolve();
        });
    }
}


text:
var nop = function() {};

// Function params
/**
 * @param {number} n
 */
var oneParam = function(n) {};

/**
 * @param {boolean} b
 * @param {string} s
 */
function twoParams(b, s) {}

/** @param {!Array<?>=} list */
function withDefaultValue(list = []) {}

/**
 * @param {boolean=} a
 */
function undefinedDefault(a = undefined) {}

/** @param {!Array<?>=} list */
function undefinedDefaultArray(list = undefined) {}

// Function returns
/**
 * @return {*}
 */
var anyReturn = function() { return "hello"; };

/**
 * @return {number}
 */
function typedReturn() { return 4; }

/**
 * @param {number} n
 * @param {boolean} b
 */
var partiallyTyped = function(n, u1, b, u2) {};

// Both params and returns
/**
 * @param {boolean} b
 * @param {string} s
 * @param {?} x
 * @return {?string}
 */
var complex = function(b, s, x) { if (b) { return s; } return null;};

// Undefined params

/**
 * @param {undefined} u
 * @param {void} v
 */
var paramUndef = function(u, v) {};

// Void returns

/**
 * @return {void}
 */
var retVoid = function() {};

/**
 * @return {undefined}
 */
var retUndef = function() {};

/**
 * @param {number} a
 * @return {number}
 */
const arrowWithJsDoc = a => { return a; };

/**
 * @param {number} a
 * @return {number}
 */
const arrowWithJsDocAndParens = (a) => { return a; };

/**
 * @param {number} a
 * @param {number} b
 * @return {number}
 */
const arrowWithJsDocMultiArg = (a, b) => { return a; };

const arrowNoJsDoc = a => { return a; };

const implicitReturnArrow = a => a;


text:
require 'active_model/validations'

module ActiveModel
  module Validations

    module HelperMethods
      def validate_state_history_entry(options = {})
        start_attr = options[:start] || :start
        validates start_attr, :presence => true

        validates_with StateHistoryEntryValidator, options
      end

      def validate_state_history(association, options = {})
        params = { :association => association }
        params.merge!(options)
        validates_with StateHistoryValidator, params
      end
    end

  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<feature
      id="com.sap.mobile.platform.server.sample.customization.dispatcher.servlet.feature"
      version="130.8.0.qualifier"
      label="SAP Mobile Platform :: Server Samples :: Dispatcher Servlet Sample Feature"
      provider-name="SAP AG">

  <copyright>
	(c) 2013 SAP AG or an SAP affiliate company.  All rights reserved.

	No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG.  The information contained herein may be changed without prior notice.
  </copyright>

  <plugin id="com.sap.mobile.platform.server.sample.customization.dispatcher.sampleservlet" download-size="0" install-size="0" version="0.0.0" unpack="false"/>

</feature>


text:
using AutoMapper;
using Atomiv.Web.AspNetCore.RestApi.IntegrationTest.Fake.Dtos.Customers;
using Atomiv.Web.AspNetCore.RestApi.IntegrationTest.Fake.Entities;

namespace Atomiv.Web.AspNetCore.RestApi.IntegrationTest.Fake.Profiles.Customers
{
    public class CustomerPostResponseProfile : Profile
    {
        public CustomerPostResponseProfile()
        {
            CreateMap<Customer, CustomerPostResponse>();
        }
    }
}


text:
package io.quarkus.gradle.tooling;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;

import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.artifacts.ResolvedConfiguration;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.FileTree;
import org.gradle.api.initialization.IncludedBuild;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.compile.AbstractCompile;
import org.gradle.language.jvm.tasks.ProcessResources;
import org.gradle.tooling.provider.model.ParameterizedToolingModelBuilder;
import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile;

import io.quarkus.bootstrap.BootstrapConstants;
import io.quarkus.bootstrap.model.ApplicationModel;
import io.quarkus.bootstrap.model.ApplicationModelBuilder;
import io.quarkus.bootstrap.model.CapabilityContract;
import io.quarkus.bootstrap.model.PlatformImports;
import io.quarkus.bootstrap.model.gradle.ModelParameter;
import io.quarkus.bootstrap.model.gradle.impl.ModelParameterImpl;
import io.quarkus.bootstrap.workspace.ArtifactSources;
import io.quarkus.bootstrap.workspace.DefaultArtifactSources;
import io.quarkus.bootstrap.workspace.DefaultSourceDir;
import io.quarkus.bootstrap.workspace.DefaultWorkspaceModule;
import io.quarkus.bootstrap.workspace.SourceDir;
import io.quarkus.bootstrap.workspace.WorkspaceModule;
import io.quarkus.fs.util.ZipUtils;
import io.quarkus.gradle.dependency.ApplicationDeploymentClasspathBuilder;
import io.quarkus.maven.dependency.ArtifactCoords;
import io.quarkus.maven.dependency.ArtifactDependency;
import io.quarkus.maven.dependency.ArtifactKey;
import io.quarkus.maven.dependency.DependencyFlags;
import io.quarkus.maven.dependency.GACT;
import io.quarkus.maven.dependency.GACTV;
import io.quarkus.maven.dependency.GAV;
import io.quarkus.maven.dependency.ResolvedDependency;
import io.quarkus.maven.dependency.ResolvedDependencyBuilder;
import io.quarkus.paths.PathCollection;
import io.quarkus.paths.PathList;
import io.quarkus.runtime.LaunchMode;
import io.quarkus.runtime.util.HashUtil;

public class GradleApplicationModelBuilder implements ParameterizedToolingModelBuilder<ModelParameter> {

    private static final String MAIN_RESOURCES_OUTPUT = "build/resources/main";
    private static final String CLASSES_OUTPUT = "build/classes";

    /* @formatter:off */
    private static final byte COLLECT_TOP_EXTENSION_RUNTIME_NODES = 0b001;
    private static final byte COLLECT_DIRECT_DEPS =                 0b010;
    private static final byte COLLECT_RELOADABLE_MODULES =          0b100;
    /* @formatter:on */

    @Override
    public boolean canBuild(String modelName) {
        return modelName.equals(ApplicationModel.class.getName());
    }

    @Override
    public Class<ModelParameter> getParameterType() {
        return ModelParameter.class;
    }

    @Override
    public Object buildAll(String modelName, Project project) {
        final ModelParameterImpl modelParameter = new ModelParameterImpl();
        modelParameter.setMode(LaunchMode.DEVELOPMENT.toString());
        return buildAll(modelName, modelParameter, project);
    }

    @Override
    public Object buildAll(String modelName, ModelParameter parameter, Project project) {
        final LaunchMode mode = LaunchMode.valueOf(parameter.getMode());

        final ApplicationDeploymentClasspathBuilder classpathBuilder = new ApplicationDeploymentClasspathBuilder(project, mode);
        final Configuration classpathConfig = classpathBuilder.getRuntimeConfiguration();
        final Configuration deploymentConfig = classpathBuilder.getDeploymentConfiguration();
        final PlatformImports platformImports = classpathBuilder.getPlatformImports();

        boolean workspaceDiscovery = LaunchMode.DEVELOPMENT.equals(mode) || LaunchMode.TEST.equals(mode)
                || Boolean.parseBoolean(System.getProperty(BootstrapConstants.QUARKUS_BOOTSTRAP_WORKSPACE_DISCOVERY));
        if (!workspaceDiscovery) {
            Object o = project.getProperties().get(BootstrapConstants.QUARKUS_BOOTSTRAP_WORKSPACE_DISCOVERY);
            if (o != null) {
                workspaceDiscovery = Boolean.parseBoolean(o.toString());
            }
        }

        final ResolvedDependency appArtifact = getProjectArtifact(project, workspaceDiscovery);
        final ApplicationModelBuilder modelBuilder = new ApplicationModelBuilder()
                .setAppArtifact(appArtifact)
                .addReloadableWorkspaceModule(appArtifact.getKey())
                .setPlatformImports(platformImports);

        collectDependencies(classpathConfig.getResolvedConfiguration(), workspaceDiscovery,
                project, modelBuilder, appArtifact.getWorkspaceModule().mutable());
        collectExtensionDependencies(project, deploymentConfig, modelBuilder);

        return modelBuilder.build();
    }

    public static ResolvedDependency getProjectArtifact(Project project, boolean workspaceDiscovery) {
        final ResolvedDependencyBuilder appArtifact = ResolvedDependencyBuilder.newInstance()
                .setGroupId(project.getGroup().toString())
                .setArtifactId(project.getName())
                .setVersion(project.getVersion().toString());

        SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
        final WorkspaceModule.Mutable mainModule = WorkspaceModule.builder()
                .setModuleId(new GAV(appArtifact.getGroupId(), appArtifact.getArtifactId(), appArtifact.getVersion()))
                .setModuleDir(project.getProjectDir().toPath())
                .setBuildDir(project.getBuildDir().toPath())
                .setBuildFile(project.getBuildFile().toPath());

        initProjectModule(project, mainModule, sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME),
                SourceSet.MAIN_SOURCE_SET_NAME, ArtifactSources.MAIN);
        if (workspaceDiscovery) {
            initProjectModule(project, mainModule, sourceSets.getByName(SourceSet.TEST_SOURCE_SET_NAME),
                    SourceSet.TEST_SOURCE_SET_NAME, ArtifactSources.TEST);
        }

        final PathList.Builder paths = PathList.builder();
        collectDestinationDirs(mainModule.getMainSources().getSourceDirs(), paths);
        collectDestinationDirs(mainModule.getMainSources().getResourceDirs(), paths);

        return appArtifact.setWorkspaceModule(mainModule).setResolvedPaths(paths.build()).build();
    }

    private static void collectDestinationDirs(Collection<SourceDir> sources, final PathList.Builder paths) {
        for (SourceDir src : sources) {
            if (!Files.exists(src.getOutputDir())) {
                continue;
            }

            final Path path = src.getOutputDir();
            if (paths.contains(path)) {
                continue;
            }
            paths.add(path);
        }
    }

    private void collectExtensionDependencies(Project project, Configuration deploymentConfiguration,
            ApplicationModelBuilder modelBuilder) {
        final ResolvedConfiguration rc = deploymentConfiguration.getResolvedConfiguration();
        for (ResolvedArtifact a : rc.getResolvedArtifacts()) {
            if (a.getId().getComponentIdentifier() instanceof ProjectComponentIdentifier) {
                ProjectComponentIdentifier projectComponentIdentifier = (ProjectComponentIdentifier) a.getId()
                        .getComponentIdentifier();
                final Project projectDep = project.getRootProject().findProject(projectComponentIdentifier.getProjectPath());
                Objects.requireNonNull(projectDep, "project " + projectComponentIdentifier.getProjectPath() + " should exist");
                SourceSetContainer sourceSets = projectDep.getExtensions().getByType(SourceSetContainer.class);

                SourceSet mainSourceSet = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME);
                ResolvedDependencyBuilder dep = modelBuilder.getDependency(
                        toAppDependenciesKey(a.getModuleVersion().getId().getGroup(), a.getName(), a.getClassifier()));
                if (dep == null) {
                    dep = toDependency(a, mainSourceSet);
                    modelBuilder.addDependency(dep);
                }
                dep.setDeploymentCp();
                dep.clearFlag(DependencyFlags.RELOADABLE);
            } else if (isDependency(a)) {
                ResolvedDependencyBuilder dep = modelBuilder.getDependency(
                        toAppDependenciesKey(a.getModuleVersion().getId().getGroup(), a.getName(), a.getClassifier()));
                if (dep == null) {
                    dep = toDependency(a);
                    modelBuilder.addDependency(dep);
                }
                dep.setDeploymentCp();
                dep.clearFlag(DependencyFlags.RELOADABLE);
            }
        }
    }

    private void collectDependencies(ResolvedConfiguration configuration,
            boolean workspaceDiscovery, Project project, ApplicationModelBuilder modelBuilder,
            WorkspaceModule.Mutable wsModule) {

        final Set<ResolvedArtifact> resolvedArtifacts = configuration.getResolvedArtifacts();
        // if the number of artifacts is less than the number of files then probably
        // the project includes direct file dependencies
        final Set<File> artifactFiles = resolvedArtifacts.size() < configuration.getFiles().size()
                ? new HashSet<>(resolvedArtifacts.size())
                : null;

        configuration.getFirstLevelModuleDependencies()
                .forEach(d -> {
                    collectDependencies(d, workspaceDiscovery, project, artifactFiles, new HashSet<>(),
                            modelBuilder,
                            wsModule,
                            (byte) (COLLECT_TOP_EXTENSION_RUNTIME_NODES | COLLECT_DIRECT_DEPS | COLLECT_RELOADABLE_MODULES));
                });

        if (artifactFiles != null) {
            // detect FS paths that aren't provided by the resolved artifacts
            for (File f : configuration.getFiles()) {
                if (artifactFiles.contains(f) || !f.exists()) {
                    continue;
                }
                // here we are trying to represent a direct FS path dependency
                // as an artifact dependency
                // SHA1 hash is used to avoid long file names in the lib dir
                final String parentPath = f.getParent();
                final String group = HashUtil.sha1(parentPath == null ? f.getName() : parentPath);
                String name = f.getName();
                String type = ArtifactCoords.TYPE_JAR;
                if (!f.isDirectory()) {
                    final int dot = f.getName().lastIndexOf('.');
                    if (dot > 0) {
                        name = f.getName().substring(0, dot);
                        type = f.getName().substring(dot + 1);
                    }
                }
                // hash could be a better way to represent the version
                final String version = String.valueOf(f.lastModified());
                final ResolvedDependencyBuilder artifactBuilder = ResolvedDependencyBuilder.newInstance()
                        .setGroupId(group)
                        .setArtifactId(name)
                        .setType(type)
                        .setVersion(version)
                        .setResolvedPath(f.toPath())
                        .setDirect(true)
                        .setRuntimeCp();
                processQuarkusDependency(artifactBuilder, modelBuilder);
                modelBuilder.addDependency(artifactBuilder);
            }
        }
    }

    private void collectDependencies(org.gradle.api.artifacts.ResolvedDependency resolvedDep, boolean workspaceDiscovery,
            Project project, Set<File> artifactFiles, Set<ArtifactKey> processedModules, ApplicationModelBuilder modelBuilder,
            WorkspaceModule.Mutable parentModule,
            byte flags) {
        WorkspaceModule.Mutable projectModule = null;
        for (ResolvedArtifact a : resolvedDep.getModuleArtifacts()) {
            final ArtifactKey artifactKey = toAppDependenciesKey(a.getModuleVersion().getId().getGroup(), a.getName(),
                    a.getClassifier());
            if (!isDependency(a) || modelBuilder.getDependency(artifactKey) != null) {
                continue;
            }
            final ArtifactCoords depCoords = toArtifactCoords(a);
            final ResolvedDependencyBuilder depBuilder = ResolvedDependencyBuilder.newInstance()
                    .setCoords(depCoords)
                    .setRuntimeCp();
            if (isFlagOn(flags, COLLECT_DIRECT_DEPS)) {
                depBuilder.setDirect(true);
                flags = clearFlag(flags, COLLECT_DIRECT_DEPS);
            }
            if (parentModule != null) {
                parentModule.addDependency(new ArtifactDependency(depCoords));
            }

            PathCollection paths = null;
            if (workspaceDiscovery && a.getId().getComponentIdentifier() instanceof ProjectComponentIdentifier) {

                final Project projectDep = project.getRootProject().findProject(
                        ((ProjectComponentIdentifier) a.getId().getComponentIdentifier()).getProjectPath());
                SourceSetContainer sourceSets = projectDep == null ? null
                        : projectDep.getExtensions().findByType(SourceSetContainer.class);

                final String classifier = a.getClassifier();
                if (classifier == null || classifier.isEmpty()) {
                    final IncludedBuild includedBuild = ToolingUtils.includedBuild(project.getRootProject(), a.getName());
                    if (includedBuild != null) {
                        final PathList.Builder pathBuilder = PathList.builder();
                        addSubstitutedProject(pathBuilder, includedBuild.getProjectDir());
                        paths = pathBuilder.build();
                    } else if (sourceSets != null) {
                        final PathList.Builder pathBuilder = PathList.builder();
                        projectModule = initProjectModuleAndBuildPaths(projectDep, a, modelBuilder, depBuilder,
                                pathBuilder, SourceSet.MAIN_SOURCE_SET_NAME, false);
                        paths = pathBuilder.build();
                    }
                } else if (sourceSets != null) {
                    if ("test".equals(classifier)) {
                        final PathList.Builder pathBuilder = PathList.builder();
                        projectModule = initProjectModuleAndBuildPaths(projectDep, a, modelBuilder, depBuilder,
                                pathBuilder, SourceSet.TEST_SOURCE_SET_NAME, true);
                        paths = pathBuilder.build();
                    } else if ("test-fixtures".equals(classifier)) {
                        final PathList.Builder pathBuilder = PathList.builder();
                        projectModule = initProjectModuleAndBuildPaths(projectDep, a, modelBuilder, depBuilder,
                                pathBuilder, "testFixtures", true);
                        paths = pathBuilder.build();
                    }
                }
            }

            depBuilder.setResolvedPaths(paths == null ? PathList.of(a.getFile().toPath()) : paths)
                    .setWorkspaceModule(projectModule);
            if (processQuarkusDependency(depBuilder, modelBuilder)) {
                if (isFlagOn(flags, COLLECT_TOP_EXTENSION_RUNTIME_NODES)) {
                    depBuilder.setFlags(DependencyFlags.TOP_LEVEL_RUNTIME_EXTENSION_ARTIFACT);
                    flags = clearFlag(flags, COLLECT_TOP_EXTENSION_RUNTIME_NODES);
                }
                flags = clearFlag(flags, COLLECT_RELOADABLE_MODULES);
            }
            if (!isFlagOn(flags, COLLECT_RELOADABLE_MODULES)) {
                depBuilder.clearFlag(DependencyFlags.RELOADABLE);
            }
            modelBuilder.addDependency(depBuilder);

            if (artifactFiles != null) {
                artifactFiles.add(a.getFile());
            }
        }

        processedModules.add(new GACT(resolvedDep.getModuleGroup(), resolvedDep.getModuleName()));
        for (org.gradle.api.artifacts.ResolvedDependency child : resolvedDep.getChildren()) {
            if (!processedModules.contains(new GACT(child.getModuleGroup(), child.getModuleName()))) {
                collectDependencies(child, workspaceDiscovery, project, artifactFiles, processedModules,
                        modelBuilder, projectModule, flags);
            }
        }
    }

    private static String toNonNullClassifier(String resolvedClassifier) {
        return resolvedClassifier == null ? "" : resolvedClassifier;
    }

    private WorkspaceModule.Mutable initProjectModuleAndBuildPaths(final Project project,
            ResolvedArtifact resolvedArtifact, ApplicationModelBuilder appModel, final ResolvedDependencyBuilder appDep,
            PathList.Builder buildPaths, String sourceName, boolean test) {

        appDep.setWorkspaceModule().setReloadable();

        final WorkspaceModule.Mutable projectModule = appModel.getOrCreateProjectModule(
                new GAV(resolvedArtifact.getModuleVersion().getId().getGroup(), resolvedArtifact.getName(),
                        resolvedArtifact.getModuleVersion().getId().getVersion()),
                project.getProjectDir(),
                project.getBuildDir())
                .setBuildFile(project.getBuildFile().toPath());

        final String classifier = toNonNullClassifier(resolvedArtifact.getClassifier());
        SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
        initProjectModule(project, projectModule, sourceSets.findByName(sourceName), sourceName, classifier);

        collectDestinationDirs(projectModule.getSources(classifier).getSourceDirs(), buildPaths);
        collectDestinationDirs(projectModule.getSources(classifier).getResourceDirs(), buildPaths);

        appModel.addReloadableWorkspaceModule(
                new GACT(resolvedArtifact.getModuleVersion().getId().getGroup(), resolvedArtifact.getName(), classifier,
                        ArtifactCoords.TYPE_JAR));
        return projectModule;
    }

    private boolean processQuarkusDependency(ResolvedDependencyBuilder artifactBuilder, ApplicationModelBuilder modelBuilder) {
        for (Path artifactPath : artifactBuilder.getResolvedPaths()) {
            if (!Files.exists(artifactPath) || !artifactBuilder.getType().equals(ArtifactCoords.TYPE_JAR)) {
                break;
            }
            if (Files.isDirectory(artifactPath)) {
                return processQuarkusDir(artifactBuilder, artifactPath.resolve(BootstrapConstants.META_INF), modelBuilder);
            } else {
                try (FileSystem artifactFs = ZipUtils.newFileSystem(artifactPath)) {
                    return processQuarkusDir(artifactBuilder, artifactFs.getPath(BootstrapConstants.META_INF), modelBuilder);
                } catch (IOException e) {
                    throw new RuntimeException("Failed to process " + artifactPath, e);
                }
            }
        }
        return false;
    }

    private static boolean processQuarkusDir(ResolvedDependencyBuilder artifactBuilder, Path quarkusDir,
            ApplicationModelBuilder modelBuilder) {
        if (!Files.exists(quarkusDir)) {
            return false;
        }
        final Path quarkusDescr = quarkusDir.resolve(BootstrapConstants.DESCRIPTOR_FILE_NAME);
        if (!Files.exists(quarkusDescr)) {
            return false;
        }
        final Properties extProps = readDescriptor(quarkusDescr);
        if (extProps == null) {
            return false;
        }
        artifactBuilder.setRuntimeExtensionArtifact();
        final String extensionCoords = artifactBuilder.toGACTVString();
        modelBuilder.handleExtensionProperties(extProps, extensionCoords);

        final String providesCapabilities = extProps.getProperty(BootstrapConstants.PROP_PROVIDES_CAPABILITIES);
        if (providesCapabilities != null) {
            modelBuilder
                    .addExtensionCapabilities(CapabilityContract.of(extensionCoords, providesCapabilities, null));
        }
        return true;
    }

    private static Properties readDescriptor(final Path path) {
        final Properties rtProps;
        if (!Files.exists(path)) {
            // not a platform artifact
            return null;
        }
        rtProps = new Properties();
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            rtProps.load(reader);
        } catch (IOException e) {
            throw new UncheckedIOException("Failed to load extension description " + path, e);
        }
        return rtProps;
    }

    private static void initProjectModule(Project project, WorkspaceModule.Mutable module, SourceSet sourceSet,
            String sourceName, String classifier) {

        if (sourceSet == null) {
            return;
        }

        final FileCollection allClassesDirs = sourceSet.getOutput().getClassesDirs();
        // some plugins do not add source directories to source sets and they may be missing from sourceSet.getAllJava()
        // see https://github.com/quarkusio/quarkus/issues/20755

        final List<SourceDir> sourceDirs = new ArrayList<>(1);
        final List<SourceDir> resourceDirs = new ArrayList<>(1);

        project.getTasks().withType(AbstractCompile.class, t -> {
            if (!t.getEnabled()) {
                return;
            }
            final FileTree source = t.getSource();
            if (source.isEmpty()) {
                return;
            }
            final File destDir = t.getDestinationDirectory().getAsFile().get();
            if (!allClassesDirs.contains(destDir)) {
                return;
            }
            source.visit(a -> {
                // we are looking for the root dirs containing sources
                if (a.getRelativePath().getSegments().length == 1) {
                    final File srcDir = a.getFile().getParentFile();
                    DefaultSourceDir sources = new DefaultSourceDir(srcDir.toPath(), destDir.toPath(),
                            Collections.singletonMap("compiler", t.getName()));
                    sourceDirs.add(sources);
                }
            });
        });

        // This "try/catch" is needed because of the way the "quarkus-cli" Gradle tests work. Without it, the tests fail.
        try {
            Class.forName("org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile");
            project.getTasks().withType(KotlinJvmCompile.class, t -> {
                if (!t.getEnabled()) {
                    return;
                }
                final FileTree source = t.getSources().getAsFileTree();
                if (source.isEmpty()) {
                    return;
                }
                final File destDir = t.getDestinationDirectory().getAsFile().get();
                if (!allClassesDirs.contains(destDir)) {
                    return;
                }
                source.visit(a -> {
                    // we are looking for the root dirs containing sources
                    if (a.getRelativePath().getSegments().length == 1) {
                        final File srcDir = a.getFile().getParentFile();
                        DefaultSourceDir sources = new DefaultSourceDir(srcDir.toPath(), destDir.toPath(),
                                Collections.singletonMap("compiler", t.getName()));
                        sourceDirs.add(sources);
                    }
                });
            });
        } catch (ClassNotFoundException e) {
            // ignore
        }

        final File resourcesOutputDir = sourceSet.getOutput().getResourcesDir();

        project.getTasks().withType(ProcessResources.class, t -> {
            if (!t.getEnabled()) {
                return;
            }
            final FileCollection source = t.getSource();
            if (source.isEmpty()) {
                return;
            }
            if (!t.getDestinationDir().equals(resourcesOutputDir)) {
                return;
            }
            final Path destDir = t.getDestinationDir().toPath();
            source.getAsFileTree().visit(a -> {
                // we are looking for the root dirs containing sources
                if (a.getRelativePath().getSegments().length == 1) {
                    final File srcDir = a.getFile().getParentFile();
                    resourceDirs.add(new DefaultSourceDir(srcDir.toPath(), destDir));
                }
            });
        });
        // there could be a task generating resources
        if (resourcesOutputDir.exists() && resourceDirs.isEmpty()) {
            sourceSet.getResources().getSrcDirs()
                    .forEach(srcDir -> resourceDirs.add(new DefaultSourceDir(srcDir.toPath(), resourcesOutputDir.toPath())));
        }
        module.addArtifactSources(new DefaultArtifactSources(classifier, sourceDirs, resourceDirs));
    }

    private void addSubstitutedProject(PathList.Builder paths, File projectFile) {
        File mainResourceDirectory = new File(projectFile, MAIN_RESOURCES_OUTPUT);
        if (mainResourceDirectory.exists()) {
            paths.add(mainResourceDirectory.toPath());
        }
        File classesOutput = new File(projectFile, CLASSES_OUTPUT);
        File[] languageDirectories = classesOutput.listFiles();
        if (languageDirectories == null) {
            throw new GradleException(
                    "The project does not contain a class output directory. " + classesOutput.getPath() + " must exist.");
        }
        for (File languageDirectory : languageDirectories) {
            if (languageDirectory.isDirectory()) {
                for (File sourceSet : languageDirectory.listFiles()) {
                    if (sourceSet.isDirectory() && sourceSet.getName().equals(SourceSet.MAIN_SOURCE_SET_NAME)) {
                        paths.add(sourceSet.toPath());
                    }
                }
            }
        }
    }

    private static boolean isFlagOn(byte walkingFlags, byte flag) {
        return (walkingFlags & flag) > 0;
    }

    private static byte clearFlag(byte flags, byte flag) {
        if ((flags & flag) > 0) {
            flags ^= flag;
        }
        return flags;
    }

    private static boolean isDependency(ResolvedArtifact a) {
        return ArtifactCoords.TYPE_JAR.equalsIgnoreCase(a.getExtension()) || "exe".equalsIgnoreCase(a.getExtension()) ||
                a.getFile().isDirectory();
    }

    /**
     * Creates an instance of Dependency and associates it with the ResolvedArtifact's path
     */
    static ResolvedDependencyBuilder toDependency(ResolvedArtifact a, int... flags) {
        return toDependency(a, PathList.of(a.getFile().toPath()), null, flags);
    }

    static ResolvedDependencyBuilder toDependency(ResolvedArtifact a, SourceSet s) {
        PathList.Builder resolvedPathBuilder = PathList.builder();

        for (File classesDir : s.getOutput().getClassesDirs()) {
            if (classesDir.exists()) {
                resolvedPathBuilder.add(classesDir.toPath());
            }
        }
        File resourceDir = s.getOutput().getResourcesDir();
        if (resourceDir != null && resourceDir.exists()) {
            resolvedPathBuilder.add(resourceDir.toPath());
        }

        return ResolvedDependencyBuilder
                .newInstance()
                .setResolvedPaths(resolvedPathBuilder.build())
                .setCoords(toArtifactCoords(a));
    }

    static ResolvedDependencyBuilder toDependency(ResolvedArtifact a, PathCollection paths, DefaultWorkspaceModule module,
            int... flags) {
        int allFlags = 0;
        for (int f : flags) {
            allFlags |= f;
        }
        return ResolvedDependencyBuilder.newInstance()
                .setCoords(toArtifactCoords(a))
                .setResolvedPaths(paths)
                .setWorkspaceModule(module)
                .setFlags(allFlags);
    }

    private static ArtifactCoords toArtifactCoords(ResolvedArtifact a) {
        final String[] split = a.getModuleVersion().toString().split(":");
        return new GACTV(split[0], split[1], a.getClassifier(), a.getType(), split.length > 2 ? split[2] : null);
    }

    private static ArtifactKey toAppDependenciesKey(String groupId, String artifactId, String classifier) {
        return new GACT(groupId, artifactId, classifier, ArtifactCoords.TYPE_JAR);
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DefaultReverseEngineering
{
    [Table("Store", Schema = "Sales")]
    public partial class Store
    {
        public Store()
        {
            Customer = new HashSet<Customer>();
        }

        [Key]
        public int BusinessEntityID { get; set; }
        public DateTime ModifiedDate { get; set; }
        public Guid rowguid { get; set; }
        public int? SalesPersonID { get; set; }

        [InverseProperty("Store")]
        public virtual ICollection<Customer> Customer { get; set; }
        [ForeignKey("BusinessEntityID")]
        [InverseProperty("Store")]
        public virtual BusinessEntity BusinessEntity { get; set; }
        [ForeignKey("SalesPersonID")]
        [InverseProperty("Store")]
        public virtual SalesPerson SalesPerson { get; set; }
    }
}


text:
'use strict';

/**
 * Class representing a UserCollaborator.
 */
class UserCollaborator {
  /**
   * Create a UserCollaborator.
   * @property {string} [email] The email address of the user.
   */
  constructor() {
  }

  /**
   * Defines the metadata of UserCollaborator
   *
   * @returns {object} metadata of UserCollaborator
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'UserCollaborator',
      type: {
        name: 'Composite',
        className: 'UserCollaborator',
        modelProperties: {
          email: {
            required: false,
            serializedName: 'email',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = UserCollaborator;


text:
package  ejb_generated;
import adapt.exceptions.InvariantException;

public class CfDCAudienceConstraints extends CfDCAudience{

	private String objectName;

	public String getObjectName() {
		return objectName;
	}

	public void setObjectName(String objectName) {
		this.objectName = objectName;
	}
}


text:
package com.cloudnative.reference.configuration;

import org.axonframework.contextsupport.spring.AnnotationDriven;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AnnotationDriven
public class RabbitConfiguration {

  @Value("${spring.rabbitmq.hostname}")
  private String hostname;

  @Value("${spring.rabbitmq.username}")
  private String username;

  @Value("${spring.rabbitmq.password}")
  private String password;

  @Value("${spring.application.exchange}")
  private String exchangeName;

  @Value("${spring.application.queue}")
  private String queueName;

  @Value("${spring.application.index}")
  private Integer index;

  @Bean
  public String uniqueQueueName() {
    return queueName + "." + index;
  }

  @Bean
  Queue eventStream(String uniqueQueueName) {
    return new Queue(uniqueQueueName, false, false, true);
  }

  @Bean
  FanoutExchange eventBusExchange() {
    return new FanoutExchange(exchangeName, true, false);
  }

  @Bean
  Binding binding(String uniqueQueueName) {
    return new Binding(uniqueQueueName, Binding.DestinationType.QUEUE, exchangeName, "*.*", null);
  }

  @Bean
  ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory(hostname);
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    return connectionFactory;
  }

  @Bean
  @Required
  RabbitAdmin rabbitAdmin(String uniqueQueueName) {
    RabbitAdmin admin = new RabbitAdmin(connectionFactory());
    admin.setAutoStartup(true);
    admin.declareExchange(eventBusExchange());
    admin.declareQueue(eventStream(uniqueQueueName));
    admin.declareBinding(binding(uniqueQueueName));
    return admin;
  }
}


text:
#ifndef _COLM_PROGRAM_H
#define _COLM_PROGRAM_H

#ifdef __cplusplus
extern "C" {
#endif

#include <colm/pdarun.h>

struct stack_block
{
	tree_t **data;
	int len;
	int offset;
	struct stack_block *next;
};

struct colm_sections
{
	struct lang_el_info *lel_info;
	long num_lang_els;

	struct struct_el_info *sel_info;
	long num_struct_els;

	struct prod_info *prod_info;
	long num_prods;

	struct region_info *region_info;
	long num_regions;

	code_t *root_code;
	long root_code_len;
	long root_frame_id;

	struct frame_info *frame_info;
	long num_frames;

	struct function_info *function_info;
	long num_functions;

	struct pat_cons_info *pat_repl_info;
	long num_patterns;

	struct pat_cons_node *pat_repl_nodes;
	long num_pattern_nodes;

	struct generic_info *generic_info;
	long num_generics;

	long argv_generic_id;
	long stds_generic_id;

	const char **litdata;
	long *litlen;
	head_t **literals;
	long num_literals;

	CaptureAttr *capture_attr;
	long num_captured_attr;

	struct fsm_tables *fsm_tables;
	struct pda_tables *pda_tables;
	int *start_states;
	int *eof_lel_ids;
	int *parser_lel_ids;
	long num_parsers;

	long global_size;

	long first_non_term_id;
	long first_struct_el_id;

	long integer_id;
	long string_id;
	long any_id;
	long eof_id;
	long no_token_id;
	long global_id;
	long argv_el_id;
	long stds_el_id;
	long struct_inbuilt_id;
	long struct_input_id;
	long struct_stream_id;

	void (*fsm_execute)( struct pda_run *pda_run, struct input_impl *input_stream );
	void (*send_named_lang_el)( struct colm_program *prg, tree_t **tree,
			struct pda_run *pda_run, struct input_impl *input_stream );
	void (*init_bindings)( struct pda_run *pda_run );
	void (*pop_binding)( struct pda_run *pda_run, parse_tree_t *tree );

	tree_t **(*host_call)( program_t *prg, long code, tree_t **sp );

	void (*commit_reduce_forward)( program_t *prg, tree_t **root, struct pda_run *pda_run, parse_tree_t *pt );
	long (*commit_union_sz)( int reducer );
	void (*init_need)();
	int (*reducer_need_tok)( program_t *prg, struct pda_run *pda_run, int id );
	int (*reducer_need_ign)( program_t *prg, struct pda_run *pda_run );
	void (*read_reduce)( program_t *prg, int reducer, input_t *input );
};

struct heap_list
{
	struct colm_struct *head;
	struct colm_struct *tail;
};

struct colm_program
{
	long active_realm;

	int argc;
	const char **argv;
	const int *argl;

	unsigned char ctx_dep_parsing;
	unsigned char reduce_clean;
	struct colm_sections *rtd;
	struct colm_struct *global;
	int induce_exit;
	int exit_status;

	struct pool_alloc kid_pool;
	struct pool_alloc tree_pool;
	struct pool_alloc parse_tree_pool;
	struct pool_alloc head_pool;
	struct pool_alloc location_pool;

	tree_t *true_val;
	tree_t *false_val;

	struct heap_list heap;

	stream_t *stdin_val;
	stream_t *stdout_val;
	stream_t *stderr_val;

	tree_t *error;

	struct run_buf *alloc_run_buf;

	/* Current stack block limits. Changed when crossing block boundaries. */
	tree_t **sb_beg;
	tree_t **sb_end;
	long sb_total;
	struct stack_block *reserve;
	struct stack_block *stack_block;
	tree_t **stack_root;

	/* Returned value for main program and any exported functions. */
	tree_t *return_val;

	void *red_ctx;

	/* This can be extracted for ownership transfer before a program is deleted. */
	const char **stream_fns;
};

#ifdef __cplusplus
}
#endif

#endif /* _COLM_PROGRAM_H */


text:
<?xml version="1.0" encoding="utf-8"?>
<transition
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/transparent"/>
    <item android:drawable="@drawable/bg_search_view_expanded"/>
</transition>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
J. Proc. Roy. Soc. New South Wales 55:200. 1922

#### Original name
null

### Remarks
null


text:
using System;
using System.Collections.Generic;
using ValueTuples.Reflection;

namespace ValueTuples.Sample
{
    public class Mage : Unit
    {
        public string Spell { get; set; }

        public Mage() { }
        public Mage(int id, string name, string spell) : base(id, name) { Spell = spell; }

        static Mage()
        {
            TypeRepository.Register(typeof(Mage), new MageInfo());
        }
    }

    internal struct MageAccessor : IRecordAccessor
    {
        Mage _value;

        public MageAccessor(Mage value) { _value = value; }

        public object Get(string key)
        {
            switch (key)
            {
                case "Id": return _value.Id;
                case "Name": return _value.Name;
                case "Spell": return _value.Spell;
                default: return null;
            }
        }

        public object Get(int index)
        {
            switch (index)
            {
                case 0: return _value.Id;
                case 1: return _value.Name;
                case 2: return _value.Spell;
                default: return null;
            }
        }

        public void Set(string key, object value)
        {
            switch (key)
            {
                case "Id": _value.Id = (int)value; break;
                case "Name": _value.Name = (string)value; break;
                case "Spell": _value.Spell = (string)value; break;
            }
        }

        public void Set(int index, object value)
        {
            switch (index)
            {
                case 0: _value.Id = (int)value; break;
                case 1: _value.Name = (string)value; break;
                case 2: _value.Spell = (string)value; break;
            }
        }
    }

    internal class MageInfo : RecordTypeInfo
    {
        public override Type Type => typeof(Mage);

        public override int? Discriminator => (int)UnitType.Mage;

        private static readonly RecordFieldInfo[] _fields =
        {
            new RecordFieldInfo(TypeRepository.Int32, "Id", 0),
            new RecordFieldInfo(TypeRepository.String, "Name", 1),
            new RecordFieldInfo(TypeRepository.String, "Spell", 2),
        };

        public override IEnumerable<RecordFieldInfo> Fields => _fields;

        public override object GetInstance() => new Mage();
        public override Array GetArray(int length) => new Mage[length];

        public override IRecordAccessor GetAccessor(object instance) => new MageAccessor((Mage)instance);
    }
}


text:
package rapture.common.model;

import rapture.common.DocumentAttributeFactory;

/**
 * Attribute for link attributes of a document. These usually represent links to
 * other documents in Rapture. Represented as /type/doc/$link
 *
 * @author dukenguyen
 *
 */
public class LinkDocumentAttribute extends BaseDocumentAttribute {

    @Override
    public String getAttributeType() {
        return DocumentAttributeFactory.LINK_TYPE;
    }

}


text:
package vgrechka.phizdetsidea.phizdets.psi.resolve;

public interface PyOverridingReferenceResolveProvider extends PyReferenceResolveProvider {
}


text:
using System;
using System.Xml;
using FluentNHibernate.Mapping.Providers;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Utils;
using FluentNHibernate.Visitors;

namespace FluentNHibernate.Mapping
{
    public interface IFilter : IFilterMappingProvider
    {
        string Condition { get; }
        string Name { get; }
    }

    /// <summary>
    /// Maps to the Filter element in NH 2.0
    /// </summary>
    public class FilterPart : IFilter
    {
        readonly string filterName;
        readonly string condition;
        readonly AttributeStore attributes = new AttributeStore();

        public FilterPart(string name) : this(name, null) { }

        public FilterPart(string name, string condition)
        {
            filterName = name;
            this.condition = condition;
        }

        public string Condition
        {
            get { return condition; }
        }
        public string Name
        {
            get { return filterName; }
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            if (obj.GetType() != typeof(FilterPart)) return false;
            return Equals((FilterPart)obj);
        }

        FilterMapping IFilterMappingProvider.GetFilterMapping()
        {
            var mapping = new FilterMapping();
            mapping.Set(x => x.Name, Layer.Defaults, Name);
            mapping.Set(x => x.Condition, Layer.Defaults, Condition);
            return mapping;
        }

        public bool Equals(FilterPart other)
        {
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
            return Equals(other.filterName, filterName) && Equals(other.condition, condition) && Equals(other.attributes, attributes);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int result = (filterName != null ? filterName.GetHashCode() : 0);
                result = (result * 397) ^ (condition != null ? condition.GetHashCode() : 0);
                result = (result * 397) ^ (attributes != null ? attributes.GetHashCode() : 0);
                return result;
            }
        }
    }
}


text:
using ISAAR.MSolve.Analyzers.Optimization;
using ISAAR.MSolve.Analyzers.Optimization.Algorithms.Metaheuristics.ParticleSwarmOptimization;
using ISAAR.MSolve.Analyzers.Optimization.Convergence;
using ISAAR.MSolve.Analyzers.Optimization.Logging;
using ISAAR.MSolve.Analyzers.Optimization.Problem;
using System;

namespace ISAAR.MSolve.SamplesConsole.Optimization.BenchmarkFunctions
{
    class OptimizationTestPSO
    {
        public static void Run()
        {
            OptimizationProblem optimizationProblem = new GoldsteinPrice();

            ParticleSwarmOptimizationAlgorithm.Builder builder = new ParticleSwarmOptimizationAlgorithm.Builder(optimizationProblem);

            builder.SwarmSize = 50;
            builder.PhiP = 2.0;
            builder.PhiG = 2.0;
            builder.ConvergenceCriterion = new MaxFunctionEvaluations((int)10E3);
            builder.Logger = new NoLogger();

            IOptimizationAlgorithm pso = builder.Build();
            IOptimizationAnalyzer analyzer = new OptimizationAnalyzer(pso);
            analyzer.Optimize();

            // Print results
            Console.WriteLine("\n Best Position:");
            for (int i = 0; i < optimizationProblem.Dimension; i++)
            {
                Console.WriteLine(String.Format(@"  x[{0}] = {1} ", i, pso.BestPosition[i]));
            }
            Console.WriteLine(String.Format(@"Best Fitness: {0}", pso.BestFitness));

            Console.Write("\nEnter any key to exit: ");
            Console.Read();
        }
    }
}


text:
using System.Windows.Controls;

namespace AntYecai.Views
{
    /// <summary>
    /// RankingListView.xaml 的交互逻辑
    /// </summary>
    public partial class RankingListView : UserControl
    {
        public RankingListView()
        {
            InitializeComponent();
        }
    }
}


text:
<?php namespace Vultuk\BusinessBox\Contracts;

/**
 * Interface to be used in Encryption classes to ensure required
 * functionality is available
 *
 * Interface Encrypt
 * @package Vultuk\BusinessBox\Contracts
 */
interface Encrypt
{
    /**
     * Method to be called statically to encrypt in one easy call
     *
     * @param $data
     * @param $publicKey
     * @param $secretKey
     * @param int $apiVersion
     * @return string
     */
    public static function encrypt($data, $publicKey, $secretKey, $apiVersion = 1);

    /**
     * Sets the procedure to encrypt the data
     *
     * @param $data
     * @return string
     * @throws \Exception
     */
    public function encryptData($data);

}


text:
-- Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
-- Copyright [2016-2022] EMBL-European Bioinformatics Institute
--
-- 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.

/**
@header patch_84_85_q.sql - Rename table regulatory_attribute to regulatory_evidence
@desc   Rename table regulatory_attribute to regulatory_evidence
*/

rename table regulatory_attribute to regulatory_evidence;

insert into meta (species_id, meta_key, meta_value) values (null, 'patch', 'patch_84_85_q.sql|Rename table regulatory_attribute to regulatory_evidence.');


text:
import hashlib, os

def get_hash_of_string (string, algorithm='MD5'):
  """This function takes a string and hashes it using an algorithm.

  Acknowledgments:
  Addition of multiple hashing algorithms courtesy of Anthony Capece, Elvis Gadtaula,
  Nick Parenti, Jordan Polun, and Christopher Tafel.
  Dictionary and associated functionality is courtesy of Jordan Polun.
  Documentation is courtesy of Jazlin Perez and Jordan Polun.

  :param string: this is the string that will be hashed.
  :type string: str.
  :param algorithm: The hashing algorithm to be used. Defaults to 'MD5'.
  :type algorithm: str.
  :returns: str -- The hash of the string.
  """
  hashing_algorithms = {'MD5'   :hashlib.md5(),
                        'SHA1'  :hashlib.sha1(),
                        'SHA224':hashlib.sha224(),
                        'SHA256':hashlib.sha256(),
                        'SHA384':hashlib.sha384(),
                        'SHA512':hashlib.sha512()
                       }
  if algorithm in hashing_algorithms:
    binary_string = convert_string_to_binary(string)
    hash_object = hashing_algorithms[algorithm]
    hash_object.update(binary_string)
    hash_digest = hash_object.hexdigest()
  else:
    hash_digest = ''
  return hash_digest

def read_binary_file (file_path):
  """This function will read and hash the contents of a file.

  Acknowledgments:
  Documentation is courtesy of Jazlin Perez and Jordan Polun.
  Thanks to Joseph Darocha for fixing the return error.

  :param file_path: this is the path to the file to be read.
  :type file_path: str.
  :returns: str -- the content of the file to be read
  """
  try:
    file_object = open(file_path,'rb')
    file_contents = file_object.read()
    file_object.close()
    return file_contents
  except:
    raise

def get_hash_of_binary_file_contents (file_path, algorithm='MD5'):
  """This function will read and hash the contents of a file.

  :param file_path: The path to the file to be hashed.
  :type file_path: str.
  :param algorithm: The hashing algorithm to be used. Defaults to 'MD5'.
  :type algorithm: str.
  :returns: str -- The hash of the contents of the file.
  """
  file_contents = read_binary_file(file_path)
  file_hash = get_hash_of_string(file_contents, algorithm)
  return file_hash

def get_hashes_of_files_in_directory (directory, algorithm='MD5'):
  """This function will get the hashes of all files in a directory.

  Acknowledgments:
  This function is courtesy of Minnie Kumar, Kyle O'Neill, Lawrence Rosenstadt,
  and Tiffany Xu.
  """
  hash_dictionary = {}
  if os.path.isdir(directory):
    for file_name in os.listdir(directory):
      file_path = os.path.join(directory, file_name)
      if os.path.isfile(file_path):
        file_hash = get_hash_of_binary_file_contents(file_path)
        hash_dictionary[file_path] = file_hash
  return hash_dictionary

def convert_string_to_binary (string):
  """This function attempts to convert a string to binary.

  Acknowledgments:
  Thanks to Minnie Kumar for finding an error in the
  get_hash_of_string function and providing a solution.

  Code based an answer from Elizafox on Stack Overflow:
  http://stackoverflow.com/questions/34869889/what-is-the-proper-way-to-determine-if-an-object-is-a-bytes-like-object-in-pytho
  """
  try:
    string = string.encode()
  except:
    pass
  return string

def do_files_have_same_content (file_1, file_2, algorithm='MD5'):
  """This function checks the hashes of the contents of two files. It returns
  a boolean.

  Acknowledgments:
  Thanks to Ryan Dorrien and Kyle O'Neill for working on this function.
  """
  file_1_hash = get_hash_of_binary_file_contents (file_1)
  file_2_hash = get_hash_of_binary_file_contents (file_2)
  if file_1_hash == file_2_hash:
    return True
  else:
    return False


text:
import Immutable from 'immutable'
import {load} from '@/lib/storage.js'
import {CHANGE_CONFIG} from './actions'

const configData = load('config')
const initialState = Immutable.fromJS({
  reportName: configData.reportName || '未命名周报',
  userName: configData.userName || '未知用户'
})

export default (state = initialState, action) => {
  const {type, config} = action
  switch (type) {
    case CHANGE_CONFIG:
      return state.update(config.key, val => config.value)
    default:
      return state
  }
}


text:
#import "AIRequest.h"

/*!
 * Sound level handler definition for AIVoiceRequest.
 *
 * @param request The request called handler.
 * @param level Noise level in range from 0 to 1.
 */
typedef void(^SoundLevelHandleBlock)(AIRequest *request, float level);

/*!
 * Record begin handler definition for AIVoiceRequest.
 *
 * @param request The request called handler.
 */
typedef void(^SoundRecordBeginBlock)(AIRequest *request);

/*!
 * Record end handler definition for AIVoiceRequest.
 *
 * @param request The request called handler.
 */
typedef void(^SoundRecordEndBlock)(AIRequest *request);

@interface AIVoiceRequest : AIRequest

/*!

 @property soundLevelHandleBlock

 @discussion Sound level handler. Default is nil.

 */
@property(nonatomic, copy) SoundLevelHandleBlock soundLevelHandleBlock;

/*!

 @property soundRecordBeginBlock

 @discussion Record begin handler. Default is nil.

 */
@property(nonatomic, copy) SoundRecordBeginBlock soundRecordBeginBlock;

/*!

 @property soundRecordEndBlock

 @discussion Record end handler. Default is nil.

 */
@property(nonatomic, copy) SoundRecordEndBlock soundRecordEndBlock;

/*!

 @property useVADForAutoCommit

 @discussion Use Voice Activity Detection for detect end of speech. Default is YES.

 */
@property(nonatomic, assign) BOOL useVADForAutoCommit;

/*!
 * Manually stop listening and send request to server.
 */
- (void)commitVoice;

@end


text:
package org.beigesoft.converter;

public interface IConverter<FR, TO> {

  public TO convert(FR from);
}


text:
package com.ayuget.redface.ui.activity;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.ayuget.redface.R;
import com.ayuget.redface.RedfaceNotifications;
import com.ayuget.redface.data.api.model.PrivateMessage;
import com.ayuget.redface.data.api.model.Topic;
import com.ayuget.redface.data.rx.EndlessObserver;
import com.ayuget.redface.data.rx.SubscriptionHandler;
import com.ayuget.redface.data.state.CategoriesStore;
import com.ayuget.redface.ui.UIConstants;
import com.ayuget.redface.ui.event.EditPostEvent;
import com.ayuget.redface.ui.event.PostActionEvent;
import com.ayuget.redface.ui.event.PrivateMessageContextItemSelectedEvent;
import com.ayuget.redface.ui.event.QuotePostEvent;
import com.ayuget.redface.ui.fragment.DetailsDefaultFragment;
import com.ayuget.redface.ui.fragment.PrivateMessageListFragment;
import com.ayuget.redface.ui.fragment.TopicFragment;
import com.ayuget.redface.ui.fragment.TopicFragmentBuilder;
import com.ayuget.redface.ui.misc.PagePosition;
import com.ayuget.redface.ui.misc.SnackbarHelper;
import com.ayuget.redface.util.GoToPageDialog;
import com.squareup.otto.Subscribe;

import javax.inject.Inject;

import timber.log.Timber;

public class PrivateMessagesActivity extends MultiPaneActivity implements PrivateMessageListFragment.OnPrivateMessageClickedListener {
    private static final String DEFAULT_FRAGMENT_TAG = "default_fragment";

    private static final String DETAILS_DEFAULT_FRAGMENT_TAG = "details_default_fragment";

    private static final String PM_LIST_FRAGMENT_TAG = "private_messages_list_fragment";

    private static final String PM_FRAGMENT_TAG = "private_message_fragment";

    private static final String ARG_TOPIC = "topic";

    private SubscriptionHandler<Topic, String> quoteHandler = new SubscriptionHandler<>();

    @Inject
    CategoriesStore categoriesStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_private_messages, savedInstanceState);

        if (getIntent() != null) {
            PrivateMessage privateMessage = getIntent().getParcelableExtra(UIConstants.ARG_SELECTED_PM);

            if (privateMessage != null) {
                Timber.d("Received private message : '%s'", privateMessage);
                loadPrivateMessage(privateMessage, privateMessage.getPagesCount(), PagePosition.bottom());
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.getExtras() != null) {
            Timber.d("Trying to display private message from intent");
            PrivateMessage privateMessage = intent.getExtras().getParcelable(UIConstants.ARG_SELECTED_PM);

            if (privateMessage != null) {
                Timber.d("Received private message : '%s'", privateMessage);

                loadPrivateMessage(privateMessage, privateMessage.getPagesCount(), PagePosition.bottom());
            }
        }
    }

    @Override
    protected void onSetupUiState() {
        Timber.d("Setting up initial state");

        PrivateMessageListFragment pmListFragment = PrivateMessageListFragment.newInstance();
        pmListFragment.setOnPrivateMessageClickedListener(this);

        if (isTwoPaneMode()) {
            DetailsDefaultFragment detailsDefaultFragment = DetailsDefaultFragment.newInstance();

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, pmListFragment, DEFAULT_FRAGMENT_TAG)
                    .replace(R.id.details_container, detailsDefaultFragment, DETAILS_DEFAULT_FRAGMENT_TAG)
                    .commit();
        }
        else {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.container, pmListFragment, DEFAULT_FRAGMENT_TAG)
                    .commit();
        }
    }

    @Override
    protected void onRestoreUiState(Bundle savedInstanceState) {
        Timber.d("Restoring UI state");

        PrivateMessageListFragment pmListFragment = (PrivateMessageListFragment) getSupportFragmentManager().findFragmentByTag(PM_LIST_FRAGMENT_TAG);
        if (pmListFragment != null) {
            pmListFragment.setOnPrivateMessageClickedListener(this);
        } else {
            Fragment defaultFragment = getSupportFragmentManager().findFragmentByTag(DEFAULT_FRAGMENT_TAG);
            if (defaultFragment instanceof PrivateMessageListFragment) {
                ((PrivateMessageListFragment)defaultFragment).setOnPrivateMessageClickedListener(this);
            }
        }
    }

    @Override
    public void onPrivateMessageClicked(PrivateMessage privateMessage) {
        int pageToLoad;
        PagePosition pagePosition;

        if (privateMessage.hasUnreadMessages()) {
            pageToLoad = privateMessage.getPagesCount();
            pagePosition = new PagePosition(PagePosition.BOTTOM);
        }
        else {
            pageToLoad = 1;
            pagePosition = new PagePosition(PagePosition.BOTTOM);
        }

        loadPrivateMessage(privateMessage, pageToLoad, pagePosition);
    }

    @Subscribe
    public void onPrivateMessageContextItemSelected(PrivateMessageContextItemSelectedEvent event) {
        Timber.d("Received private message contextItem event : %d for PM %s", event.getItemId(), event.getPrivateMessage().toString());

        switch (event.getItemId()) {
            case UIConstants.TOPIC_ACTION_GO_TO_FIRST_PAGE:
                loadPrivateMessage(event.getPrivateMessage(), 1, new PagePosition(PagePosition.TOP));
                break;
            case UIConstants.TOPIC_ACTION_GO_TO_SPECIFIC_PAGE:
                GoToPageDialog goToPageDialog = new GoToPageDialog(this, themeManager, event.getPrivateMessage().getPagesCount(),
                        new GoToPageDialog.GoToPageDialogCallback() {
                            @Override
                            public void onSuccess(int pageNumber) {
                                loadPrivateMessage(event.getPrivateMessage(), pageNumber, new PagePosition(PagePosition.TOP));
                            }

                            @Override
                            public void onError() {
                                SnackbarHelper.makeError(PrivateMessagesActivity.this, R.string.invalid_page_number).show();
                            }
                        });
                goToPageDialog.show();
                break;
            case UIConstants.TOPIC_ACTION_GO_TO_LAST_PAGE:
                loadPrivateMessage(event.getPrivateMessage(),
                        event.getPrivateMessage().getPagesCount(),
                        new PagePosition(PagePosition.BOTTOM));
                break;
            case UIConstants.TOPIC_ACTION_REPLY_TO_TOPIC:
                Topic pmAsTopic = event.getPrivateMessage().asTopic()
                        .withCategory(categoriesStore.getPrivateMessagesCategory());
                Intent intent = new Intent(this, ReplyActivity.class);
                intent.putExtra(ARG_TOPIC, pmAsTopic);
                startActivity(intent);
                break;
        }

    }

    /**
     * Code is duplicated with TopicsActivity because Otto doesn't support settings @Subscribe annotations
     * on base classes (pull request #135 still not merged)
     */
    @Subscribe
    public void onQuotePost(final QuotePostEvent event) {
        subscribe(quoteHandler.load(event.getTopic(), mdService.getQuote(userManager.getActiveUser(), event.getTopic(), event.getPostId()), new EndlessObserver<String>() {
            @Override
            public void onNext(String quoteBBCode) {
                startReplyActivity(event.getTopic(), quoteBBCode);
            }
        }));
    }

    /**
     * fixme: Code is duplicated with TopicsActivity because Otto doesn't support settings @Subscribe annotations
     * on base classes (pull request #135 still not merged)
     */
    @Subscribe public void onEditPost(final EditPostEvent event) {
        subscribe(quoteHandler.load(event.getTopic(), mdService.getPostContent(userManager.getActiveUser(), event.getTopic(), event.getPostId()), new EndlessObserver<String>() {
            @Override
            public void onNext(String messageBBCode) {
                startEditActivity(event.getTopic(), event.getPostId(), messageBBCode);
            }
        }));
    }

    /**
     * fixme: Code is duplicated with TopicsActivity because Otto doesn't support settings @Subscribe annotations
     * on base classes (pull request #135 still not merged)
     */
    @Subscribe public void onPostActionEvent(final PostActionEvent event) {
        switch (event.getPostAction()) {
            case DELETE:
                Timber.d("About to delete post");
                new AlertDialog.Builder(this)
                        .setTitle(R.string.post_delete_confirmation)
                        .setPositiveButton(R.string.post_delete_yes, (dialog, which) -> deletePost(event.getTopic(), event.getPostId()))
                        .setNegativeButton(R.string.post_delete_no, null)
                        .show();
                break;
            default:
                Timber.e("Action not handled");
                break;
        }
    }

    /**
     * Loads a private message in the appropriate pane.
     */
    private void loadPrivateMessage(PrivateMessage privateMessage, int page, PagePosition pagePosition) {
        Timber.d("Loading private message '%s' at page '%d'", privateMessage.getSubject(), page);

        RedfaceNotifications.dismissPrivateMessageNotificationIfNeeded(this, privateMessage);

        // Mask private message as a regular topic (kinda ugly, btw...)
        Topic pmAsTopic = privateMessage.asTopic().withCategory(categoriesStore.getPrivateMessagesCategory());

        TopicFragment topicFragment = new TopicFragmentBuilder(page, pagePosition, pmAsTopic).build();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        int topicFragmentContainer = isTwoPaneMode() ? R.id.details_container : R.id.container;

        if (!isTwoPaneMode()) {
            Timber.d("Setting slide animation for topicFragment (private message)");
            transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
        }

        transaction.replace(topicFragmentContainer, topicFragment, PM_FRAGMENT_TAG);
        transaction.addToBackStack(PM_FRAGMENT_TAG);
        transaction.commit();
    }

    @Override
    protected void requestMasterPaneRefresh() {
        PrivateMessageListFragment privateMessageListFragment = (PrivateMessageListFragment) getSupportFragmentManager().findFragmentByTag(PM_LIST_FRAGMENT_TAG);
        if (privateMessageListFragment != null) {
            privateMessageListFragment.refreshData();
        }
    }
}


text:
namespace shaka {

namespace media {
class DecoderIntegration;
class DecoderDecryptIntegration;
}  // namespace media

namespace eme {

class ClearKeyImplementation final : public Implementation {
 public:
  explicit ClearKeyImplementation(ImplementationHelper* helper);
  ~ClearKeyImplementation() override;

  bool GetExpiration(const std::string& session_id,
                     int64_t* expiration) const override;

  bool GetKeyStatuses(const std::string& session_id,
                      std::vector<KeyStatusInfo>* statuses) const override;

  void SetServerCertificate(EmePromise promise, Data cert) override;

  void CreateSessionAndGenerateRequest(
      EmePromise promise,
      std::function<void(const std::string&)> set_session_id,
      MediaKeySessionType session_type, MediaKeyInitDataType init_data_type,
      Data data) override;

  void Load(const std::string& session_id, EmePromise promise) override;

  void Update(const std::string& session_id, EmePromise promise,
              Data data) override;

  void Close(const std::string& session_id, EmePromise promise) override;

  void Remove(const std::string& session_id, EmePromise promise) override;

  DecryptStatus Decrypt(const FrameEncryptionInfo* info, const uint8_t* data,
                        size_t data_size, uint8_t* dest) const override;

 private:
  struct Session {
    struct Key {
      Key(std::vector<uint8_t> key_id, std::vector<uint8_t> key);
      ~Key();

      // TODO: Consider storing keys in OpenSSL key objects instead.
      std::vector<uint8_t> key_id;
      std::vector<uint8_t> key;  // This contains the raw AES key.
    };

    Session();
    ~Session();

    Session(Session&&);
    Session(const Session&) = delete;
    Session& operator=(Session&&);
    Session& operator=(const Session&) = delete;

    std::list<Key> keys;
    bool callable = false;
  };

  friend class ClearKeyImplementationTest;
  friend class media::DecoderIntegration;
  friend class media::DecoderDecryptIntegration;

  DecryptStatus DecryptBlock(const FrameEncryptionInfo* info,
                             const uint8_t* data, size_t data_size,
                             size_t block_offset, uint8_t* dest,
                             util::Decryptor* decryptor) const;

  void LoadKeyForTesting(std::vector<uint8_t> key_id, std::vector<uint8_t> key);

  mutable std::mutex mutex_;
  std::unordered_map<std::string, Session> sessions_;
  ImplementationHelper* helper_;
  uint32_t cur_session_id_;
};

}  // namespace eme
}  // namespace shaka

#endif  // SHAKA_EMBEDDED_EME_CLEARKEY_FACTORY_H_


text:
package core.learning.features.dictionary;

import core.language.dictionary.Dictionary;
import core.language.word.Word;
import core.learning.features.Feature;

public class WordFrequency extends Feature {

    public WordFrequency(Word word, Dictionary dictionary) {
        this.value = dictionary.getMentionCount(word.getText());
    }

    @Override
    public String getName() {
        return "WordFrequency";
    }
}